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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
SebLague/Tiny-Chess-Bot-Challenge-Results | 13,042 | Bots/Bot_494.cs | namespace auto_Bot_494;
using ChessChallenge.API;
using System;
using System.Linq;
/// <summary>
/// Note I am quite confident that this bot isn't going to win but hopefully this if going to be quite a strong bot that is quite token compact,
/// as a side note, I am not really good at making chess bots as some of the features and implementation did come from another open source bot.
/// Where I am most confident in is token optimization as I have been programming in C# for around 5 years and know the ins and outs of the language
/// as well as some of the low level functions
/// </summary>
public class Bot_494 : IChessBot
{
Move bestrootmove;
//Transpostion Table (ulong key, Move move, int depth, int score, int bound)
(ulong, Move, int, int, int)[] tt;
//decompressed is a lookup table that is condensed into a decimal array where each byte of the 768 byte array contains the piece values and square scores
//for "midgame" and "endgame" note the true in ToByteArray to specify that our numbers are encoded as positive numbers, then the numbers are expanded and shifted
//to a more reasonable scale
//This lookup table I had many ideas of how to reduce the token count, most just made the bot play worse than before
//One idea that came close and didn't have time to make was to make the "midgame" and "endgame" values into a 32 bit value where the upper 16 bits were "midgame"
//and the lower 16 bits were "endgame" this would reduce the size of the lookup table in half and make the eval function only look at the array once per piece
//instead of twice. Sadly didn't have enough time to test this out
//We keep the lookup table to the class as it would be too expensive to compute this table each time we call Think
int[] decompressed = new[] { 17078798320628004012597322274m, 9333125444692524849785552433m, 11491000994506709063692395807m,
9643767193844008032108028710m, 10563755001543880993352327706m, 11495851031481492121365652002m, 15850506097695417493575191372m, 12427937542397017557944447025m,
11493437920583430004736796456m, 10876881067323431980510749733m, 24859477897109925765908342053m, 27036909915508042251286037864m, 31682764487639182077742770256m,
27659464247841063978382813795m, 27960410978821928488923912277m, 26410591744955314614102875738m, 24227233657148759196861941313m, 21444286532810235342995671116m,
25786752725013150989425004362m, 22682231331427084577713115730m, 23299945053073219425472891461m, 29519963194250865918452386377m, 32624569738373786526510048347m,
29829533466370946603768441960m, 31069867597095993848715502431m, 30146253011723926646968117092m, 24854670993176552123620221017m, 24238128324308118753512411216m,
25789199040555512973780734034m, 24857121993181397119461905493m, 25165369650172923337596162383m, 24236914657745363333492396114m, 41943079200831958700934595456m,
38849452158499688575890589835m, 37592098248375645279755138932m, 35426935883370435720997730427m, 38833674582847172418427254384m, 40392046356039515068758588285m,
40392041615081608870935954563m, 40080129271922804546630353026m, 40078920327510921073207247490m, 39768216928834929700252909183m, 76125997110477970443776196991m,
78911423653508744625184898303m, 74256969468557107527503114224m, 75190288645094419995357804274m, 75502186655351228764179723247m, 71777467389509964344098748148m,
72079651250512640499100476637m, 69909643830162646583757628652m, 72385518927899158068905436383m, 69597726653308368900466403046m, 66184881655824445429035621082m,
5899595834933605395550886110m, 3733262359571037410193772566m, 2491643504635523350337491211m, 1870269873878609464820109317m, 5592547620763608038526224646m,
3728365007998395665681160205m, 5596231326173110746976686861m, 6834157087608497328734147602m, 4045165369473914621557872406m, 5900828501784335416611180300m,
1870269819115403136465834259m}.SelectMany(x => new System.Numerics.BigInteger(x).ToByteArray(true)).Select(x => (int)(x * 4.524) - 74).ToArray();
public Move Think(Board board, Timer timer)
{
//It doesn't reallocate the array if the size is the same
//(see https://source.dot.net/#System.Private.CoreLib/src/libraries/System.Private.CoreLib/src/System/Array.cs,71074deaf111c4e3,references)
//and saves 3 tokens over just using new (ulong, Move, int, int, int)
//Sadly using alias for tuples (see https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-12.0/using-alias-types) is a C# 12 feture
//.Net 6 by default uses C# 10 if a C# version isn't specified in the project config
Array.Resize(ref tt, 1_000_000);
var killermoves = new Move[512]; //We allocate new arrays for killer moves and history as the GC penalty won't be that large (hopefully)
var history = new int[2, 7, 64];
//Spend no more than
int depth = 1, timeallocated = timer.MillisecondsRemaining / 30, alpha = -30_300, beta = 30_300, eval;
//Itterative deepening with a asperation window for time control
for (; ; )
{
//Do a search
eval = Search(alpha, beta, depth, 0, true);
//Out of time check
if (timer.MillisecondsElapsedThisTurn >= timeallocated) return bestrootmove;
//If the evaluation is outside alpha or beta, do a re-search with a wider upper and lower bound
if (eval <= alpha) alpha -= 62;
else if (eval >= beta) beta += 62;
else
{
//Best case if our narrow search result is in between alpha and beta. Then we can go to the next depth
alpha = eval - 17;
beta = eval + 17;
depth++;
}
}
//We make use of a lot of local function so we don't store variables in the class, we pay a small cost of putting all captured variables into a struct and passing
//the struct by reference
//(https://sharplab.io/#v2:D4AQTABCCMDsCwAoA3ki6oBYoFYAuAlgPYB2AFAJRoaqIb0QEl4QCGEAvBDgNzUONmEAEacIsPnQER+DJiwCSJEgFMATiHzFyFTgD42EANQjJ0mVPQBfJFaA)
//Also note that null window search, "search", and quiescence search are all packed into 1 function to save tokens
int Search(int alpha, int beta, int depth, int ply, bool allownull)
{
//Variable initialization
ulong key = board.ZobristKey;
bool qsearch = depth <= 0, notRoot = ply > 0, incheck = board.IsInCheck(), canEFP = false;
Move bestMove = default;
int best = -30_300, movelooked = 0, score = 0, origalpha = alpha, moveused = 0;
if (notRoot && board.IsRepeatedPosition()) return 0; // Check for repetition
var (_key, _move, _depth, _score, _bound) = tt[key % 1_000_000]; //Deconstruct the entry into diffrent variables to save tokens
// TT cutoffs |exact score| | lower bound, fail high | | upper bound, fail low |
if (notRoot && _key == key && _depth >= depth && (_bound == 3 || _bound == 2 && _score >= beta || _bound == 1 && _score <= alpha)) return _score;
//Check extentions
if (incheck) depth++;
int localsearch(int newalpha, int r = 1, bool _allownull = true) => score = -Search(-newalpha, -alpha, depth - r, ply + 1, _allownull);
#region QSearshAndNullWindowSearch
if (qsearch)
{
best = Eval();
if (best >= beta) return best;
alpha = Math.Max(alpha, best);
}
else if (!incheck && beta - alpha == 1) //Only do this block if we are in a null window search
{
int staticeval = Eval();
//Reverse Futility Pruning, done before Extended Futility Pruning
if (depth <= 10 && staticeval - 96 * depth >= beta) return staticeval;
if (depth >= 2 && allownull)
{
board.ForceSkipTurn();
localsearch(beta, 3 + (depth >> 2), false); //Null move pruning, don't look at moves that are worse than not doing anything
board.UndoSkipTurn();
// Failed high on the null move
if (score >= beta) return score;
}
//Extended Futility Pruning, found that 128 works as a constant to multiply with depth
canEFP = depth <= 8 && staticeval + depth * 128 <= alpha;
}
#endregion
//Note we can't use var for the type for some reason the default type for a stackalloc expression is a pointer type which is unsafe
Span<Move> moves = stackalloc Move[218];
board.GetLegalMovesNonAlloc(ref moves, qsearch); // Generate moves, only captures if we are in qsearch
Span<int> scores = stackalloc int[moves.Length];
#region MoveSorting
//Score the Moves | Transposition table | Most Valuable Victim, Least Valuable Aggressor | Killer Moves | History Moves |
foreach (Move move in moves) scores[movelooked++] = -(move == _move ? 9_000_000 : move.IsCapture ? 1_000_000 * (int)move.CapturePieceType - (int)move.MovePieceType : killermoves[ply] == move ? 900_000 : history[ply & 1, (int)move.MovePieceType, move.TargetSquare.Index]);
scores.Sort(moves); //Sort to see what moves we should look at first
#endregion
#region SearchMoves
foreach (Move item in moves)
{
if (timer.MillisecondsElapsedThisTurn >= timeallocated && depth > 1) return 30_000;
//Where Extended Futility Pruning is used to skip looking into moves
if (canEFP && !(moveused == 0 || item.IsCapture || item.IsPromotion)) continue;
board.MakeMove(item);
#region PV&LMR
if (qsearch || moveused++ == 0 || ((moveused < 6 || depth < 2 || localsearch(alpha + 1, 3) > alpha) && localsearch(alpha + 1) < beta)) localsearch(beta);
#endregion
board.UndoMove(item);
if (score <= best) continue; //If the move isn't the best seen so far, just continue
if (!notRoot) bestrootmove = item;
best = score;
bestMove = item;
alpha = Math.Max(alpha, score); // Improve alpha
#region KillerHistoryStoring
if (alpha >= beta)
{
if (!item.IsCapture)
{
history[ply & 1, (int)item.MovePieceType, item.TargetSquare.Index] += depth * depth;
killermoves[ply] = item; //If it isn't a capture, store in the killer moves
}
break; // Fail-high
}
#endregion
}
#endregion
// (Check/Stale)mate and draw detection
if (!qsearch && moves.IsEmpty) return incheck ? ply - 30_000 : 0;
// Push the best move to TT
tt[key % 1_000_000] = (key, bestMove, depth, best, best >= beta ? 2 : best > origalpha ? 3 : 1); // Did we fail high/low or get an exact score?
return best;
}
/// <summary>
/// This is the static evaluation function
/// </summary>
int Eval()
{
//If scope is just 1 line, { and } aren't required, (still makes for some unreadable code)
int mg = 0, eg = 0, stage = 0, sidetomove = 2, piece, index;
//sidetomove gets set to 1 then to zero where we negate the mg and eg values
for (; --sidetomove >= 0; mg = -mg, eg = -eg)
for (piece = -1; ++piece < 6;) //loops piece from 0 to 5
for (ulong mask = board.GetPieceBitboard(piece + PieceType.Pawn, sidetomove > 0); mask != 0;) //it is faster to grab each peice bitborad than to loop over 1 bitboard and then grab the peice type
{
//Instead of using a lookuptable like for { 0, 1, 1, 2, 4, 0 }, we can use a 18 bit number (seen by 0x4448) 3 bit for each element
//And use bitshifts to acsess the items to save 5 tokens over creating an array (and it might be faster, IDK)
//Stage is used for how "endgame" our position is
stage += 0x4448 >> piece * 3 & 7;
mg += decompressed[index = piece * 128 + (BitboardHelper.ClearAndGetIndexOfLSB(ref mask) ^ 56 * sidetomove)];
eg += decompressed[index + 64];
}
return (mg * stage + eg * (24 - stage)) / 24 * (board.IsWhiteToMove ? 1 : -1);
}
}
} | 412 | 0.802606 | 1 | 0.802606 | game-dev | MEDIA | 0.860591 | game-dev | 0.908612 | 1 | 0.908612 |
alelievr/Mixture | 1,502 | Packages/com.alelievr.mixture/Runtime/Nodes/TerrainTopology/TerrainInputNode.cs | using GraphProcessor;
using UnityEngine;
using UnityEngine.Rendering;
namespace Mixture
{
[Documentation(@"
Helper node able to input a TerrainData in the graph. It could be used with all Terrain Topology Node
to input the terrain dimension and terrain height
")]
[System.Serializable, NodeMenuItem("Terrain/Terrain Input")]
public class TerrainInputNode : MixtureNode, ICreateNodeFrom<TerrainData>, ICreateNodeFrom<Terrain>
{
[Output("Terrain Data")] public MixtureTerrain output;
[ShowInInspector(true)] public TerrainData _terrainData;
public override string name => "Terrain Input";
public override bool hasPreview => false;
public override bool isRenamable => true;
public override bool showDefaultInspector => true;
protected override bool ProcessNode(CommandBuffer cmd)
{
if (!base.ProcessNode(cmd))
{
return false;
}
if (this._terrainData == null)
{
this.output = null;
return false;
}
this.output = new MixtureTerrain(_terrainData);
return true;
}
public bool InitializeNodeFromObject(TerrainData value)
{
_terrainData = value;
return true;
}
public bool InitializeNodeFromObject(Terrain value)
{
this._terrainData = value.terrainData;
return true;
}
}
} | 412 | 0.681957 | 1 | 0.681957 | game-dev | MEDIA | 0.877857 | game-dev | 0.87794 | 1 | 0.87794 |
Jannyboy11/InvSee-plus-plus | 18,171 | InvSee++_Platforms/Impl_1_19_4_R3/src/main/java/com/janboerman/invsee/spigot/impl_1_19_4_R3/InvseeImpl.java | package com.janboerman.invsee.spigot.impl_1_19_4_R3;
import com.janboerman.invsee.spigot.api.CreationOptions;
import com.janboerman.invsee.spigot.api.EnderSpectatorInventory;
import com.janboerman.invsee.spigot.api.EnderSpectatorInventoryView;
import com.janboerman.invsee.spigot.api.MainSpectatorInventory;
import com.janboerman.invsee.spigot.api.MainSpectatorInventoryView;
import com.janboerman.invsee.spigot.api.SpectatorInventory;
import com.janboerman.invsee.spigot.api.event.SpectatorInventorySaveEvent;
import com.janboerman.invsee.spigot.api.placeholder.PlaceholderGroup;
import com.janboerman.invsee.spigot.api.placeholder.PlaceholderPalette;
import com.janboerman.invsee.spigot.api.response.*;
import com.janboerman.invsee.spigot.api.target.Target;
import com.janboerman.invsee.spigot.api.template.EnderChestSlot;
import com.janboerman.invsee.spigot.api.template.Mirror;
import com.janboerman.invsee.spigot.api.template.PlayerInventorySlot;
import static com.janboerman.invsee.spigot.impl_1_19_4_R3.HybridServerSupport.enderChestItems;
import static com.janboerman.invsee.spigot.impl_1_19_4_R3.HybridServerSupport.nextContainerCounter;
import com.janboerman.invsee.spigot.internal.EventHelper;
import com.janboerman.invsee.spigot.internal.InvseePlatform;
import com.janboerman.invsee.spigot.internal.NamesAndUUIDs;
import com.janboerman.invsee.spigot.internal.OpenSpectatorsCache;
import com.janboerman.invsee.spigot.api.Scheduler;
import com.mojang.authlib.GameProfile;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket;
import net.minecraft.network.protocol.game.ClientboundOpenScreenPacket;
import net.minecraft.network.protocol.game.ServerboundContainerClosePacket;
import net.minecraft.server.dedicated.DedicatedPlayerList;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.inventory.PlayerEnderChestContainer;
import net.minecraft.world.inventory.Slot;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.storage.PlayerDataStorage;
import org.bukkit.Location;
import org.bukkit.craftbukkit.v1_19_R3.CraftServer;
import org.bukkit.craftbukkit.v1_19_R3.CraftWorld;
import org.bukkit.craftbukkit.v1_19_R3.entity.CraftHumanEntity;
import org.bukkit.craftbukkit.v1_19_R3.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_19_R3.inventory.CraftInventory;
import org.bukkit.craftbukkit.v1_19_R3.inventory.CraftItemStack;
import org.bukkit.craftbukkit.v1_19_R3.util.CraftChatMessage;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.inventory.InventoryView;
import org.bukkit.plugin.Plugin;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
public class InvseeImpl implements InvseePlatform {
private final Plugin plugin;
private final OpenSpectatorsCache cache;
private final Scheduler scheduler;
public InvseeImpl(Plugin plugin, NamesAndUUIDs lookup, Scheduler scheduler, OpenSpectatorsCache cache) {
this.plugin = plugin;
this.cache = cache;
this.scheduler = scheduler;
if (lookup.onlineMode(plugin.getServer())) {
lookup.uuidResolveStrategies.add(new UUIDSearchSaveFilesStrategy(plugin, scheduler));
} else {
// If we are in offline mode, then we should insert this strategy *before* the UUIDOfflineModeStrategy.
lookup.uuidResolveStrategies.add(lookup.uuidResolveStrategies.size() - 1, new UUIDSearchSaveFilesStrategy(plugin, scheduler));
}
lookup.nameResolveStrategies.add(2, new NameSearchSaveFilesStrategy(plugin, scheduler));
}
@Override
public OpenResponse<MainSpectatorInventoryView> openMainSpectatorInventory(Player spectator, MainSpectatorInventory inv, CreationOptions<PlayerInventorySlot> options) {
var target = Target.byGameProfile(inv.getSpectatedPlayerId(), inv.getSpectatedPlayerName());
var title = options.getTitle().titleFor(target);
CraftPlayer bukkitPlayer = (CraftPlayer) spectator;
ServerPlayer nmsPlayer = bukkitPlayer.getHandle();
MainBukkitInventory bukkitInventory = (MainBukkitInventory) inv;
MainNmsInventory nmsInventory = bukkitInventory.getInventory();
//this is what the nms does: nmsPlayer.openMenu(nmsWindow);
//so let's emulate that!
int windowId = nextContainerCounter(nmsPlayer);
Inventory bottom = nmsPlayer.getInventory();
MainNmsContainer nmsWindow = new MainNmsContainer(windowId, nmsInventory, bottom, nmsPlayer, options);
nmsWindow.setTitle(CraftChatMessage.fromString(title != null ? title : inv.getTitle())[0]);
var eventCancelled = callInventoryOpenEvent(nmsPlayer, nmsWindow); //closes current open inventory if one is already open
if (eventCancelled.isPresent()) {
return OpenResponse.closed(NotOpenedReason.inventoryOpenEventCancelled(eventCancelled.get()));
} else {
nmsPlayer.containerMenu = nmsWindow;
nmsPlayer.connection.send(new ClientboundOpenScreenPacket(windowId, nmsWindow.getType(), nmsWindow.getTitle()));
nmsPlayer.initMenu(nmsWindow);
MainBukkitInventoryView bukkitWindow = nmsWindow.getBukkitView();
//send placeholders
Mirror<PlayerInventorySlot> mirror = options.getMirror();
PlaceholderPalette palette = options.getPlaceholderPalette();
ItemStack inaccessible = CraftItemStack.asNMSCopy(palette.inaccessible());
for (int i = PlayerInventorySlot.CONTAINER_35.defaultIndex() + 1; i < nmsInventory.getContainerSize(); i++) {
Integer idx = mirror.getIndex(PlayerInventorySlot.byDefaultIndex(i));
if (idx == null) {
sendItemChange(nmsPlayer, i, inaccessible);
continue;
}
int rawIndex = idx.intValue();
Slot slot = nmsWindow.getSlot(rawIndex);
if (slot.hasItem()) continue;
//slot has no item, send placeholder.
if (slot instanceof InaccessibleSlot) sendItemChange(nmsPlayer, rawIndex, inaccessible);
else if (slot instanceof BootsSlot) sendItemChange(nmsPlayer, rawIndex, CraftItemStack.asNMSCopy(palette.armourBoots()));
else if (slot instanceof LeggingsSlot) sendItemChange(nmsPlayer, rawIndex, CraftItemStack.asNMSCopy(palette.armourLeggings()));
else if (slot instanceof ChestplateSlot) sendItemChange(nmsPlayer, rawIndex, CraftItemStack.asNMSCopy(palette.armourChestplate()));
else if (slot instanceof HelmetSlot) sendItemChange(nmsPlayer, rawIndex, CraftItemStack.asNMSCopy(palette.armourHelmet()));
else if (slot instanceof OffhandSlot) sendItemChange(nmsPlayer, rawIndex, CraftItemStack.asNMSCopy(palette.offHand()));
else if (slot instanceof CursorSlot) sendItemChange(nmsPlayer, rawIndex, CraftItemStack.asNMSCopy(palette.cursor()));
else if (slot instanceof PersonalSlot personal) sendItemChange(nmsPlayer, rawIndex, personal.works() ? CraftItemStack.asNMSCopy(palette.generic()) : inaccessible);
}
return OpenResponse.open(bukkitWindow);
}
}
@Override
public MainSpectatorInventory spectateInventory(HumanEntity player, CreationOptions<PlayerInventorySlot> options) {
MainNmsInventory spectatorInv = new MainNmsInventory(((CraftHumanEntity) player).getHandle(), options);
MainBukkitInventory bukkitInventory = spectatorInv.bukkit();
InventoryView targetView = player.getOpenInventory();
bukkitInventory.watch(targetView);
cache.cache(bukkitInventory);
return bukkitInventory;
}
@Override
public CompletableFuture<SpectateResponse<MainSpectatorInventory>> createOfflineInventory(UUID playerId, String playerName, CreationOptions<PlayerInventorySlot> options) {
return createOffline(playerId, playerName, options, this::spectateInventory);
}
@Override
public CompletableFuture<SaveResponse> saveInventory(MainSpectatorInventory newInventory) {
return save(newInventory, this::spectateInventory, MainSpectatorInventory::setContents);
}
@Override
public OpenResponse<EnderSpectatorInventoryView> openEnderSpectatorInventory(Player spectator, EnderSpectatorInventory inv, CreationOptions<EnderChestSlot> options) {
var target = Target.byGameProfile(inv.getSpectatedPlayerId(), inv.getSpectatedPlayerName());
var title = options.getTitle().titleFor(target);
CraftPlayer bukkitPlayer = (CraftPlayer) spectator;
ServerPlayer nmsPlayer = bukkitPlayer.getHandle();
EnderBukkitInventory bukkitInventory = (EnderBukkitInventory) inv;
EnderNmsInventory nmsInventory = bukkitInventory.getInventory();
//this is what the nms does: nmsPlayer.openMenu(nmsWindow);
//so let's emulate that!
int windowId = nextContainerCounter(nmsPlayer);
Inventory bottom = nmsPlayer.getInventory();
EnderNmsContainer nmsWindow = new EnderNmsContainer(windowId, nmsInventory, bottom, nmsPlayer, options);
nmsWindow.setTitle(CraftChatMessage.fromString(title != null ? title : inv.getTitle())[0]);
var eventCancelled = callInventoryOpenEvent(nmsPlayer, nmsWindow); //closes current open inventory if one is already open
if (eventCancelled.isPresent()) {
return OpenResponse.closed(NotOpenedReason.inventoryOpenEventCancelled(eventCancelled.get()));
} else {
nmsPlayer.containerMenu = nmsWindow;
nmsPlayer.connection.send(new ClientboundOpenScreenPacket(windowId, nmsWindow.getType(), nmsWindow.getTitle()));
nmsPlayer.initMenu(nmsWindow);
return OpenResponse.open(nmsWindow.getBukkitView());
}
}
@Override
public EnderSpectatorInventory spectateEnderChest(HumanEntity player, CreationOptions<EnderChestSlot> options) {
UUID uuid = player.getUniqueId();
String name = player.getName();
CraftInventory craftInventory = (CraftInventory) player.getEnderChest();
PlayerEnderChestContainer nmsInventory = (PlayerEnderChestContainer) craftInventory.getInventory();
EnderNmsInventory spectatorInv = new EnderNmsInventory(uuid, name, enderChestItems(nmsInventory), options);
EnderBukkitInventory bukkitInventory = spectatorInv.bukkit();
cache.cache(bukkitInventory);
return bukkitInventory;
}
@Override
public CompletableFuture<SpectateResponse<EnderSpectatorInventory>> createOfflineEnderChest(UUID playerId, String playerName, CreationOptions<EnderChestSlot> options) {
return createOffline(playerId, playerName, options, this::spectateEnderChest);
}
@Override
public CompletableFuture<SaveResponse> saveEnderChest(EnderSpectatorInventory newInventory) {
return save(newInventory, this::spectateEnderChest, EnderSpectatorInventory::setContents);
}
private <Slot, IS extends SpectatorInventory<Slot>> CompletableFuture<SpectateResponse<IS>> createOffline(UUID player, String name, CreationOptions<Slot> options, BiFunction<? super HumanEntity, ? super CreationOptions<Slot>, IS> invCreator) {
CraftServer server = (CraftServer) plugin.getServer();
DedicatedPlayerList playerList = server.getHandle();
PlayerDataStorage worldNBTStorage = playerList.playerIo;
CraftWorld world = (CraftWorld) server.getWorlds().get(0);
Location spawn = world.getSpawnLocation();
float yaw = spawn.getYaw();
GameProfile gameProfile = new GameProfile(player, name);
FakeEntityHuman fakeEntityHuman = new FakeEntityHuman(
world.getHandle(),
new BlockPos(spawn.getBlockX(), spawn.getBlockY(), spawn.getBlockZ()),
yaw,
gameProfile);
return CompletableFuture.supplyAsync(() -> {
CompoundTag playerCompound = worldNBTStorage.load(fakeEntityHuman);
if (playerCompound == null) {
// player file does not exist
if (!options.isUnknownPlayerSupported()) {
return SpectateResponse.fail(NotCreatedReason.unknownTarget(Target.byGameProfile(player, name)));
} //else: unknown/new players are supported!
// if we get here, then we create a spectator inventory for the non-existent player anyway.
} else {
// player file already exists, load the data from the compound onto the player
fakeEntityHuman.readAdditionalSaveData(playerCompound); //only player-specific stuff
}
CraftHumanEntity craftHumanEntity = new FakeCraftHumanEntity(server, fakeEntityHuman);
return SpectateResponse.succeed(EventHelper.callSpectatorInventoryOfflineCreatedEvent(server, invCreator.apply(craftHumanEntity, options)));
}, runnable -> scheduler.executeSyncPlayer(player, runnable, null));
}
private <Slot, SI extends SpectatorInventory<Slot>> CompletableFuture<SaveResponse> save(SI newInventory, BiFunction<? super HumanEntity, ? super CreationOptions<Slot>, SI> currentInvProvider, BiConsumer<SI, SI> transfer) {
CraftServer server = (CraftServer) plugin.getServer();
SpectatorInventorySaveEvent event = EventHelper.callSpectatorInventorySaveEvent(server, newInventory);
if (event.isCancelled()) return CompletableFuture.completedFuture(SaveResponse.notSaved(newInventory));
CraftWorld world = (CraftWorld) server.getWorlds().get(0);
UUID playerId = newInventory.getSpectatedPlayerId();
GameProfile gameProfile = new GameProfile(playerId, newInventory.getSpectatedPlayerName());
FakeEntityPlayer fakeEntityPlayer = new FakeEntityPlayer(
server.getServer(),
world.getHandle(),
gameProfile);
return CompletableFuture.supplyAsync(() -> {
FakeCraftPlayer fakeCraftPlayer = fakeEntityPlayer.getBukkitEntity();
fakeCraftPlayer.loadData();
CreationOptions<Slot> creationOptions = newInventory.getCreationOptions();
SI currentInv = currentInvProvider.apply(fakeCraftPlayer, creationOptions);
transfer.accept(currentInv, newInventory);
fakeCraftPlayer.saveData();
return SaveResponse.saved(currentInv);
}, runnable -> scheduler.executeSyncPlayer(playerId, runnable, null));
}
private static Optional<InventoryOpenEvent> callInventoryOpenEvent(ServerPlayer nmsPlayer, AbstractContainerMenu nmsView) {
//copy-pasta from CraftEventFactory, but returns the cancelled event in case it was cancelled.
if (nmsPlayer.containerMenu != nmsPlayer.inventoryMenu) {
nmsPlayer.connection.handleContainerClose(new ServerboundContainerClosePacket(nmsPlayer.containerMenu.containerId));
}
CraftServer server = nmsPlayer.level.getCraftServer();
CraftPlayer bukkitPlayer = nmsPlayer.getBukkitEntity();
nmsPlayer.containerMenu.transferTo(nmsView, bukkitPlayer);
InventoryOpenEvent event = new InventoryOpenEvent(nmsView.getBukkitView());
server.getPluginManager().callEvent(event);
if (event.isCancelled()) {
nmsView.transferTo(nmsPlayer.containerMenu, bukkitPlayer);
return Optional.of(event);
} else {
return Optional.empty();
}
}
@Override
public PlaceholderPalette getPlaceholderPalette(String name) {
return switch (name) {
case "glass panes" -> Placeholders.PALETTE_GLASS;
case "icons" -> Placeholders.PALETTE_ICONS;
default -> PlaceholderPalette.empty();
};
}
static void sendItemChange(ServerPlayer entityPlayer, int rawIndex, ItemStack toSend) {
AbstractContainerMenu container = entityPlayer.containerMenu;
entityPlayer.connection.send(new ClientboundContainerSetSlotPacket(container.containerId, container.incrementStateId(), rawIndex, toSend));
}
static ItemStack getItemOrPlaceholder(PlaceholderPalette palette, MainBukkitInventoryView view, int rawIndex, PlaceholderGroup group) {
Slot slot = view.nms.getSlot(rawIndex);
if (slot.hasItem()) return slot.getItem();
if (slot instanceof InaccessibleSlot) {
return CraftItemStack.asNMSCopy(palette.inaccessible());
} else if (slot instanceof BootsSlot) {
return CraftItemStack.asNMSCopy(palette.armourBoots());
} else if (slot instanceof LeggingsSlot) {
return CraftItemStack.asNMSCopy(palette.armourLeggings());
} else if (slot instanceof ChestplateSlot) {
return CraftItemStack.asNMSCopy(palette.armourChestplate());
} else if (slot instanceof HelmetSlot) {
return CraftItemStack.asNMSCopy(palette.armourLeggings());
} else if (slot instanceof OffhandSlot) {
return CraftItemStack.asNMSCopy(palette.offHand());
} else if (slot instanceof CursorSlot) {
return CraftItemStack.asNMSCopy(palette.cursor());
} else if (slot instanceof PersonalSlot personalSlot) {
if (!personalSlot.works()) return CraftItemStack.asNMSCopy(palette.inaccessible());
if (group == null) return ItemStack.EMPTY; //no group for personal slot -> fall back to empty stack
Mirror<PlayerInventorySlot> mirror = view.nms.creationOptions.getMirror();
PlayerInventorySlot pis = mirror.getSlot(rawIndex);
if (pis == null) return CraftItemStack.asNMSCopy(palette.inaccessible());
return CraftItemStack.asNMSCopy(palette.getPersonalSlotPlaceholder(pis, group));
} else {
return ItemStack.EMPTY;
}
}
}
| 412 | 0.950476 | 1 | 0.950476 | game-dev | MEDIA | 0.985191 | game-dev | 0.969598 | 1 | 0.969598 |
mpcjanssen/simpletask-android | 9,177 | app/src/main/java/nl/mpcjanssen/simpletask/Interpreter.kt | package nl.mpcjanssen.simpletask
import android.util.Log
import nl.mpcjanssen.simpletask.task.Task
import nl.mpcjanssen.simpletask.util.*
import org.luaj.vm2.*
import org.luaj.vm2.lib.OneArgFunction
import org.luaj.vm2.lib.jse.JsePlatform
import java.util.*
object Interpreter : AbstractInterpreter() {
private val globals = JsePlatform.standardGlobals()!!
const val tag = "LuaInterp"
private val TODOLIB = readAsset(TodoApplication.app.assets, "lua/todolib.lua")
init {
globals.set("toast", LuaToastShort())
globals.set("log", LuaLog())
evalScript(null, TODOLIB)
try {
evalScript(null, TodoApplication.config.luaConfig)
} catch (e: LuaError) {
Log.w(TodoApplication.config.TAG, "Lua execution failed " + e.message)
showToastLong(TodoApplication.app, "${getString(R.string.lua_error)}: ${e.message}")
}
}
override fun tasklistTextSize(): Float? {
return callZeroArgLuaFunction(CONFIG_TASKLIST_TEXT_SIZE_SP) { it.tofloat() }
}
// Callback to determine the theme. Return true for dark.
override fun configTheme(): String? {
return callZeroArgLuaFunction(CONFIG_THEME) { it.toString() }
}
override fun onFilterCallback(moduleName: String, t: Task): Pair<Boolean, String> {
val module = globals.get(moduleName).checktable()
if (module == LuaValue.NIL) {
return Pair(true, "true")
}
val onFilter = module.get(ON_FILTER_NAME)
if (!onFilter.isnil()) {
val args = fillOnFilterVarargs(t)
try {
val result = onFilter.call(args.arg1(), args.arg(2), args.arg(3))
return Pair(result.toboolean(), result.toString())
} catch (e: LuaError) {
Log.d(TAG, "Lua execution failed " + e.message)
}
}
return Pair(true, "true")
}
override fun hasFilterCallback(moduleName: String): Boolean {
return try {
val module = globals.get(moduleName).checktable() ?: globals
!module.get(ON_FILTER_NAME).isnil()
} catch (e: LuaError) {
Log.e(TAG, "Lua error: ${e.message} )")
false
}
}
override fun hasOnSortCallback(moduleName: String): Boolean {
return try {
val module = globals.get(moduleName).checktable() ?: globals
!module.get(ON_SORT_NAME).isnil()
} catch (e: LuaError) {
Log.e(TAG, "Lua error: ${e.message} )")
false
}
}
override fun hasOnGroupCallback(moduleName: String): Boolean {
return try {
val module = globals.get(moduleName).checktable() ?: globals
!module.get(ON_GROUP_NAME).isnil()
} catch (e: LuaError) {
Log.e(TAG, "Lua error: ${e.message} )")
false
}
}
override fun onSortCallback(moduleName: String, t: Task): String {
val module = try {
globals.get(moduleName).checktable()
} catch (e: LuaError) {
Log.e(TAG, "Lua error: ${e.message} )")
LuaValue.NIL
}
if (module == LuaValue.NIL) {
return ""
}
val callback = module.get(ON_SORT_NAME)
return executeCallback(callback, t) ?: ""
}
override fun onGroupCallback(moduleName: String, t: Task): String? {
val module = getModule(moduleName)
if (module == LuaValue.NIL) {
return null
}
val callback = module.get(ON_GROUP_NAME)
return executeCallback(callback, t)
}
private fun getModule(moduleName: String): LuaValue {
return try {
globals.get(moduleName).checktable()
} catch (e: LuaError) {
Log.e(TAG, "Lua error: ${e.message} )")
LuaValue.NIL
}
}
private fun executeCallback(callback: LuaValue, t: Task): String? {
if (!callback.isnil()) {
val args = fillOnFilterVarargs(t)
try {
val result = callback.call(args.arg1(), args.arg(2), args.arg(3))
return result.tojstring()
} catch (e: LuaError) {
Log.d(TAG, "Lua execution failed " + e.message)
}
}
return null
}
override fun onDisplayCallback(moduleName: String, t: Task): String? {
val module = getModule(moduleName)
if (module == LuaValue.NIL) {
return null
}
val callback = module.get(ON_DISPLAY_NAME)
return executeCallback(callback, t)
}
override fun onAddCallback(t: Task): Task? {
val callback = globals.get(ON_ADD_NAME)
val result = executeCallback(callback, t)
return if (result!=null) Task(result) else null
}
override fun onTextSearchCallback(moduleName: String, input: String, search: String, caseSensitive: Boolean): Boolean? {
val module = getModule(moduleName)
if (module == LuaValue.NIL) {
return null
}
val onFilter = module.get(ON_TEXTSEARCH_NAME)
if (!onFilter.isnil()) {
try {
val result = onFilter.invoke(LuaString.valueOf(input), LuaString.valueOf(search), LuaBoolean.valueOf(caseSensitive)).arg1()
return result.toboolean()
} catch (e: LuaError) {
Log.d(TAG, "Lua execution failed " + e.message)
}
}
return null
}
override fun evalScript(moduleName: String?, script: String?): AbstractInterpreter {
if (moduleName != null) {
val module = LuaTable.tableOf()
val metatable = LuaValue.tableOf()
metatable.set("__index", globals)
module.setmetatable(metatable)
globals.set(moduleName, module)
script?.let { globals.load(script, moduleName, module).call() }
} else {
script?.let { globals.load(script).call() }
}
return this
}
// Fill the arguments for the onFilter callback
private fun fillOnFilterVarargs(t: Task): Varargs {
val args = ArrayList<LuaValue>()
args.add(LuaValue.valueOf(t.inFileFormat(TodoApplication.config.useUUIDs)))
val fieldTable = LuaTable.tableOf()
fieldTable.set("due", dateStringToLuaLong(t.dueDate))
fieldTable.set("threshold", dateStringToLuaLong(t.thresholdDate))
fieldTable.set("createdate", dateStringToLuaLong(t.createDate))
fieldTable.set("completiondate", dateStringToLuaLong(t.completionDate))
fieldTable.set("text", t.alphaParts)
val recPat = t.recurrencePattern
if (recPat != null) {
fieldTable.set("recurrence", t.recurrencePattern)
}
fieldTable.set("completed", LuaBoolean.valueOf(t.isCompleted()))
val prioCode = t.priority.code
if (prioCode != "-") {
fieldTable.set("priority", prioCode)
}
fieldTable.set("tags", javaListToLuaTable(t.tags))
fieldTable.set("lists", javaListToLuaTable(t.lists))
args.add(fieldTable)
val extensionTable = LuaTable.tableOf()
for ((key, value) in t.extensions) {
extensionTable.set(key, value)
}
args.add(extensionTable)
return LuaValue.varargsOf(args.toTypedArray())
}
private fun dateStringToLuaLong(dateString: String?): LuaValue {
dateString?.toDateTime()?.let {
return LuaValue.valueOf((it.getMilliseconds(TimeZone.getDefault()) / 1000).toDouble())
}
return LuaValue.NIL
}
private fun javaListToLuaTable(javaList: Iterable<String>?): LuaValue {
val luaTable = LuaValue.tableOf()
javaList?.forEach {
luaTable.set(it, LuaValue.TRUE)
}
return luaTable
}
// Call a Lua function `name`
// Use unpackResult to transform the resulting LuaValue to the expected return type `T`
// Returns null if the function is not found or if a `LuaError` occurred
private fun <T> callZeroArgLuaFunction(name: String, unpackResult: (LuaValue) -> T?): T? {
val function = globals.get(name)
if (!function.isnil()) {
try {
return unpackResult(function.call())
} catch (e: LuaError) {
Log.d(TAG, "Lua execution failed " + e.message)
}
}
return null
}
override fun clearOnFilter(moduleName: String) {
val module = globals.get(moduleName)
if (module != LuaValue.NIL) {
module.set(ON_FILTER_NAME, LuaValue.NIL)
}
}
}
class LuaToastShort : OneArgFunction() {
override fun call(text: LuaValue?): LuaValue? {
val string = text?.tojstring() ?: ""
Log.i(Interpreter.tag, "Toasted: \"$string\"")
showToastShort(TodoApplication.app, string)
return LuaValue.NIL
}
}
class LuaLog : OneArgFunction() {
override fun call(text: LuaValue?): LuaValue? {
val string = text?.tojstring() ?: ""
Log.i(Interpreter.tag, string)
return LuaValue.NIL
}
} | 412 | 0.841668 | 1 | 0.841668 | game-dev | MEDIA | 0.33859 | game-dev | 0.872595 | 1 | 0.872595 |
Dimbreath/AzurLaneData | 1,200 | en-US/controller/command/player/harvestresourcecommand.lua | slot0 = class("HarvestResourceCommand", pm.SimpleCommand)
function slot0.execute(slot0, slot1)
slot2 = slot1:getBody()
slot3 = id2res(slot2)
slot6 = nil
if slot2 == 1 then
slot6 = getProxy(PlayerProxy):getData():getLevelMaxGold()
elseif slot2 == 2 then
slot6 = slot5:getLevelMaxOil()
end
if slot6 <= slot5[slot3] then
pg.TipsMgr.GetInstance():ShowTips(i18n("player_harvestResource_error_fullBag"))
return
end
pg.ConnectionMgr.GetInstance():Send(11013, {
number = 0,
type = slot2
}, 11014, function (slot0)
if slot0.result == 0 then
slot2 = 0
if uv0 - uv1[uv2] < uv1[uv2 .. "Field"] then
slot2 = slot1
uv1:addResources({
[uv2] = slot1
})
uv1[uv2 .. "Field"] = uv1[uv2 .. "Field"] - slot1
else
slot2 = uv1[uv2 .. "Field"]
uv1:addResources({
[uv2] = uv1[uv2 .. "Field"]
})
uv1[uv2 .. "Field"] = 0
end
uv3:updatePlayer(uv1)
uv4:sendNotification(GAME.HARVEST_RES_DONE, {
type = uv5,
outPut = slot2
})
pg.CriMgr.GetInstance():PlaySoundEffect_V3(SFX_UI_ACADEMY_GETMATERIAL)
else
pg.TipsMgr.GetInstance():ShowTips(errorTip("player_harvestResource", slot0.result))
end
end)
end
return slot0
| 412 | 0.582547 | 1 | 0.582547 | game-dev | MEDIA | 0.350229 | game-dev | 0.897846 | 1 | 0.897846 |
HushengStudent/myGameFramework | 1,813 | Client/Assets/Scripts/Framework/BehaviorTree/BehaviorTree.cs | /********************************************************************************
** auth: https://github.com/HushengStudent
** date: 2018/06/18 13:13:25
** desc: 行为树;
*********************************************************************************/
using Framework.ECSModule;
namespace Framework.BehaviorTreeModule
{
public sealed partial class BehaviorTree
{
public bool Enable;
public event OnBTStartEventHandler OnStart;
public event OnBTSuccesstEventHandler OnSuccess;
public event OnBTFailureEventHandler OnFailure;
public event OnBTResetEventHandler OnReset;
public AbsBehavior Root { get; private set; }
public AbsEntity Entity { get; private set; }
public BehaviorTree(AbsBehavior root, AbsEntity entity)
{
Root = root;
Entity = entity;
Enable = false;
}
public void Update(float interval)
{
if (Enable && Entity != null && (Root.Reslut == BehaviorState.Reset || Root.Reslut == BehaviorState.Running))
{
var reslut = Root.Behave(Entity, interval);
switch (reslut)
{
case BehaviorState.Reset:
break;
case BehaviorState.Failure:
break;
case BehaviorState.Running:
break;
case BehaviorState.Success:
break;
case BehaviorState.Finish:
break;
default:
Enable = false;
LogHelper.PrintError("[BehaviorTree]error state.");
break;
}
}
}
}
} | 412 | 0.878968 | 1 | 0.878968 | game-dev | MEDIA | 0.919264 | game-dev | 0.902352 | 1 | 0.902352 |
chromealex/Unity3d.UI.Windows | 3,326 | Assets/UI.Windows.Addons/Ads/Services/UnityAdsService.cs | using UnityEngine;
using System.Collections;
using UnityEngine.UI.Windows.Plugins.Flow;
using System.Collections.Generic;
using UnityEngine.UI.Windows.Plugins.Services;
using System.Linq;
#if UNITY_ADS
using UnityEngine.Advertisements;
#endif
namespace UnityEngine.UI.Windows.Plugins.Ads.Services {
public class UnityAdsService : AdsService {
#if UNITY_ADS
private bool isPlaying = false;
#endif
public override string GetAuthKey(ServiceItem item) {
#pragma warning disable
var itemAds = (item as AdsServiceItem);
#pragma warning restore
#if UNITY_IOS
return itemAds.iosKey;
#elif UNITY_ANDROID
return itemAds.androidKey;
#else
return item.authKey;
#endif
}
public override string GetServiceName() {
return "UnityAds";
}
public override bool IsSupported() {
#if UNITY_ADS
return Advertisement.isSupported;
#else
return false;
#endif
}
public override bool IsConnected() {
#if UNITY_ADS
return Advertisement.isInitialized;
#else
return false;
#endif
}
public override System.Collections.Generic.IEnumerator<byte> Auth(string key, ServiceItem serviceItem) {
#if UNITY_ADS
if (Advertisement.isSupported == true) {
Advertisement.Initialize(key, testMode: (serviceItem as AdsServiceItem).testMode);
/*while (Advertisement.isInitialized == false) {
yield return 0;
}*/
}
#endif
yield return 0;
}
public override bool CanShow() {
#if UNITY_ADS
return Advertisement.IsReady();
#else
return false;
#endif
}
public override System.Collections.Generic.IEnumerator<byte> Show(string name, Dictionary<object, object> options = null, System.Action onFinish = null, System.Action onFailed = null, System.Action onSkipped = null) {
#if UNITY_ADS
if (Advertisement.IsReady() == true && this.isPlaying == false) {
this.isPlaying = true;
Advertisement.Show(name, new ShowOptions() {
resultCallback = (result) => {
switch (result) {
case ShowResult.Failed:
if (onFailed != null) onFailed.Invoke();
break;
case ShowResult.Finished:
if (onFinish != null) onFinish.Invoke();
break;
case ShowResult.Skipped:
if (onSkipped != null) onSkipped.Invoke();
break;
}
this.isPlaying = false;
}
});
} else {
if (onFailed != null) onFailed.Invoke();
}
#endif
yield return 0;
}
#if UNITY_EDITOR
protected override void OnInspectorGUI(UnityEngine.UI.Windows.Plugins.Ads.AdsSettings settings, AdsServiceItem item, System.Action onReset, GUISkin skin) {
var found = false;
#if UNITY_ADS
found = true;
#endif
if (found == false) {
UnityEditor.EditorGUILayout.HelpBox("To enable Unity Ads open `Window/Unity Services` window, login there and turn on `Ads`.", UnityEditor.MessageType.Warning);
} else {
UnityEditor.EditorGUILayout.HelpBox("Unity Ads is enabled.", UnityEditor.MessageType.Info);
item.iosKey = UnityEditor.EditorGUILayout.TextField("GameID (iOS): ", item.iosKey);
item.androidKey = UnityEditor.EditorGUILayout.TextField("GameID (Android): ", item.androidKey);
item.testMode = UnityEditor.EditorGUILayout.Toggle("Test mode: ", item.testMode);
}
}
#endif
}
} | 412 | 0.795224 | 1 | 0.795224 | game-dev | MEDIA | 0.426822 | game-dev | 0.600228 | 1 | 0.600228 |
Innoxia/liliths-throne-public | 3,274 | res/items/innoxia/race/pig_oinkers_fries.xml | <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<item>
<coreAttributes>
<value>15</value>
<determiner><![CDATA[a box of]]></determiner>
<name><![CDATA[Oinkers Fries]]></name>
<namePlural pluralByDefault="false"><![CDATA[Oinkers Fries']]></namePlural>
<description><![CDATA[A cardboard box stuffed full of greasy, curly fries. The branding on the front of the packet declares it to be from the fast food outlet, 'Oinkers!', while on the back some text worryingly declares that the fat content is 'less than 50%'.]]></description>
<useDescriptor>eat</useDescriptor>
<sexUse>true</sexUse>
<combatUseAllies>true</combatUseAllies>
<combatUseEnemies>false</combatUseEnemies>
<consumedOnUse>true</consumedOnUse>
<rarity>RARE</rarity>
<imageName zLayer="0" imageRotation="0" imageSize="100">background_bottom.svg</imageName>
<imageName zLayer="1" imageRotation="0" imageSize="70" target1='stroke="#000"' replacement1='stroke="#ff5555"' target2='#ff8080' replacement2='#ff5555'>res/race/innoxia/pig/subspecies/icon.svg</imageName>
<imageName zLayer="2" imageRotation="0" imageSize="75">pig_oinkers_fries.svg</imageName>
<imageName zLayer="3" imageRotation="0" imageSize="100">background_top.svg</imageName>
<colourPrimary>innoxia_pig</colourPrimary>
<colourSecondary/>
<colourTertiary/>
<potionDescriptor><![CDATA[pig]]></potionDescriptor>
<associatedRace>innoxia_pig</associatedRace>
<enchantmentItemTypeId>ELIXIR</enchantmentItemTypeId>
<enchantmentEffectId>RACE</enchantmentEffectId> <!-- 'RACE' is a special value, and when defined, this item will use the defined 'associatedRace' to give the player enchantment options for making a TF elixir for that race. -->
<effectTooltipLines>
<line><![CDATA[[style.boldGood(Restores)] 10% [style.boldHealth([#ATTRIBUTE_HEALTH_MAXIMUM.getName()])]]]></line>
<line><![CDATA[[#ATTRIBUTE_MAJOR_PHYSIQUE.getFormattedValue(2)] to 'potion effects']]></line>
<line><![CDATA[If body size is less than [style.colourBodySizeThree('large')], increases body size by 1]]></line>
</effectTooltipLines>
<applyEffects><![CDATA[
[##npc.incrementHealth(npc.getAttributeValue(ATTRIBUTE_HEALTH_MAXIMUM)/10)]
<p style='margin-bottom:0; padding-bottom:0;'>
[npc.Name] [npc.verb(start)] to feel heavier...
</p>
[#npc.addPotionEffect(ATTRIBUTE_MAJOR_PHYSIQUE, 2)]
#IF(npc.getBodySizeValue()<60)
[#npc.incrementBodySize(1)]
#ENDIF
]]></applyEffects>
<itemTags>
<tag>FOOD_POOR</tag>
<tag>DOMINION_ALLEYWAY_SPAWN</tag>
<tag>ELIS_ALLEYWAY_SPAWN</tag>
<tag>RACIAL_TF_ITEM</tag>
<tag>SOLD_BY_RALPH</tag>
</itemTags>
</coreAttributes>
<useDescriptions>
<selfUse><![CDATA[
[npc.Name] [npc.verb(start)] quickly devouring the curly fries, and within moments [npc.sheIs] left with an empty box and an unhealthy, greasy taste filling [npc.her] mouth.
]]></selfUse>
<otherUse><![CDATA[
[npc.Name] [npc.verb(present)] [npc2.name] with the box of curly fries and [npc.verb(get)] [npc2.herHim] to eat them. Stuffing them in [npc2.her] mouth, it only takes a few moments before [npc2.nameIs] left with an empty box and an unhealthy, greasy taste filling [npc2.her] mouth.
]]></otherUse>
</useDescriptions>
</item>
| 412 | 0.646628 | 1 | 0.646628 | game-dev | MEDIA | 0.966918 | game-dev | 0.605072 | 1 | 0.605072 |
OPM/ResInsight | 7,806 | ApplicationLibCode/Commands/CompletionCommands/RicNewFishbonesSubsFeature.cpp | /////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
// ResInsight 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.
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
#include "RicNewFishbonesSubsFeature.h"
#include "WellPathCommands/RicWellPathsUnitSystemSettingsImpl.h"
#include "RiaApplication.h"
#include "RiaLogging.h"
#include "Well/RigWellPath.h"
#include "Rim3dView.h"
#include "RimFishbones.h"
#include "RimFishbonesCollection.h"
#include "RimProject.h"
#include "RimTools.h"
#include "RimWellPath.h"
#include "RimWellPathCollection.h"
#include "RimWellPathCompletions.h"
#include "RiuMainWindow.h"
#include "cafSelectionManager.h"
#include <QAction>
#include <QMenu>
#include <QMessageBox>
#include <cmath>
CAF_CMD_SOURCE_INIT( RicNewFishbonesSubsFeature, "RicNewFishbonesSubsFeature" );
//---------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RicNewFishbonesSubsFeature::onActionTriggered( bool isChecked )
{
// Nothing to do here, handled by sub menu actions
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RicNewFishbonesSubsFeature::onDrillingStandard()
{
createFishbones( RimFishbonesDefines::drillingStandardParameters() );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RicNewFishbonesSubsFeature::onDrillingExtended()
{
createFishbones( RimFishbonesDefines::drillingExtendedParameters() );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RicNewFishbonesSubsFeature::onAcidJetting()
{
createFishbones( RimFishbonesDefines::acidJettingParameters() );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RicNewFishbonesSubsFeature::createFishbones( const RimFishbonesDefines::RicFishbonesSystemParameters& customParameters )
{
RimFishbonesCollection* fishbonesCollection = selectedFishbonesCollection();
CVF_ASSERT( fishbonesCollection );
RimWellPath* wellPath = fishbonesCollection->firstAncestorOrThisOfTypeAsserted<RimWellPath>();
if ( !RicWellPathsUnitSystemSettingsImpl::ensureHasUnitSystem( wellPath ) ) return;
auto* obj = new RimFishbones;
fishbonesCollection->appendFishbonesSubs( obj );
obj->setSystemParameters( customParameters.lateralsPerSub,
customParameters.lateralLength,
customParameters.holeDiameter,
customParameters.buildAngle,
customParameters.icdsPerSub );
double wellPathTipMd = wellPath->uniqueEndMD();
if ( wellPathTipMd != HUGE_VAL )
{
double startMd = wellPathTipMd - 150 - 100;
if ( startMd < 100 ) startMd = 100;
obj->setMeasuredDepthAndCount( startMd, 12.5, 13 );
}
RicNewFishbonesSubsFeature::adjustWellPathScaling( fishbonesCollection );
RimWellPathCollection* wellPathCollection = RimTools::wellPathCollection();
if ( wellPathCollection )
{
wellPathCollection->uiCapability()->updateConnectedEditors();
}
RiuMainWindow::instance()->selectAsCurrentItem( obj );
RimProject* proj = RimProject::current();
proj->reloadCompletionTypeResultsInAllViews();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RimFishbonesCollection* RicNewFishbonesSubsFeature::selectedFishbonesCollection()
{
const auto selectedItems = caf::SelectionManager::instance()->selectedItems();
if ( selectedItems.size() != 1u ) return nullptr;
RimFishbonesCollection* objToFind = nullptr;
caf::PdmUiItem* pdmUiItem = selectedItems.front();
auto* objHandle = dynamic_cast<caf::PdmObjectHandle*>( pdmUiItem );
if ( objHandle )
{
objToFind = objHandle->firstAncestorOrThisOfType<RimFishbonesCollection>();
}
if ( objToFind == nullptr )
{
auto wellPaths = caf::SelectionManager::instance()->objectsByType<RimWellPath>();
if ( !wellPaths.empty() )
{
return wellPaths[0]->fishbonesCollection();
}
RimWellPathCompletions* completions = caf::SelectionManager::instance()->selectedItemOfType<RimWellPathCompletions>();
if ( completions )
{
return completions->fishbonesCollection();
}
}
return objToFind;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RicNewFishbonesSubsFeature::setupActionLook( QAction* actionToSetup )
{
auto icon = QIcon( ":/FishBoneGroup16x16.png" );
actionToSetup->setIcon( icon );
actionToSetup->setText( "Create Fishbones" );
auto subMenu = new QMenu;
{
auto action = subMenu->addAction( "Drilling Standard" );
action->setIcon( icon );
connect( action, &QAction::triggered, this, &RicNewFishbonesSubsFeature::onDrillingStandard );
}
{
auto action = subMenu->addAction( "Drilling Extended" );
action->setIcon( icon );
connect( action, &QAction::triggered, this, &RicNewFishbonesSubsFeature::onDrillingExtended );
}
{
auto action = subMenu->addAction( "Acid Jetting" );
action->setIcon( icon );
connect( action, &QAction::triggered, this, &RicNewFishbonesSubsFeature::onAcidJetting );
}
actionToSetup->setMenu( subMenu );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RicNewFishbonesSubsFeature::isCommandEnabled() const
{
return selectedFishbonesCollection() != nullptr;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RicNewFishbonesSubsFeature::adjustWellPathScaling( RimFishbonesCollection* fishboneCollection )
{
CVF_ASSERT( fishboneCollection );
RimWellPathCollection* wellPathColl = RimTools::wellPathCollection();
if ( wellPathColl->wellPathRadiusScaleFactor > 0.05 )
{
wellPathColl->wellPathRadiusScaleFactor = 0.01;
RiaLogging::info( "Radius scale of well paths is reduced to ensure the fish bone laterals are visible." );
}
}
| 412 | 0.944979 | 1 | 0.944979 | game-dev | MEDIA | 0.735731 | game-dev | 0.925963 | 1 | 0.925963 |
Bozar/GodotRoguelikeTutorial | 1,782 | 05/scene/main/PCMove.gd | extends Node2D
const Schedule := preload("res://scene/main/Schedule.gd")
var _ref_Schedule: Schedule
var _new_ConvertCoord := preload("res://library/ConvertCoord.gd").new()
var _new_InputName := preload("res://library/InputName.gd").new()
var _new_GroupName := preload("res://library/GroupName.gd").new()
var _pc: Sprite
var _move_inputs: Array = [
_new_InputName.MOVE_LEFT,
_new_InputName.MOVE_RIGHT,
_new_InputName.MOVE_UP,
_new_InputName.MOVE_DOWN,
]
func _ready() -> void:
set_process_unhandled_input(false)
func _unhandled_input(event: InputEvent) -> void:
var source: Array = _new_ConvertCoord.vector_to_array(_pc.position)
var target: Array
if _is_move_input(event):
target = _get_new_position(event, source)
_pc.position = _new_ConvertCoord.index_to_vector(target[0], target[1])
set_process_unhandled_input(false)
_ref_Schedule.end_turn()
func _on_InitWorld_sprite_created(new_sprite: Sprite) -> void:
if new_sprite.is_in_group(_new_GroupName.PC):
_pc = new_sprite
set_process_unhandled_input(true)
func _on_Schedule_turn_started(current_sprite: Sprite) -> void:
if current_sprite.is_in_group(_new_GroupName.PC):
set_process_unhandled_input(true)
print("{0}: Start turn.".format([current_sprite.name]))
func _is_move_input(event: InputEvent) -> bool:
for m in _move_inputs:
if event.is_action_pressed(m):
return true
return false
func _get_new_position(event: InputEvent, source: Array) -> Array:
var x: int = source[0]
var y: int = source[1]
if event.is_action_pressed(_new_InputName.MOVE_LEFT):
x -= 1
elif event.is_action_pressed(_new_InputName.MOVE_RIGHT):
x += 1
elif event.is_action_pressed(_new_InputName.MOVE_UP):
y -= 1
elif event.is_action_pressed(_new_InputName.MOVE_DOWN):
y += 1
return [x, y]
| 412 | 0.691235 | 1 | 0.691235 | game-dev | MEDIA | 0.754506 | game-dev,desktop-app | 0.893058 | 1 | 0.893058 |
Secrets-of-Sosaria/World | 1,873 | Data/Scripts/Items/Magical/God/Weapons/SE Weapons/LevelWakizashi.cs | using System;
using Server.Network;
using Server.Items;
namespace Server.Items
{
[FlipableAttribute( 0x27A4, 0x27EF )]
public class LevelWakizashi : BaseLevelSword
{
public override WeaponAbility PrimaryAbility{ get{ return WeaponAbility.FrenziedWhirlwind; } }
public override WeaponAbility SecondaryAbility{ get{ return WeaponAbility.DoubleStrike; } }
public override WeaponAbility ThirdAbility{ get{ return WeaponAbility.EarthStrike; } }
public override WeaponAbility FourthAbility{ get{ return WeaponAbility.FireStrike; } }
public override WeaponAbility FifthAbility{ get{ return WeaponAbility.ZapStamStrike; } }
public override int AosStrengthReq{ get{ return 20; } }
public override int AosMinDamage{ get{ return (int)(11 * GetDamageScaling()); } }
public override int AosMaxDamage{ get{ return (int)(13 * GetDamageScaling()); } }
public override int AosSpeed{ get{ return 44; } }
public override float MlSpeed{ get{ return 2.50f; } }
public override int OldStrengthReq{ get{ return 20; } }
public override int OldMinDamage{ get{ return 11; } }
public override int OldMaxDamage{ get{ return 13; } }
public override int OldSpeed{ get{ return 44; } }
public override int DefHitSound{ get{ return 0x23B; } }
public override int DefMissSound{ get{ return 0x23A; } }
public override int InitMinHits{ get{ return 45; } }
public override int InitMaxHits{ get{ return 50; } }
[Constructable]
public LevelWakizashi() : base( 0x27A4 )
{
Weight = 5.0;
Layer = Layer.OneHanded;
}
public LevelWakizashi( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
} | 412 | 0.792461 | 1 | 0.792461 | game-dev | MEDIA | 0.945267 | game-dev | 0.782977 | 1 | 0.782977 |
gameprogcpp/code | 1,974 | Chapter03/Actor.cpp | // ----------------------------------------------------------------
// From Game Programming in C++ by Sanjay Madhav
// Copyright (C) 2017 Sanjay Madhav. All rights reserved.
//
// Released under the BSD License
// See LICENSE in root directory for full details.
// ----------------------------------------------------------------
#include "Actor.h"
#include "Game.h"
#include "Component.h"
#include <algorithm>
Actor::Actor(Game* game)
:mState(EActive)
, mPosition(Vector2::Zero)
, mScale(1.0f)
, mRotation(0.0f)
, mGame(game)
{
mGame->AddActor(this);
}
Actor::~Actor()
{
mGame->RemoveActor(this);
// Need to delete components
// Because ~Component calls RemoveComponent, need a different style loop
while (!mComponents.empty())
{
delete mComponents.back();
}
}
void Actor::Update(float deltaTime)
{
if (mState == EActive)
{
UpdateComponents(deltaTime);
UpdateActor(deltaTime);
}
}
void Actor::UpdateComponents(float deltaTime)
{
for (auto comp : mComponents)
{
comp->Update(deltaTime);
}
}
void Actor::UpdateActor(float deltaTime)
{
}
void Actor::ProcessInput(const uint8_t* keyState)
{
if (mState == EActive)
{
// First process input for components
for (auto comp : mComponents)
{
comp->ProcessInput(keyState);
}
ActorInput(keyState);
}
}
void Actor::ActorInput(const uint8_t* keyState)
{
}
void Actor::AddComponent(Component* component)
{
// Find the insertion point in the sorted vector
// (The first element with a order higher than me)
int myOrder = component->GetUpdateOrder();
auto iter = mComponents.begin();
for (;
iter != mComponents.end();
++iter)
{
if (myOrder < (*iter)->GetUpdateOrder())
{
break;
}
}
// Inserts element before position of iterator
mComponents.insert(iter, component);
}
void Actor::RemoveComponent(Component* component)
{
auto iter = std::find(mComponents.begin(), mComponents.end(), component);
if (iter != mComponents.end())
{
mComponents.erase(iter);
}
}
| 412 | 0.822162 | 1 | 0.822162 | game-dev | MEDIA | 0.973976 | game-dev | 0.821835 | 1 | 0.821835 |
hojat72elect/libgdx_games | 5,768 | 2D_Adventure/core/src/main/kotlin/com/github/quillraven/quillysadventure/ai/PlayerState.kt | package com.github.quillraven.quillysadventure.ai
import com.badlogic.ashley.core.Entity
import com.badlogic.gdx.graphics.g2d.Animation
import com.github.quillraven.quillysadventure.ecs.component.AnimationType
import com.github.quillraven.quillysadventure.ecs.component.AttackOrder
import com.github.quillraven.quillysadventure.ecs.component.CastOrder
import com.github.quillraven.quillysadventure.ecs.component.CollisionComponent
import com.github.quillraven.quillysadventure.ecs.component.JumpOrder
import com.github.quillraven.quillysadventure.ecs.component.MoveOrder
import com.github.quillraven.quillysadventure.ecs.component.PhysicComponent
import com.github.quillraven.quillysadventure.ecs.component.abilityCmp
import com.github.quillraven.quillysadventure.ecs.component.aniCmp
import com.github.quillraven.quillysadventure.ecs.component.attackCmp
import com.github.quillraven.quillysadventure.ecs.component.collCmp
import com.github.quillraven.quillysadventure.ecs.component.jumpCmp
import com.github.quillraven.quillysadventure.ecs.component.moveCmp
import com.github.quillraven.quillysadventure.ecs.component.physicCmp
import com.github.quillraven.quillysadventure.ecs.component.stateCmp
import kotlin.math.abs
enum class PlayerState(
override val aniType: AnimationType,
override val aniMode: Animation.PlayMode = Animation.PlayMode.LOOP
) : EntityState {
IDLE(AnimationType.IDLE) {
override fun update(entity: Entity) {
with(entity.stateCmp.stateMachine) {
when {
entity.abilityCmp.order == CastOrder.BEGIN_CAST -> changeState(CAST)
entity.attackCmp.order == AttackOrder.START -> changeState(ATTACK)
entity.jumpCmp.order == JumpOrder.JUMP -> changeState(JUMP)
entity.moveCmp.order != MoveOrder.NONE -> changeState(RUN)
isFalling(entity.physicCmp, entity.collCmp) -> changeState(FALL)
}
}
}
},
RUN(AnimationType.RUN) {
override fun update(entity: Entity) {
val physicCmp = entity.physicCmp
val velocity = physicCmp.body.linearVelocity
with(entity.stateCmp.stateMachine) {
when {
entity.abilityCmp.order == CastOrder.BEGIN_CAST -> changeState(CAST)
entity.attackCmp.order == AttackOrder.START -> changeState(ATTACK)
entity.jumpCmp.order == JumpOrder.JUMP -> changeState(JUMP)
isFalling(physicCmp, entity.collCmp) -> changeState(FALL)
entity.moveCmp.order == MoveOrder.NONE && abs(velocity.x) <= 0.5f -> changeState(IDLE)
}
}
}
},
JUMP(AnimationType.JUMP, Animation.PlayMode.NORMAL) {
override fun update(entity: Entity) {
val collision = entity.collCmp
with(entity.stateCmp) {
if (isFalling(entity.physicCmp, collision) || stateTime >= entity.jumpCmp.maxJumpTime) {
// player is in mid-air and falling down OR player exceeds maximum jump time
stateMachine.changeState(FALL)
} else if (collision.numGroundContacts > 0 && entity.jumpCmp.order == JumpOrder.NONE) {
// player is on ground again
stateMachine.changeState(IDLE)
}
}
}
override fun exit(entity: Entity) {
entity.jumpCmp.order = JumpOrder.NONE
}
},
FALL(AnimationType.FALL) {
override fun update(entity: Entity) {
if (entity.collCmp.numGroundContacts > 0) {
// reached ground again
entity.stateCmp.stateMachine.changeState(IDLE)
}
}
},
ATTACK(AnimationType.ATTACK, Animation.PlayMode.NORMAL) {
override fun enter(entity: Entity) {
entity.attackCmp.order = AttackOrder.ATTACK_ONCE
entity.moveCmp.lockMovement = true
super.enter(entity)
}
override fun update(entity: Entity) {
if (entity.aniCmp.isAnimationFinished()) {
entity.attackCmp.order = AttackOrder.NONE
entity.stateCmp.stateMachine.changeState(IDLE)
}
}
override fun exit(entity: Entity) {
entity.moveCmp.lockMovement = false
}
},
CAST(AnimationType.CAST, Animation.PlayMode.NORMAL) {
override fun enter(entity: Entity) {
entity.moveCmp.lockMovement = true
super.enter(entity)
}
override fun update(entity: Entity) {
entity.stateCmp.let { state ->
with(entity.abilityCmp) {
if (state.stateTime >= 0.2f && order == CastOrder.BEGIN_CAST) {
order = CastOrder.CAST
}
if (entity.aniCmp.isAnimationFinished() || (state.stateTime < 0.2f && order == CastOrder.NONE)) {
state.stateMachine.changeState(IDLE)
}
}
}
}
override fun exit(entity: Entity) {
entity.moveCmp.lockMovement = false
super.exit(entity)
}
},
FAKE_DEATH(AnimationType.DEATH, Animation.PlayMode.NORMAL) {
override fun enter(entity: Entity) {
super.enter(entity)
entity.aniCmp.animationSpeed = 0.5f
}
override fun exit(entity: Entity) {
super.exit(entity)
entity.aniCmp.animationSpeed = 1f
}
};
fun isFalling(physic: PhysicComponent, collision: CollisionComponent) =
physic.body.linearVelocity.y < 0f && collision.numGroundContacts == 0
}
| 412 | 0.883218 | 1 | 0.883218 | game-dev | MEDIA | 0.978818 | game-dev | 0.989184 | 1 | 0.989184 |
json-everything/json-everything | 5,224 | src/JsonSchema.DataGeneration/Generators/ObjectGenerator.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json.Nodes;
using Bogus;
namespace Json.Schema.DataGeneration.Generators;
internal class ObjectGenerator : IDataGenerator
{
public static ObjectGenerator Instance { get; } = new();
private static readonly Faker _faker = new();
// TODO: move these to a public settings object
public static uint DefaultMinProperties { get; set; } = 0;
public static uint DefaultMaxProperties { get; set; } = 10;
public static uint DefaultMinContains { get; set; } = 1;
public static uint DefaultMaxContains { get; set; } = 10;
private ObjectGenerator() { }
public SchemaValueType Type => SchemaValueType.Object;
public GenerationResult Generate(RequirementsContext context)
{
var minProperties = DefaultMinProperties;
var maxProperties = DefaultMaxProperties;
if (context.PropertyCounts != null)
{
if (!context.PropertyCounts.Ranges.Any())
return GenerationResult.Fail("No valid property counts possible");
var numberRange = JsonSchemaExtensions.Randomizer.ArrayElement(context.PropertyCounts.Ranges.ToArray());
if (numberRange.Minimum.Value != NumberRangeSet.MinRangeValue)
minProperties = (uint)(numberRange.Minimum.Inclusive
? numberRange.Minimum.Value
: numberRange.Minimum.Value + 1);
if (numberRange.Maximum.Value != NumberRangeSet.MaxRangeValue)
maxProperties = (uint)(numberRange.Maximum.Inclusive
? numberRange.Maximum.Value
: numberRange.Maximum.Value - 1);
}
var propertyCount = (int)JsonSchemaExtensions.Randomizer.UInt(minProperties, maxProperties);
var containsCount = 0;
if (context.Contains != null)
{
var minContains = DefaultMinContains;
var maxContains = Math.Min(maxProperties, DefaultMaxContains + minContains);
if (context.ContainsCounts != null)
{
var numberRange = JsonSchemaExtensions.Randomizer.ArrayElement(context.ContainsCounts.Ranges.ToArray());
if (numberRange.Minimum.Value != NumberRangeSet.MinRangeValue)
minContains = (uint)numberRange.Minimum.Value;
if (numberRange.Maximum.Value != NumberRangeSet.MaxRangeValue)
maxContains = (uint)numberRange.Maximum.Value;
}
// some simple checks to ensure an instance can be generated
if (minContains > maxContains)
return GenerationResult.Fail("minContains is greater than maxContains");
if (minContains > maxProperties)
return GenerationResult.Fail("minContains is greater than maxItems less property count");
containsCount = (int)JsonSchemaExtensions.Randomizer.UInt(minContains, maxContains);
if (propertyCount < containsCount)
propertyCount = containsCount;
}
var propertyGenerationResults = new Dictionary<string, GenerationResult>();
var definedPropertyNames = new List<string>();
var remainingPropertyCount = propertyCount;
if (context.RequiredProperties != null)
{
definedPropertyNames.AddRange(context.RequiredProperties);
remainingPropertyCount -= context.RequiredProperties.Count;
}
if (context.AvoidProperties != null)
{
foreach (var avoidProperty in context.AvoidProperties)
{
if (definedPropertyNames.Remove(avoidProperty))
remainingPropertyCount++;
}
}
if (context.Properties != null)
{
var propertyNames = context.Properties.Keys.Except(definedPropertyNames).ToArray();
if (propertyNames.Length != 0)
{
propertyNames = JsonSchemaExtensions.Randomizer.ArrayElements(propertyNames, Math.Min(propertyNames.Length, remainingPropertyCount));
definedPropertyNames.AddRange(propertyNames);
remainingPropertyCount -= propertyNames.Length;
}
}
var remainingProperties = context.RemainingProperties ?? new RequirementsContext();
if (remainingProperties.IsFalse)
remainingPropertyCount = 0;
remainingPropertyCount = Math.Max(0, remainingPropertyCount);
var otherPropertyNames = remainingPropertyCount == 0
? []
: _faker.Lorem.Sentence(remainingPropertyCount * 2).Split(' ')
.Distinct()
.Take(remainingPropertyCount)
.ToArray();
var allPropertyNames = definedPropertyNames.Concat(otherPropertyNames).ToArray();
var containsProperties = JsonSchemaExtensions.Randomizer
.ArrayElements(allPropertyNames, Math.Min(allPropertyNames.Length, containsCount))
.ToArray();
int currentContainsIndex = 0;
foreach (var propertyName in allPropertyNames)
{
if (context.Properties?.TryGetValue(propertyName, out var propertyRequirement) != true)
propertyRequirement = context.RemainingProperties ?? new RequirementsContext();
if (containsCount > 0 && currentContainsIndex < containsProperties.Length)
{
propertyRequirement = new RequirementsContext(propertyRequirement!);
propertyRequirement.And(context.Contains!);
currentContainsIndex++;
}
var propertyGenerationResult = propertyRequirement!.GenerateData();
if (propertyGenerationResult.IsSuccess)
propertyGenerationResults[propertyName] = propertyGenerationResult;
}
return propertyGenerationResults.All(x => x.Value.IsSuccess)
? GenerationResult.Success(new JsonObject(propertyGenerationResults.ToDictionary(x => x.Key, x => x.Value.Result?.DeepClone())))
: GenerationResult.Fail(propertyGenerationResults.Values);
}
} | 412 | 0.8858 | 1 | 0.8858 | game-dev | MEDIA | 0.274858 | game-dev | 0.94496 | 1 | 0.94496 |
2Retr0/GodotGrass | 22,508 | addons/imgui-godot/include/imgui-godot.h | #pragma once
#include <imgui.h>
#ifndef IMGUI_HAS_VIEWPORT
#error use ImGui docking branch
#endif
#if __has_include("godot_cpp/godot.hpp")
#define IGN_GDEXT
// GDExtension
#include <godot_cpp/classes/atlas_texture.hpp>
#include <godot_cpp/classes/engine.hpp>
#include <godot_cpp/classes/font_file.hpp>
#include <godot_cpp/classes/input_event.hpp>
#include <godot_cpp/classes/resource.hpp>
#include <godot_cpp/classes/sub_viewport.hpp>
#include <godot_cpp/classes/texture2d.hpp>
#include <godot_cpp/classes/window.hpp>
#include <godot_cpp/variant/callable.hpp>
#include <godot_cpp/variant/typed_array.hpp>
#else
// module
#include "core/config/engine.h"
#include "core/input/input_enums.h"
#include "core/os/keyboard.h"
#include "core/variant/callable.h"
#include "scene/main/viewport.h"
#include "scene/main/window.h"
#include "scene/resources/atlas_texture.h"
#include "scene/resources/texture.h"
#endif
static_assert(sizeof(void*) == 8);
static_assert(sizeof(ImDrawIdx) == 2);
static_assert(sizeof(ImWchar) == 2);
namespace ImGui::Godot {
#if defined(IGN_GDEXT)
using godot::AtlasTexture;
using godot::Callable;
using godot::ClassDB;
using godot::Color;
using godot::Engine;
using godot::FontFile;
using godot::JoyButton;
using godot::Key;
using godot::Object;
using godot::PackedInt32Array;
using godot::Ref;
using godot::RID;
using godot::String;
using godot::StringName;
using godot::Texture2D;
using godot::TypedArray;
using godot::Vector2;
using godot::Viewport;
#endif
static_assert(sizeof(RID) == 8);
#ifndef IGN_EXPORT
// C++ user interface
namespace detail {
inline static Object* ImGuiGD = nullptr;
inline bool GET_IMGUIGD()
{
if (ImGuiGD)
return true;
#ifdef IGN_GDEXT
ImGuiGD = Engine::get_singleton()->get_singleton("ImGuiGD");
#else
ImGuiGD = Engine::get_singleton()->get_singleton_object("ImGuiGD");
#endif
return ImGuiGD != nullptr;
}
inline static void GetAtlasUVs(AtlasTexture* tex, ImVec2& uv0, ImVec2& uv1)
{
ERR_FAIL_COND(!tex);
Vector2 atlasSize = tex->get_atlas()->get_size();
uv0 = tex->get_region().get_position() / atlasSize;
uv1 = tex->get_region().get_end() / atlasSize;
}
} // namespace detail
inline void AddFont(const Ref<FontFile>& fontFile, int fontSize, bool merge = false, ImWchar* glyphRanges = nullptr)
{
ERR_FAIL_COND(!detail::GET_IMGUIGD());
static const StringName sn("AddFont");
PackedInt32Array gr;
if (glyphRanges)
{
do
{
gr.append(*glyphRanges);
} while (*++glyphRanges != 0);
}
detail::ImGuiGD->call(sn, fontSize, merge, gr);
}
inline void Connect(const Callable& callable)
{
ERR_FAIL_COND(!detail::GET_IMGUIGD());
static const StringName sn("Connect");
detail::ImGuiGD->call(sn, callable);
}
inline void RebuildFontAtlas()
{
ERR_FAIL_COND(!detail::GET_IMGUIGD());
static const StringName sn("RebuildFontAtlas");
detail::ImGuiGD->call(sn);
}
inline void ResetFonts()
{
ERR_FAIL_COND(!detail::GET_IMGUIGD());
static const StringName sn("ResetFonts");
detail::ImGuiGD->call(sn);
}
inline void SetJoyAxisDeadZone(float deadZone)
{
ERR_FAIL_COND(!detail::GET_IMGUIGD());
static const StringName sn("JoyAxisDeadZone");
detail::ImGuiGD->set(sn, deadZone);
}
inline void SetVisible(bool vis)
{
ERR_FAIL_COND(!detail::GET_IMGUIGD());
static const StringName sn("Visible");
detail::ImGuiGD->set(sn, vis);
}
inline void SetMainViewport(Viewport* vp)
{
ERR_FAIL_COND(!detail::GET_IMGUIGD());
static const StringName sn("SetMainViewport");
detail::ImGuiGD->call(sn, vp);
}
inline bool ToolInit()
{
ERR_FAIL_COND_V(!detail::GET_IMGUIGD(), false);
static const StringName sn("ToolInit");
return detail::ImGuiGD->call(sn);
}
inline void SetIniFilename(String fn)
{
ERR_FAIL_COND(!detail::GET_IMGUIGD());
static const StringName sn("SetIniFilename");
detail::ImGuiGD->call(sn, fn);
}
inline void SyncImGuiPtrs()
{
Object* obj = ClassDB::instantiate("ImGuiSync");
ERR_FAIL_COND(!obj);
static const StringName sn("GetImGuiPtrs");
TypedArray<int64_t> ptrs = obj->call(sn,
String(ImGui::GetVersion()),
(int32_t)sizeof(ImGuiIO),
(int32_t)sizeof(ImDrawVert),
(int32_t)sizeof(ImDrawIdx),
(int32_t)sizeof(ImWchar));
ERR_FAIL_COND(ptrs.size() != 3);
ImGui::SetCurrentContext(reinterpret_cast<ImGuiContext*>((int64_t)ptrs[0]));
ImGuiMemAllocFunc alloc_func = reinterpret_cast<ImGuiMemAllocFunc>((int64_t)ptrs[1]);
ImGuiMemFreeFunc free_func = reinterpret_cast<ImGuiMemFreeFunc>((int64_t)ptrs[2]);
ImGui::SetAllocatorFunctions(alloc_func, free_func, nullptr);
memdelete(obj);
}
inline ImTextureID BindTexture(Texture2D* tex)
{
ERR_FAIL_COND_V(!tex, 0);
return reinterpret_cast<ImTextureID>(tex->get_rid().get_id());
}
#endif
#ifdef IGN_GDEXT // GDExtension
inline ImGuiKey ToImGuiKey(Key key)
{
switch (key)
{
case Key::KEY_ESCAPE:
return ImGuiKey_Escape;
case Key::KEY_TAB:
return ImGuiKey_Tab;
case Key::KEY_BACKSPACE:
return ImGuiKey_Backspace;
case Key::KEY_ENTER:
return ImGuiKey_Enter;
case Key::KEY_KP_ENTER:
return ImGuiKey_KeypadEnter;
case Key::KEY_INSERT:
return ImGuiKey_Insert;
case Key::KEY_DELETE:
return ImGuiKey_Delete;
case Key::KEY_PAUSE:
return ImGuiKey_Pause;
case Key::KEY_PRINT:
return ImGuiKey_PrintScreen;
case Key::KEY_HOME:
return ImGuiKey_Home;
case Key::KEY_END:
return ImGuiKey_End;
case Key::KEY_LEFT:
return ImGuiKey_LeftArrow;
case Key::KEY_UP:
return ImGuiKey_UpArrow;
case Key::KEY_RIGHT:
return ImGuiKey_RightArrow;
case Key::KEY_DOWN:
return ImGuiKey_DownArrow;
case Key::KEY_PAGEUP:
return ImGuiKey_PageUp;
case Key::KEY_PAGEDOWN:
return ImGuiKey_PageDown;
case Key::KEY_SHIFT:
return ImGuiKey_LeftShift;
case Key::KEY_CTRL:
return ImGuiKey_LeftCtrl;
case Key::KEY_META:
return ImGuiKey_LeftSuper;
case Key::KEY_ALT:
return ImGuiKey_LeftAlt;
case Key::KEY_CAPSLOCK:
return ImGuiKey_CapsLock;
case Key::KEY_NUMLOCK:
return ImGuiKey_NumLock;
case Key::KEY_SCROLLLOCK:
return ImGuiKey_ScrollLock;
case Key::KEY_F1:
return ImGuiKey_F1;
case Key::KEY_F2:
return ImGuiKey_F2;
case Key::KEY_F3:
return ImGuiKey_F3;
case Key::KEY_F4:
return ImGuiKey_F4;
case Key::KEY_F5:
return ImGuiKey_F5;
case Key::KEY_F6:
return ImGuiKey_F6;
case Key::KEY_F7:
return ImGuiKey_F7;
case Key::KEY_F8:
return ImGuiKey_F8;
case Key::KEY_F9:
return ImGuiKey_F9;
case Key::KEY_F10:
return ImGuiKey_F10;
case Key::KEY_F11:
return ImGuiKey_F11;
case Key::KEY_F12:
return ImGuiKey_F12;
case Key::KEY_KP_MULTIPLY:
return ImGuiKey_KeypadMultiply;
case Key::KEY_KP_DIVIDE:
return ImGuiKey_KeypadDivide;
case Key::KEY_KP_SUBTRACT:
return ImGuiKey_KeypadSubtract;
case Key::KEY_KP_PERIOD:
return ImGuiKey_KeypadDecimal;
case Key::KEY_KP_ADD:
return ImGuiKey_KeypadAdd;
case Key::KEY_KP_0:
return ImGuiKey_Keypad0;
case Key::KEY_KP_1:
return ImGuiKey_Keypad1;
case Key::KEY_KP_2:
return ImGuiKey_Keypad2;
case Key::KEY_KP_3:
return ImGuiKey_Keypad3;
case Key::KEY_KP_4:
return ImGuiKey_Keypad4;
case Key::KEY_KP_5:
return ImGuiKey_Keypad5;
case Key::KEY_KP_6:
return ImGuiKey_Keypad6;
case Key::KEY_KP_7:
return ImGuiKey_Keypad7;
case Key::KEY_KP_8:
return ImGuiKey_Keypad8;
case Key::KEY_KP_9:
return ImGuiKey_Keypad9;
case Key::KEY_MENU:
return ImGuiKey_Menu;
case Key::KEY_SPACE:
return ImGuiKey_Space;
case Key::KEY_APOSTROPHE:
return ImGuiKey_Apostrophe;
case Key::KEY_COMMA:
return ImGuiKey_Comma;
case Key::KEY_MINUS:
return ImGuiKey_Minus;
case Key::KEY_PERIOD:
return ImGuiKey_Period;
case Key::KEY_SLASH:
return ImGuiKey_Slash;
case Key::KEY_0:
return ImGuiKey_0;
case Key::KEY_1:
return ImGuiKey_1;
case Key::KEY_2:
return ImGuiKey_2;
case Key::KEY_3:
return ImGuiKey_3;
case Key::KEY_4:
return ImGuiKey_4;
case Key::KEY_5:
return ImGuiKey_5;
case Key::KEY_6:
return ImGuiKey_6;
case Key::KEY_7:
return ImGuiKey_7;
case Key::KEY_8:
return ImGuiKey_8;
case Key::KEY_9:
return ImGuiKey_9;
case Key::KEY_SEMICOLON:
return ImGuiKey_Semicolon;
case Key::KEY_EQUAL:
return ImGuiKey_Equal;
case Key::KEY_A:
return ImGuiKey_A;
case Key::KEY_B:
return ImGuiKey_B;
case Key::KEY_C:
return ImGuiKey_C;
case Key::KEY_D:
return ImGuiKey_D;
case Key::KEY_E:
return ImGuiKey_E;
case Key::KEY_F:
return ImGuiKey_F;
case Key::KEY_G:
return ImGuiKey_G;
case Key::KEY_H:
return ImGuiKey_H;
case Key::KEY_I:
return ImGuiKey_I;
case Key::KEY_J:
return ImGuiKey_J;
case Key::KEY_K:
return ImGuiKey_K;
case Key::KEY_L:
return ImGuiKey_L;
case Key::KEY_M:
return ImGuiKey_M;
case Key::KEY_N:
return ImGuiKey_N;
case Key::KEY_O:
return ImGuiKey_O;
case Key::KEY_P:
return ImGuiKey_P;
case Key::KEY_Q:
return ImGuiKey_Q;
case Key::KEY_R:
return ImGuiKey_R;
case Key::KEY_S:
return ImGuiKey_S;
case Key::KEY_T:
return ImGuiKey_T;
case Key::KEY_U:
return ImGuiKey_U;
case Key::KEY_V:
return ImGuiKey_V;
case Key::KEY_W:
return ImGuiKey_W;
case Key::KEY_X:
return ImGuiKey_X;
case Key::KEY_Y:
return ImGuiKey_Y;
case Key::KEY_Z:
return ImGuiKey_Z;
case Key::KEY_BRACKETLEFT:
return ImGuiKey_LeftBracket;
case Key::KEY_BACKSLASH:
return ImGuiKey_Backslash;
case Key::KEY_BRACKETRIGHT:
return ImGuiKey_RightBracket;
case Key::KEY_QUOTELEFT:
return ImGuiKey_GraveAccent;
default:
return ImGuiKey_None;
};
}
inline ImGuiKey ToImGuiKey(JoyButton btn)
{
switch (btn)
{
case JoyButton::JOY_BUTTON_A:
return ImGuiKey_GamepadFaceDown;
case JoyButton::JOY_BUTTON_B:
return ImGuiKey_GamepadFaceRight;
case JoyButton::JOY_BUTTON_X:
return ImGuiKey_GamepadFaceLeft;
case JoyButton::JOY_BUTTON_Y:
return ImGuiKey_GamepadFaceUp;
case JoyButton::JOY_BUTTON_BACK:
return ImGuiKey_GamepadBack;
case JoyButton::JOY_BUTTON_START:
return ImGuiKey_GamepadStart;
case JoyButton::JOY_BUTTON_LEFT_STICK:
return ImGuiKey_GamepadL3;
case JoyButton::JOY_BUTTON_RIGHT_STICK:
return ImGuiKey_GamepadR3;
case JoyButton::JOY_BUTTON_LEFT_SHOULDER:
return ImGuiKey_GamepadL1;
case JoyButton::JOY_BUTTON_RIGHT_SHOULDER:
return ImGuiKey_GamepadR1;
case JoyButton::JOY_BUTTON_DPAD_UP:
return ImGuiKey_GamepadDpadUp;
case JoyButton::JOY_BUTTON_DPAD_DOWN:
return ImGuiKey_GamepadDpadDown;
case JoyButton::JOY_BUTTON_DPAD_LEFT:
return ImGuiKey_GamepadDpadLeft;
case JoyButton::JOY_BUTTON_DPAD_RIGHT:
return ImGuiKey_GamepadDpadRight;
default:
return ImGuiKey_None;
};
}
#else // module
inline ImGuiKey ToImGuiKey(Key key)
{
switch (key)
{
case Key::ESCAPE:
return ImGuiKey_Escape;
case Key::TAB:
return ImGuiKey_Tab;
case Key::BACKSPACE:
return ImGuiKey_Backspace;
case Key::ENTER:
return ImGuiKey_Enter;
case Key::KP_ENTER:
return ImGuiKey_KeypadEnter;
case Key::INSERT:
return ImGuiKey_Insert;
case Key::KEY_DELETE:
return ImGuiKey_Delete;
case Key::PAUSE:
return ImGuiKey_Pause;
case Key::PRINT:
return ImGuiKey_PrintScreen;
case Key::HOME:
return ImGuiKey_Home;
case Key::END:
return ImGuiKey_End;
case Key::LEFT:
return ImGuiKey_LeftArrow;
case Key::UP:
return ImGuiKey_UpArrow;
case Key::RIGHT:
return ImGuiKey_RightArrow;
case Key::DOWN:
return ImGuiKey_DownArrow;
case Key::PAGEUP:
return ImGuiKey_PageUp;
case Key::PAGEDOWN:
return ImGuiKey_PageDown;
case Key::SHIFT:
return ImGuiKey_LeftShift;
case Key::CTRL:
return ImGuiKey_LeftCtrl;
case Key::META:
return ImGuiKey_LeftSuper;
case Key::ALT:
return ImGuiKey_LeftAlt;
case Key::CAPSLOCK:
return ImGuiKey_CapsLock;
case Key::NUMLOCK:
return ImGuiKey_NumLock;
case Key::SCROLLLOCK:
return ImGuiKey_ScrollLock;
case Key::F1:
return ImGuiKey_F1;
case Key::F2:
return ImGuiKey_F2;
case Key::F3:
return ImGuiKey_F3;
case Key::F4:
return ImGuiKey_F4;
case Key::F5:
return ImGuiKey_F5;
case Key::F6:
return ImGuiKey_F6;
case Key::F7:
return ImGuiKey_F7;
case Key::F8:
return ImGuiKey_F8;
case Key::F9:
return ImGuiKey_F9;
case Key::F10:
return ImGuiKey_F10;
case Key::F11:
return ImGuiKey_F11;
case Key::F12:
return ImGuiKey_F12;
case Key::KP_MULTIPLY:
return ImGuiKey_KeypadMultiply;
case Key::KP_DIVIDE:
return ImGuiKey_KeypadDivide;
case Key::KP_SUBTRACT:
return ImGuiKey_KeypadSubtract;
case Key::KP_PERIOD:
return ImGuiKey_KeypadDecimal;
case Key::KP_ADD:
return ImGuiKey_KeypadAdd;
case Key::KP_0:
return ImGuiKey_Keypad0;
case Key::KP_1:
return ImGuiKey_Keypad1;
case Key::KP_2:
return ImGuiKey_Keypad2;
case Key::KP_3:
return ImGuiKey_Keypad3;
case Key::KP_4:
return ImGuiKey_Keypad4;
case Key::KP_5:
return ImGuiKey_Keypad5;
case Key::KP_6:
return ImGuiKey_Keypad6;
case Key::KP_7:
return ImGuiKey_Keypad7;
case Key::KP_8:
return ImGuiKey_Keypad8;
case Key::KP_9:
return ImGuiKey_Keypad9;
case Key::MENU:
return ImGuiKey_Menu;
case Key::SPACE:
return ImGuiKey_Space;
case Key::APOSTROPHE:
return ImGuiKey_Apostrophe;
case Key::COMMA:
return ImGuiKey_Comma;
case Key::MINUS:
return ImGuiKey_Minus;
case Key::PERIOD:
return ImGuiKey_Period;
case Key::SLASH:
return ImGuiKey_Slash;
case Key::KEY_0:
return ImGuiKey_0;
case Key::KEY_1:
return ImGuiKey_1;
case Key::KEY_2:
return ImGuiKey_2;
case Key::KEY_3:
return ImGuiKey_3;
case Key::KEY_4:
return ImGuiKey_4;
case Key::KEY_5:
return ImGuiKey_5;
case Key::KEY_6:
return ImGuiKey_6;
case Key::KEY_7:
return ImGuiKey_7;
case Key::KEY_8:
return ImGuiKey_8;
case Key::KEY_9:
return ImGuiKey_9;
case Key::SEMICOLON:
return ImGuiKey_Semicolon;
case Key::EQUAL:
return ImGuiKey_Equal;
case Key::A:
return ImGuiKey_A;
case Key::B:
return ImGuiKey_B;
case Key::C:
return ImGuiKey_C;
case Key::D:
return ImGuiKey_D;
case Key::E:
return ImGuiKey_E;
case Key::F:
return ImGuiKey_F;
case Key::G:
return ImGuiKey_G;
case Key::H:
return ImGuiKey_H;
case Key::I:
return ImGuiKey_I;
case Key::J:
return ImGuiKey_J;
case Key::K:
return ImGuiKey_K;
case Key::L:
return ImGuiKey_L;
case Key::M:
return ImGuiKey_M;
case Key::N:
return ImGuiKey_N;
case Key::O:
return ImGuiKey_O;
case Key::P:
return ImGuiKey_P;
case Key::Q:
return ImGuiKey_Q;
case Key::R:
return ImGuiKey_R;
case Key::S:
return ImGuiKey_S;
case Key::T:
return ImGuiKey_T;
case Key::U:
return ImGuiKey_U;
case Key::V:
return ImGuiKey_V;
case Key::W:
return ImGuiKey_W;
case Key::X:
return ImGuiKey_X;
case Key::Y:
return ImGuiKey_Y;
case Key::Z:
return ImGuiKey_Z;
case Key::BRACKETLEFT:
return ImGuiKey_LeftBracket;
case Key::BACKSLASH:
return ImGuiKey_Backslash;
case Key::BRACKETRIGHT:
return ImGuiKey_RightBracket;
case Key::QUOTELEFT:
return ImGuiKey_GraveAccent;
default:
return ImGuiKey_None;
};
}
inline ImGuiKey ToImGuiKey(JoyButton btn)
{
switch (btn)
{
case JoyButton::A:
return ImGuiKey_GamepadFaceDown;
case JoyButton::B:
return ImGuiKey_GamepadFaceRight;
case JoyButton::X:
return ImGuiKey_GamepadFaceLeft;
case JoyButton::Y:
return ImGuiKey_GamepadFaceUp;
case JoyButton::BACK:
return ImGuiKey_GamepadBack;
case JoyButton::START:
return ImGuiKey_GamepadStart;
case JoyButton::LEFT_STICK:
return ImGuiKey_GamepadL3;
case JoyButton::RIGHT_STICK:
return ImGuiKey_GamepadR3;
case JoyButton::LEFT_SHOULDER:
return ImGuiKey_GamepadL1;
case JoyButton::RIGHT_SHOULDER:
return ImGuiKey_GamepadR1;
case JoyButton::DPAD_UP:
return ImGuiKey_GamepadDpadUp;
case JoyButton::DPAD_DOWN:
return ImGuiKey_GamepadDpadDown;
case JoyButton::DPAD_LEFT:
return ImGuiKey_GamepadDpadLeft;
case JoyButton::DPAD_RIGHT:
return ImGuiKey_GamepadDpadRight;
default:
return ImGuiKey_None;
};
}
#endif
} // namespace ImGui::Godot
#ifndef IGN_EXPORT
// widgets
namespace ImGui {
#if defined(IGN_GDEXT)
using godot::AtlasTexture;
using godot::Ref;
using godot::StringName;
using godot::SubViewport;
using godot::Texture2D;
#endif
inline bool SubViewport(SubViewport* svp)
{
ERR_FAIL_COND_V(!ImGui::Godot::detail::GET_IMGUIGD(), false);
static const StringName sn("SubViewport");
return ImGui::Godot::detail::ImGuiGD->call(sn, svp);
}
inline void Image(Texture2D* tex, const Vector2& size, const Vector2& uv0 = {0, 0}, const Vector2& uv1 = {1, 1},
const Color& tint_col = {1, 1, 1, 1}, const Color& border_col = {0, 0, 0, 0})
{
ImGui::Image(ImGui::Godot::BindTexture(tex), size, uv0, uv1, tint_col, border_col);
}
inline void Image(const Ref<Texture2D>& tex, const Vector2& size, const Vector2& uv0 = {0, 0},
const Vector2& uv1 = {1, 1}, const Color& tint_col = {1, 1, 1, 1},
const Color& border_col = {0, 0, 0, 0})
{
ImGui::Image(ImGui::Godot::BindTexture(tex.ptr()), size, uv0, uv1, tint_col, border_col);
}
inline void Image(AtlasTexture* tex, const Vector2& size, const Color& tint_col = {1, 1, 1, 1},
const Color& border_col = {0, 0, 0, 0})
{
ImVec2 uv0, uv1;
ImGui::Godot::detail::GetAtlasUVs(tex, uv0, uv1);
ImGui::Image(ImGui::Godot::BindTexture(tex), size, uv0, uv1, tint_col, border_col);
}
inline void Image(const Ref<AtlasTexture>& tex, const Vector2& size, const Color& tint_col = {1, 1, 1, 1},
const Color& border_col = {0, 0, 0, 0})
{
ImVec2 uv0, uv1;
ImGui::Godot::detail::GetAtlasUVs(tex.ptr(), uv0, uv1);
ImGui::Image(ImGui::Godot::BindTexture(tex.ptr()), size, uv0, uv1, tint_col, border_col);
}
inline bool ImageButton(const char* str_id, Texture2D* tex, const Vector2& size, const Vector2& uv0 = {0, 0},
const Vector2& uv1 = {1, 1}, const Color& bg_col = {0, 0, 0, 0},
const Color& tint_col = {1, 1, 1, 1})
{
return ImGui::ImageButton(str_id, ImGui::Godot::BindTexture(tex), size, uv0, uv1, bg_col, tint_col);
}
inline bool ImageButton(const char* str_id, const Ref<Texture2D>& tex, const Vector2& size, const Vector2& uv0 = {0, 0},
const Vector2& uv1 = {1, 1}, const Color& bg_col = {0, 0, 0, 0},
const Color& tint_col = {1, 1, 1, 1})
{
return ImGui::ImageButton(str_id, ImGui::Godot::BindTexture(tex.ptr()), size, uv0, uv1, bg_col, tint_col);
}
inline bool ImageButton(const char* str_id, AtlasTexture* tex, const Vector2& size, const Color& bg_col = {0, 0, 0, 0},
const Color& tint_col = {1, 1, 1, 1})
{
ImVec2 uv0, uv1;
ImGui::Godot::detail::GetAtlasUVs(tex, uv0, uv1);
return ImGui::ImageButton(str_id, ImGui::Godot::BindTexture(tex), size, uv0, uv1, bg_col, tint_col);
}
inline bool ImageButton(const char* str_id, const Ref<AtlasTexture>& tex, const Vector2& size,
const Color& bg_col = {0, 0, 0, 0}, const Color& tint_col = {1, 1, 1, 1})
{
ImVec2 uv0, uv1;
ImGui::Godot::detail::GetAtlasUVs(tex.ptr(), uv0, uv1);
return ImGui::ImageButton(str_id, ImGui::Godot::BindTexture(tex.ptr()), size, uv0, uv1, bg_col, tint_col);
}
} // namespace ImGui
#endif
#ifndef IGN_GDEXT
#ifdef _WIN32
#define IGN_MOD_EXPORT __declspec(dllexport)
#else
#define IGN_MOD_EXPORT
#endif
#define IMGUI_GODOT_MODULE_INIT() \
extern "C" { \
void IGN_MOD_EXPORT imgui_godot_module_init(uint32_t ver, ImGuiContext* ctx, ImGuiMemAllocFunc afunc, \
ImGuiMemFreeFunc ffunc) \
{ \
IM_ASSERT(ver == IMGUI_VERSION_NUM); \
ImGui::SetCurrentContext(ctx); \
ImGui::SetAllocatorFunctions(afunc, ffunc, nullptr); \
} \
}
#endif
| 412 | 0.821657 | 1 | 0.821657 | game-dev | MEDIA | 0.613062 | game-dev,desktop-app | 0.931998 | 1 | 0.931998 |
WeakAuras/WeakAuras2 | 2,420 | WeakAuras/AuraEnvironmentWrappedSystems.lua | if not WeakAuras.IsLibsOK() then return end
---@type string
local AddonName = ...
---@class Private
local Private = select(2, ...)
local L = WeakAuras.L
--- @class AuraEnvironmentWrappedSystem
--- @field Get fun(systemName: string, id: auraId, cloneId: string?): any
--- @type AuraEnvironmentWrappedSystem
Private.AuraEnvironmentWrappedSystem = {
Get = function(systemName, id, cloneId)
end
}
--- @type table<auraId, table<string, table<string, any>>> Table of id, cloneId, systemName to wrapped system
local wrappers = {}
--- @type fun(_: any, uid: uid, id: auraId)
local function OnDelete(_, uid, id)
wrappers[id] = nil
end
--- @type fun(_: any, uid: uid, oldId: auraId, newId: auraId)
local function OnRename(_, uid, oldId, newId)
wrappers[newId] = wrappers[oldId]
wrappers[oldId] = nil
end
Private.callbacks:RegisterCallback("Delete", OnDelete)
Private.callbacks:RegisterCallback("Rename", OnRename)
local WrapData = {
C_Timer = {
{ name = "After", arg = 2},
{ name = "NewTimer", arg = 2},
{ name = "NewTicker", arg = 2}
}
}
--- @type fun(id: auraId, cloneId: string, system: any, funcs: {name: string, arg: number}[])
--- @return table wrappedSystem
local function Wrap(id, cloneId, system, funcs)
local wrappedSystem = {}
for _, data in ipairs(funcs) do
wrappedSystem[data.name] = function(...)
local packed = SafePack(...)
local oldArg = select(data.arg, ...)
if type(oldArg) == "function" then
packed[data.arg] = function(...)
local region = WeakAuras.GetRegion(id, cloneId)
if region then
Private.ActivateAuraEnvironmentForRegion(region)
xpcall(oldArg, Private.GetErrorHandlerId(id, L["Callback function"]), ...)
Private.ActivateAuraEnvironment()
else
oldArg(...)
end
end
end
return system[data.name](SafeUnpack(packed))
end
end
setmetatable(wrappedSystem, { __index = system, __metatable = false })
return wrappedSystem
end
Private.AuraEnvironmentWrappedSystem.Get = function(systemName, id, cloneId)
local cloneIdKey = cloneId or ""
wrappers[id] = wrappers[id] or {}
wrappers[id][cloneIdKey] = wrappers[id][cloneIdKey] or {}
wrappers[id][cloneIdKey][systemName] = wrappers[id][cloneIdKey][systemName]
or Wrap(id, cloneId, _G[systemName], WrapData[systemName])
return wrappers[id][cloneIdKey][systemName]
end
| 412 | 0.787962 | 1 | 0.787962 | game-dev | MEDIA | 0.557682 | game-dev | 0.91637 | 1 | 0.91637 |
Eniripsa96/SkillAPI | 7,722 | src/com/sucy/skill/manager/CmdManager.java | /**
* SkillAPI
* com.sucy.skill.manager.CmdManager
*
* The MIT License (MIT)
*
* Copyright (c) 2014 Steven Sucy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software") to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.sucy.skill.manager;
import com.rit.sucy.commands.CommandManager;
import com.rit.sucy.commands.ConfigurableCommand;
import com.rit.sucy.commands.SenderType;
import com.sucy.skill.SkillAPI;
import com.sucy.skill.cmd.*;
import com.sucy.skill.data.Permissions;
/**
* Sets up commands for the plugin
*/
public class CmdManager
{
private SkillAPI api;
/**
* Initializes a new command manager. This is handled by the API and
* shouldn't be used by other plugins.
*
* @param api SkillAPI reference
*/
public CmdManager(SkillAPI api)
{
this.api = api;
this.initialize();
}
/**
* Initializes commands with MCCore's CommandManager
*/
public void initialize()
{
ConfigurableCommand root = new ConfigurableCommand(api, "class", SenderType.ANYONE);
root.addSubCommands(
new ConfigurableCommand(api, "acc", SenderType.PLAYER_ONLY, new CmdAccount(), "Changes account", "<accountId>", Permissions.BASIC),
new ConfigurableCommand(api, "bind", SenderType.PLAYER_ONLY, new CmdBind(), "Binds a skill", "<skill>", Permissions.BASIC),
new ConfigurableCommand(api, "cast", SenderType.PLAYER_ONLY, new CmdCast(), "Casts a skill", "<skill>", Permissions.BASIC),
new ConfigurableCommand(api, "changeclass", SenderType.ANYONE, new CmdChangeClass(), "Swaps classes", "<player> <group> <class>", Permissions.FORCE),
new ConfigurableCommand(api, "clearbind", SenderType.PLAYER_ONLY, new CmdClearBinds(), "Clears skill binds", "", Permissions.BASIC),
new ConfigurableCommand(api, "exp", SenderType.ANYONE, new CmdExp(), "Gives players exp", "[player] <amount>", Permissions.LVL),
new ConfigurableCommand(api, "info", SenderType.ANYONE, new CmdInfo(), "Shows class info", "[player]", Permissions.BASIC),
new ConfigurableCommand(api, "level", SenderType.ANYONE, new CmdLevel(), "Gives players levels", "[player] <amount>", Permissions.LVL),
new ConfigurableCommand(api, "list", SenderType.ANYONE, new CmdList(), "Displays accounts", "[player]", Permissions.BASIC),
new ConfigurableCommand(api, "lore", SenderType.PLAYER_ONLY, new CmdLore(), "Adds lore to item", "<lore>", Permissions.LORE),
new ConfigurableCommand(api, "mana", SenderType.ANYONE, new CmdMana(), "Gives player mana", "[player] <amount>", Permissions.MANA),
new ConfigurableCommand(api, "options", SenderType.PLAYER_ONLY, new CmdOptions(), "Views profess options", "", Permissions.BASIC),
new ConfigurableCommand(api, "points", SenderType.ANYONE, new CmdPoints(), "Gives player points", "[player] <amount>", Permissions.POINTS),
new ConfigurableCommand(api, "profess", SenderType.PLAYER_ONLY, new CmdProfess(), "Professes classes", "<class>", Permissions.BASIC),
new ConfigurableCommand(api, "reload", SenderType.ANYONE, new CmdReload(), "Reloads the plugin", "", Permissions.RELOAD),
new ConfigurableCommand(api, "reset", SenderType.PLAYER_ONLY, new CmdReset(), "Resets account data", "", Permissions.BASIC),
new ConfigurableCommand(api, "skill", SenderType.PLAYER_ONLY, new CmdSkill(), "Shows player skills", "", Permissions.BASIC),
new ConfigurableCommand(api, "unbind", SenderType.PLAYER_ONLY, new CmdUnbind(), "Unbinds held item", "", Permissions.BASIC)
);
root.addSubCommands(
new ConfigurableCommand(api, "forceaccount", SenderType.CONSOLE_ONLY, new CmdForceAccount(), "Changes player's account", "<player> <accountId>", Permissions.FORCE),
new ConfigurableCommand(api, "forceattr", SenderType.CONSOLE_ONLY, new CmdForceAttr(), "Refunds/gives attributes", "<player> [attr] [amount]", Permissions.FORCE),
new ConfigurableCommand(api, "forcecast", SenderType.CONSOLE_ONLY, new CmdForceCast(), "Player casts the skill", "<player> <skill> [level]", Permissions.FORCE),
new ConfigurableCommand(api, "forceprofess", SenderType.CONSOLE_ONLY, new CmdForceProfess(), "Professes a player", "<player> <class>", Permissions.FORCE),
new ConfigurableCommand(api, "forcereset", SenderType.CONSOLE_ONLY, new CmdForceReset(), "Resets player data", "<player> [account]", Permissions.FORCE)
);
if (SkillAPI.getSettings().isUseSql())
{
root.addSubCommand(new ConfigurableCommand(api, "backup", SenderType.ANYONE, new CmdBackup(), "Backs up SQL data", "", Permissions.BACKUP));
}
if (SkillAPI.getSettings().isSkillBarEnabled())
{
root.addSubCommand(new ConfigurableCommand(api, "bar", SenderType.PLAYER_ONLY, new CmdBar(), "Toggles skill bar", "", Permissions.BASIC));
}
if (SkillAPI.getSettings().isCustomCombosAllowed())
{
root.addSubCommand(new ConfigurableCommand(api, "combo", SenderType.PLAYER_ONLY, new CmdCombo(), "Sets skill combo", "<skill> <combo>", Permissions.BASIC));
}
if (SkillAPI.getSettings().isMapTreeEnabled())
{
root.addSubCommand(new ConfigurableCommand(api, "scheme", SenderType.PLAYER_ONLY, new CmdScheme(), "Views/sets map schemes", "[scheme]", Permissions.BASIC));
}
if (SkillAPI.getSettings().isAttributesEnabled())
{
root.addSubCommand(new ConfigurableCommand(api, "ap", SenderType.ANYONE, new CmdAP(), "Gives attrib points", "[player] <amount>", Permissions.ATTRIB));
root.addSubCommand(new ConfigurableCommand(api, "attr", SenderType.PLAYER_ONLY, new CmdAttribute(), "Opens attribute menu", "", Permissions.BASIC));
}
if (SkillAPI.getSettings().isMapTreeAvailable() && !SkillAPI.getSettings().isMapTreeEnabled())
{
root.addSubCommand(new ConfigurableCommand(api, "skillmap", SenderType.PLAYER_ONLY, new CmdSkillMap(), "Alternate skill list", "", Permissions.BASIC));
}
CommandManager.registerCommand(root);
}
public static String join(String[] args, int start) {
return join(args, start, args.length);
}
public static String join(String[] args, int start, int end) {
final StringBuilder builder = new StringBuilder();
for (int i = start; i <= end; i++) builder.append(args[i]);
return builder.toString();
}
/**
* Unregisters all commands for SkillAPI from the server
*/
public void clear()
{
CommandManager.unregisterCommands(api);
}
}
| 412 | 0.779336 | 1 | 0.779336 | game-dev | MEDIA | 0.787384 | game-dev | 0.618116 | 1 | 0.618116 |
ThePaperLuigi/The-Stars-Above | 9,620 | UI/Starfarers/StarfarerPrompt.cs |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using StarsAbove.Systems;
using Terraria;
using Terraria.GameContent;
using Terraria.GameContent.UI.Elements;
using Terraria.UI;
using static Terraria.ModLoader.ModContent;
namespace StarsAbove.UI.Starfarers
{
internal class StarfarerPrompt : UIState
{
// For this bar we'll be using a frame texture and then a gradient inside bar, as it's one of the more simpler approaches while still looking decent.
// Once this is all set up make sure to go and do the required stuff for most UI's in the Mod class.
private UIText text;
private UIText warning;
private UIText AText;
private UIText EridaniText;
private UIElement area;
private UIElement barFrame;
private UIElement area3;
private UIImage bg;
private UIImageButton imageButton;
private UIImage bulletIndicatorOn;
private Color gradientA;
private Color gradientB;
private Color finalColor;
private Vector2 offset;
public bool dragging = false;
private UIElement face;
public static Vector2 PromptPos;
public override void OnInitialize() {
// Create a UIElement for all the elements to sit on top of, this simplifies the numbers as nested elements can be positioned relative to the top left corner of this element.
// UIElement is invisible and has no padding. You can use a UIPanel if you wish for a background.
area = new UIElement();
area.Left.Set(0, 0f); // Place the resource bar to the left of the hearts.
area.Top.Set(0, 0f);
area.Width.Set(700, 0f);
area.Height.Set(300, 0f);
//area.OnMouseDown += new UIElement.MouseEvent(DragStart);
//area.OnMouseUp += new UIElement.MouseEvent(DragEnd);
face = new UIElement();
face.Width.Set(400, 0f);
face.Height.Set(400, 0f);
barFrame = new UIElement();
barFrame.Left.Set(184, 0f);
barFrame.Top.Set(199, 0f);
barFrame.Width.Set(452, 0f);
barFrame.Height.Set(4, 0f);
//imageButton = new UIImageButton(Request<Texture2D>("StarsAbove/UI/Starfarers/Button"));
//imageButton.OnClick += MouseClickA;
//imageButton.Left.Set(616, 0f);
//imageButton.Top.Set(221, 0f);
/*Asphodene = new UIImage(Request<Texture2D>("StarsAbove/UI/Starfarers/Eridani"));
Asphodene.OnMouseOver += MouseOverA;
Asphodene.OnClick += MouseClickA;
Asphodene.Top.Set(0, 0f);
Asphodene.Left.Set(0, 0f);
Asphodene.Width.Set(0, 0f);
Asphodene.Height.Set(0, 0f);*/
text = new UIText("", 0.9f);
text.Width.Set(0, 0f);
text.Height.Set(0, 0f);
text.Top.Set(226, 0f);
text.Left.Set(50, 0f);
gradientA = new Color(249, 133, 36); //
gradientB = new Color(255, 166, 83); //
//area3.Append(Asphodene);
area.Append(face);
area.Append(text);
//area.Append(imageButton);
area.Append(barFrame);
Append(area);
}
private void DragStart(UIMouseEvent evt, UIElement listeningElement)
{
if (!(Main.LocalPlayer.GetModPlayer<StarsAbovePlayer>().promptVisibility >= 2f && Main.LocalPlayer.GetModPlayer<StarsAbovePlayer>().promptIsActive == true))
return;
offset = new Vector2(evt.MousePosition.X - area.Left.Pixels, evt.MousePosition.Y - area.Top.Pixels);
dragging = true;
}
private void DragEnd(UIMouseEvent evt, UIElement listeningElement)
{
if (!(Main.LocalPlayer.GetModPlayer<StarsAbovePlayer>().promptVisibility >= 2f && Main.LocalPlayer.GetModPlayer<StarsAbovePlayer>().promptIsActive == true))
return;
Vector2 end = evt.MousePosition;
dragging = false;
area.Left.Set(end.X - offset.X, 0f);
area.Top.Set(end.Y - offset.Y, 0f);
Recalculate();
}
private void MouseClickA(UIMouseEvent evt, UIElement listeningElement)
{
if (!(Main.LocalPlayer.GetModPlayer<StarsAbovePlayer>().starfarerDialogueVisibility >= 2f && Main.LocalPlayer.GetModPlayer<StarsAbovePlayer>().starfarerDialogue == true && Main.LocalPlayer.GetModPlayer<StarsAbovePlayer>().chosenStarfarer == 1))
return;
Main.LocalPlayer.GetModPlayer<StarsAbovePlayer>().dialogueLeft--;
if (Main.LocalPlayer.GetModPlayer<StarsAbovePlayer>().dialogueLeft <= 0)
{
Main.LocalPlayer.GetModPlayer<StarsAbovePlayer>().starfarerDialogue = false;
Main.LocalPlayer.GetModPlayer<StarsAbovePlayer>().chosenDialogue = 0;
Main.LocalPlayer.GetModPlayer<StarsAbovePlayer>().dialogue = "";
}
// We can do stuff in here!
}
public override void Draw(SpriteBatch spriteBatch) {
// This prevents drawing unless we are using an ExampleDamageItem
if (!(Main.LocalPlayer.GetModPlayer<StarsAbovePlayer>().promptVisibility > 0))
return;
base.Draw(spriteBatch);
}
protected override void DrawSelf(SpriteBatch spriteBatch)
{
base.DrawSelf(spriteBatch);
var modPlayer = Main.LocalPlayer.GetModPlayer<StarsAbovePlayer>();
/*area.Left.Set(area.Left.Pixels + modPlayer.promptMoveIn, 0);
if(modPlayer.starfarerPromptActiveTimer < 1)
{
modPlayer.promptMoveIn = 0;
}*/
Rectangle hitbox = area.GetInnerDimensions().ToRectangle();
Rectangle faceHitbox = face.GetInnerDimensions().ToRectangle();
face.Left.Set(-102, 0f);
face.Top.Set(-8, 0f);
Rectangle faceHitboxAlt = face.GetInnerDimensions().ToRectangle();
faceHitboxAlt.X += 18;
faceHitboxAlt.Y += 8;
faceHitboxAlt.Height = 400;
faceHitbox.Height = 400;
//Rectangle dialogueBox = new Rectangle((50), (480), (700), (300));
float quotient = (float)modPlayer.starfarerPromptActiveTimer / 250; // Creating a quotient that represents the difference of your currentResource vs your maximumResource, resulting in a float of 0-1f.
quotient = Utils.Clamp(quotient, 0f, 1f); // Clamping it to 0-1f so it doesn't go over that.
// Here we get the screen dimensions of the barFrame element, then tweak the resulting rectangle to arrive at a rectangle within the barFrame texture that we will draw the gradient. These values were measured in a drawing program.
Rectangle hitbox2 = barFrame.GetInnerDimensions().ToRectangle();
//hitbox2.Height += 40;
// Now, using this hitbox, we draw a gradient by drawing vertical lines while slowly interpolating between the 2 colors.
int left = hitbox2.Left;
int right = hitbox2.Right;
int steps = (int)((right - left) * quotient);
for (int i = 0; i < steps; i += 1)
{
//float percent = (float)i / steps; // Alternate Gradient Approach
float percent = (float)i / (right - left);
spriteBatch.Draw(TextureAssets.MagicPixel.Value, new Rectangle(left + i, hitbox2.Y, 1, hitbox2.Height), Color.Lerp(gradientA, gradientB, percent));
}
spriteBatch.Draw((Texture2D)Request<Texture2D>("StarsAbove/UI/Starfarers/MiniDialogue"), hitbox, Color.White * modPlayer.promptVisibility);
if (modPlayer.vagrantDialogue == 2)
{
if (modPlayer.chosenStarfarer == 1)
{
spriteBatch.Draw((Texture2D)Request<Texture2D>("StarsAbove/UI/Starfarers/DialoguePortraits/HABase"), hitbox, Color.White * (modPlayer.promptVisibility - 0.3f));
spriteBatch.Draw((Texture2D)Request<Texture2D>("StarsAbove/UI/VN/As1" + modPlayer.promptExpression), faceHitbox, Color.White * (modPlayer.promptVisibility - 0.3f));
}
else
{
spriteBatch.Draw((Texture2D)Request<Texture2D>("StarsAbove/UI/Starfarers/DialoguePortraits/HEBase"), hitbox, Color.White * (modPlayer.promptVisibility - 0.3f));
spriteBatch.Draw((Texture2D)Request<Texture2D>("StarsAbove/UI/VN/Er0" + modPlayer.promptExpression), faceHitboxAlt, Color.White * (modPlayer.promptVisibility - 0.3f));
}
}
else
{
if (modPlayer.chosenStarfarer == 1)
{
spriteBatch.Draw((Texture2D)Request<Texture2D>("StarsAbove/UI/Starfarers/DialoguePortraits/ABase"), hitbox, Color.White * (modPlayer.promptVisibility - 0.3f));
spriteBatch.Draw((Texture2D)Request<Texture2D>("StarsAbove/UI/VN/As1" + modPlayer.promptExpression), faceHitbox, Color.White * (modPlayer.promptVisibility - 0.3f));
}
else
{
spriteBatch.Draw((Texture2D)Request<Texture2D>("StarsAbove/UI/Starfarers/DialoguePortraits/EBase"), hitbox, Color.White * (modPlayer.promptVisibility - 0.3f));
spriteBatch.Draw((Texture2D)Request<Texture2D>("StarsAbove/UI/VN/Er0" + modPlayer.promptExpression), faceHitboxAlt, Color.White * (modPlayer.promptVisibility - 0.3f));
}
}
if (modPlayer.chosenStarfarer == 1)
{
spriteBatch.Draw((Texture2D)Request<Texture2D>("StarsAbove/UI/Starfarers/DialoguePortraits/AOutfit" + modPlayer.starfarerOutfitVisible), hitbox, Color.White * modPlayer.promptVisibility);
}
if (modPlayer.chosenStarfarer == 2)
{
spriteBatch.Draw((Texture2D)Request<Texture2D>("StarsAbove/UI/Starfarers/DialoguePortraits/EOutfit" + modPlayer.starfarerOutfitVisible), hitbox, Color.White * modPlayer.promptVisibility);
}
spriteBatch.Draw((Texture2D)Request<Texture2D>("StarsAbove/UI/Starfarers/MiniDialogueOverlay"), hitbox, Color.White * modPlayer.promptVisibility);
Recalculate();
}
public override void Update(GameTime gameTime) {
if (!(Main.LocalPlayer.GetModPlayer<StarsAbovePlayer>().promptVisibility > 0))
{
area.Remove();
return;
}
else
{
Append(area);
}
Vector2 configVec = PromptPos;
Left.Set(configVec.X, 1f);
Top.Set(configVec.Y, 1f);
var modPlayer = Main.LocalPlayer.GetModPlayer<StarsAbovePlayer>();
// Setting the text per tick to update and show our resource values.
text.SetText($"{modPlayer.animatedPromptDialogue}");
//text.SetText($"[c/5970cf:{modPlayer.judgementGauge} / 100]");
base.Update(gameTime);
}
}
}
| 412 | 0.88976 | 1 | 0.88976 | game-dev | MEDIA | 0.788408 | game-dev | 0.964396 | 1 | 0.964396 |
exmex/HC | 14,495 | Client/Code_Core/cocos2dx/actions/CCActionInstant.cpp | /****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCActionInstant.h"
#include "base_nodes/CCNode.h"
#include "sprite_nodes/CCSprite.h"
#include "script_support/CCScriptSupport.h"
#include "cocoa/CCZone.h"
NS_CC_BEGIN
//
// InstantAction
//
CCActionInstant::CCActionInstant() {
}
CCObject * CCActionInstant::copyWithZone(CCZone *pZone) {
CCZone *pNewZone = NULL;
CCActionInstant *pRet = NULL;
if (pZone && pZone->m_pCopyObject) {
pRet = (CCActionInstant*) (pZone->m_pCopyObject);
} else {
pRet = new CCActionInstant();
pZone = pNewZone = new CCZone(pRet);
}
CCFiniteTimeAction::copyWithZone(pZone);
CC_SAFE_DELETE(pNewZone);
return pRet;
}
bool CCActionInstant::isDone() {
return true;
}
void CCActionInstant::step(float dt) {
CC_UNUSED_PARAM(dt);
update(1);
}
void CCActionInstant::update(float time) {
CC_UNUSED_PARAM(time);
// nothing
}
CCFiniteTimeAction * CCActionInstant::reverse() {
return (CCFiniteTimeAction*) (copy()->autorelease());
}
//
// Show
//
CCShow* CCShow::create()
{
CCShow* pRet = new CCShow();
if (pRet) {
pRet->autorelease();
}
return pRet;
}
void CCShow::update(float time) {
CC_UNUSED_PARAM(time);
m_pTarget->setVisible(true);
}
CCFiniteTimeAction* CCShow::reverse() {
return (CCFiniteTimeAction*) (CCHide::create());
}
CCObject* CCShow::copyWithZone(CCZone *pZone) {
CCZone *pNewZone = NULL;
CCShow *pRet = NULL;
if (pZone && pZone->m_pCopyObject) {
pRet = (CCShow*) (pZone->m_pCopyObject);
} else {
pRet = new CCShow();
pZone = pNewZone = new CCZone(pRet);
}
CCActionInstant::copyWithZone(pZone);
CC_SAFE_DELETE(pNewZone);
return pRet;
}
//
// Hide
//
CCHide * CCHide::create()
{
CCHide *pRet = new CCHide();
if (pRet) {
pRet->autorelease();
}
return pRet;
}
void CCHide::update(float time) {
CC_UNUSED_PARAM(time);
m_pTarget->setVisible(false);
}
CCFiniteTimeAction *CCHide::reverse() {
return (CCFiniteTimeAction*) (CCShow::create());
}
CCObject* CCHide::copyWithZone(CCZone *pZone) {
CCZone *pNewZone = NULL;
CCHide *pRet = NULL;
if (pZone && pZone->m_pCopyObject) {
pRet = (CCHide*) (pZone->m_pCopyObject);
} else {
pRet = new CCHide();
pZone = pNewZone = new CCZone(pRet);
}
CCActionInstant::copyWithZone(pZone);
CC_SAFE_DELETE(pNewZone);
return pRet;
}
//
// ToggleVisibility
//
CCToggleVisibility * CCToggleVisibility::create()
{
CCToggleVisibility *pRet = new CCToggleVisibility();
if (pRet)
{
pRet->autorelease();
}
return pRet;
}
void CCToggleVisibility::update(float time)
{
CC_UNUSED_PARAM(time);
m_pTarget->setVisible(!m_pTarget->isVisible());
}
CCObject* CCToggleVisibility::copyWithZone(CCZone *pZone)
{
CCZone *pNewZone = NULL;
CCToggleVisibility *pRet = NULL;
if (pZone && pZone->m_pCopyObject) {
pRet = (CCToggleVisibility*) (pZone->m_pCopyObject);
} else {
pRet = new CCToggleVisibility();
pZone = pNewZone = new CCZone(pRet);
}
CCActionInstant::copyWithZone(pZone);
CC_SAFE_DELETE(pNewZone);
return pRet;
}
//
// Remove Self
//
CCRemoveSelf * CCRemoveSelf::create(bool isNeedCleanUp /*= true*/)
{
CCRemoveSelf *pRet = new CCRemoveSelf();
if (pRet && pRet->init(isNeedCleanUp)) {
pRet->autorelease();
}
return pRet;
}
bool CCRemoveSelf::init(bool isNeedCleanUp) {
m_bIsNeedCleanUp = isNeedCleanUp;
return true;
}
void CCRemoveSelf::update(float time) {
CC_UNUSED_PARAM(time);
m_pTarget->removeFromParentAndCleanup(m_bIsNeedCleanUp);
}
CCFiniteTimeAction *CCRemoveSelf::reverse() {
return (CCFiniteTimeAction*) (CCRemoveSelf::create(m_bIsNeedCleanUp));
}
CCObject* CCRemoveSelf::copyWithZone(CCZone *pZone) {
CCZone *pNewZone = NULL;
CCRemoveSelf *pRet = NULL;
if (pZone && pZone->m_pCopyObject) {
pRet = (CCRemoveSelf*) (pZone->m_pCopyObject);
} else {
pRet = new CCRemoveSelf();
pZone = pNewZone = new CCZone(pRet);
}
CCActionInstant::copyWithZone(pZone);
pRet->init(m_bIsNeedCleanUp);
CC_SAFE_DELETE(pNewZone);
return pRet;
}
//
// FlipX
//
CCFlipX *CCFlipX::create(bool x)
{
CCFlipX *pRet = new CCFlipX();
if (pRet && pRet->initWithFlipX(x)) {
pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
bool CCFlipX::initWithFlipX(bool x) {
m_bFlipX = x;
return true;
}
void CCFlipX::update(float time) {
CC_UNUSED_PARAM(time);
((CCSprite*) (m_pTarget))->setFlipX(m_bFlipX);
}
CCFiniteTimeAction* CCFlipX::reverse() {
return CCFlipX::create(!m_bFlipX);
}
CCObject * CCFlipX::copyWithZone(CCZone *pZone) {
CCZone *pNewZone = NULL;
CCFlipX *pRet = NULL;
if (pZone && pZone->m_pCopyObject) {
pRet = (CCFlipX*) (pZone->m_pCopyObject);
} else {
pRet = new CCFlipX();
pZone = pNewZone = new CCZone(pRet);
}
CCActionInstant::copyWithZone(pZone);
pRet->initWithFlipX(m_bFlipX);
CC_SAFE_DELETE(pNewZone);
return pRet;
}
//
// FlipY
//
CCFlipY * CCFlipY::create(bool y)
{
CCFlipY *pRet = new CCFlipY();
if (pRet && pRet->initWithFlipY(y)) {
pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
bool CCFlipY::initWithFlipY(bool y) {
m_bFlipY = y;
return true;
}
void CCFlipY::update(float time) {
CC_UNUSED_PARAM(time);
((CCSprite*) (m_pTarget))->setFlipY(m_bFlipY);
}
CCFiniteTimeAction* CCFlipY::reverse() {
return CCFlipY::create(!m_bFlipY);
}
CCObject* CCFlipY::copyWithZone(CCZone *pZone) {
CCZone *pNewZone = NULL;
CCFlipY *pRet = NULL;
if (pZone && pZone->m_pCopyObject) {
pRet = (CCFlipY*) (pZone->m_pCopyObject);
} else {
pRet = new CCFlipY();
pZone = pNewZone = new CCZone(pRet);
}
CCActionInstant::copyWithZone(pZone);
pRet->initWithFlipY(m_bFlipY);
CC_SAFE_DELETE(pNewZone);
return pRet;
}
//
// Place
//
CCPlace* CCPlace::create(const CCPoint& pos)
{
CCPlace *pRet = new CCPlace();
if (pRet && pRet->initWithPosition(pos)) {
pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
bool CCPlace::initWithPosition(const CCPoint& pos) {
m_tPosition = pos;
return true;
}
CCObject * CCPlace::copyWithZone(CCZone *pZone) {
CCZone *pNewZone = NULL;
CCPlace *pRet = NULL;
if (pZone && pZone->m_pCopyObject) {
pRet = (CCPlace*) (pZone->m_pCopyObject);
} else {
pRet = new CCPlace();
pZone = pNewZone = new CCZone(pRet);
}
CCActionInstant::copyWithZone(pZone);
pRet->initWithPosition(m_tPosition);
CC_SAFE_DELETE(pNewZone);
return pRet;
}
void CCPlace::update(float time) {
CC_UNUSED_PARAM(time);
m_pTarget->setPosition(m_tPosition);
}
//
// CallFunc
//
CCCallFunc * CCCallFunc::create(CCObject* pSelectorTarget, SEL_CallFunc selector)
{
CCCallFunc *pRet = new CCCallFunc();
if (pRet && pRet->initWithTarget(pSelectorTarget)) {
pRet->m_pCallFunc = selector;
pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
CCCallFunc * CCCallFunc::create(int nHandler)
{
CCCallFunc *pRet = new CCCallFunc();
if (pRet) {
pRet->m_nScriptHandler = nHandler;
pRet->autorelease();
}
else{
CC_SAFE_DELETE(pRet);
}
return pRet;
}
bool CCCallFunc::initWithTarget(CCObject* pSelectorTarget) {
if (pSelectorTarget)
{
pSelectorTarget->retain();
}
if (m_pSelectorTarget)
{
m_pSelectorTarget->release();
}
m_pSelectorTarget = pSelectorTarget;
return true;
}
CCCallFunc::~CCCallFunc(void)
{
if (m_nScriptHandler)
{
cocos2d::CCScriptEngineManager::sharedManager()->getScriptEngine()->removeScriptHandler(m_nScriptHandler);
}
CC_SAFE_RELEASE(m_pSelectorTarget);
}
CCObject * CCCallFunc::copyWithZone(CCZone *pZone) {
CCZone* pNewZone = NULL;
CCCallFunc* pRet = NULL;
if (pZone && pZone->m_pCopyObject) {
//in case of being called at sub class
pRet = (CCCallFunc*) (pZone->m_pCopyObject);
} else {
pRet = new CCCallFunc();
pZone = pNewZone = new CCZone(pRet);
}
CCActionInstant::copyWithZone(pZone);
pRet->initWithTarget(m_pSelectorTarget);
pRet->m_pCallFunc = m_pCallFunc;
if (m_nScriptHandler > 0 ) {
pRet->m_nScriptHandler = cocos2d::CCScriptEngineManager::sharedManager()->getScriptEngine()->reallocateScriptHandler(m_nScriptHandler);
}
CC_SAFE_DELETE(pNewZone);
return pRet;
}
void CCCallFunc::update(float time) {
CC_UNUSED_PARAM(time);
this->execute();
}
void CCCallFunc::execute() {
if (m_pCallFunc) {
(m_pSelectorTarget->*m_pCallFunc)();
}
if (m_nScriptHandler) {
CCScriptEngineManager::sharedManager()->getScriptEngine()->executeCallFuncActionEvent(this);
}
}
//
// CallFuncN
//
void CCCallFuncN::execute() {
if (m_pCallFuncN) {
(m_pSelectorTarget->*m_pCallFuncN)(m_pTarget);
}
if (m_nScriptHandler) {
CCScriptEngineManager::sharedManager()->getScriptEngine()->executeCallFuncActionEvent(this, m_pTarget);
}
}
CCCallFuncN * CCCallFuncN::create(CCObject* pSelectorTarget, SEL_CallFuncN selector)
{
CCCallFuncN *pRet = new CCCallFuncN();
if (pRet && pRet->initWithTarget(pSelectorTarget, selector))
{
pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
CCCallFuncN * CCCallFuncN::create(int nHandler)
{
CCCallFuncN *pRet = new CCCallFuncN();
if (pRet) {
pRet->m_nScriptHandler = nHandler;
pRet->autorelease();
}
else{
CC_SAFE_DELETE(pRet);
}
return pRet;
}
bool CCCallFuncN::initWithTarget(CCObject* pSelectorTarget,
SEL_CallFuncN selector) {
if (CCCallFunc::initWithTarget(pSelectorTarget)) {
m_pCallFuncN = selector;
return true;
}
return false;
}
CCObject * CCCallFuncN::copyWithZone(CCZone* zone) {
CCZone* pNewZone = NULL;
CCCallFuncN* pRet = NULL;
if (zone && zone->m_pCopyObject) {
//in case of being called at sub class
pRet = (CCCallFuncN*) (zone->m_pCopyObject);
} else {
pRet = new CCCallFuncN();
zone = pNewZone = new CCZone(pRet);
}
CCCallFunc::copyWithZone(zone);
pRet->initWithTarget(m_pSelectorTarget, m_pCallFuncN);
CC_SAFE_DELETE(pNewZone);
return pRet;
}
//
// CallFuncND
//
CCCallFuncND * CCCallFuncND::create(CCObject* pSelectorTarget, SEL_CallFuncND selector, void* d)
{
CCCallFuncND* pRet = new CCCallFuncND();
if (pRet && pRet->initWithTarget(pSelectorTarget, selector, d)) {
pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
bool CCCallFuncND::initWithTarget(CCObject* pSelectorTarget,
SEL_CallFuncND selector, void* d) {
if (CCCallFunc::initWithTarget(pSelectorTarget)) {
m_pData = d;
m_pCallFuncND = selector;
return true;
}
return false;
}
CCObject * CCCallFuncND::copyWithZone(CCZone* zone) {
CCZone* pNewZone = NULL;
CCCallFuncND* pRet = NULL;
if (zone && zone->m_pCopyObject) {
//in case of being called at sub class
pRet = (CCCallFuncND*) (zone->m_pCopyObject);
} else {
pRet = new CCCallFuncND();
zone = pNewZone = new CCZone(pRet);
}
CCCallFunc::copyWithZone(zone);
pRet->initWithTarget(m_pSelectorTarget, m_pCallFuncND, m_pData);
CC_SAFE_DELETE(pNewZone);
return pRet;
}
void CCCallFuncND::execute() {
if (m_pCallFuncND) {
(m_pSelectorTarget->*m_pCallFuncND)(m_pTarget, m_pData);
}
}
//
// CCCallFuncO
//
CCCallFuncO::CCCallFuncO() :
m_pObject(NULL) {
}
CCCallFuncO::~CCCallFuncO() {
CC_SAFE_RELEASE(m_pObject);
}
void CCCallFuncO::execute() {
if (m_pCallFuncO) {
(m_pSelectorTarget->*m_pCallFuncO)(m_pObject);
}
}
CCCallFuncO * CCCallFuncO::create(CCObject* pSelectorTarget, SEL_CallFuncO selector, CCObject* pObject)
{
CCCallFuncO *pRet = new CCCallFuncO();
if (pRet && pRet->initWithTarget(pSelectorTarget, selector, pObject)) {
pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
bool CCCallFuncO::initWithTarget(CCObject* pSelectorTarget,
SEL_CallFuncO selector, CCObject* pObject) {
if (CCCallFunc::initWithTarget(pSelectorTarget)) {
m_pObject = pObject;
CC_SAFE_RETAIN(m_pObject);
m_pCallFuncO = selector;
return true;
}
return false;
}
CCObject * CCCallFuncO::copyWithZone(CCZone* zone) {
CCZone* pNewZone = NULL;
CCCallFuncO* pRet = NULL;
if (zone && zone->m_pCopyObject) {
//in case of being called at sub class
pRet = (CCCallFuncO*) (zone->m_pCopyObject);
} else {
pRet = new CCCallFuncO();
zone = pNewZone = new CCZone(pRet);
}
CCCallFunc::copyWithZone(zone);
pRet->initWithTarget(m_pSelectorTarget, m_pCallFuncO, m_pObject);
CC_SAFE_DELETE(pNewZone);
return pRet;
}
NS_CC_END
| 412 | 0.734867 | 1 | 0.734867 | game-dev | MEDIA | 0.591677 | game-dev | 0.879586 | 1 | 0.879586 |
ProjectSkyfire/SkyFire.406a | 9,892 | src/server/game/Entities/Creature/TemporarySummon.cpp | /*
* Copyright (C) 2011-2019 Project SkyFire <http://www.projectskyfire.org/>
* Copyright (C) 2008-2019 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2019 MaNGOS <https://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Log.h"
#include "ObjectAccessor.h"
#include "CreatureAI.h"
#include "ObjectMgr.h"
#include "TemporarySummon.h"
TempSummon::TempSummon(SummonPropertiesEntry const* properties, Unit* owner, bool isWorldObject) :
Creature(isWorldObject), m_Properties(properties), m_type(TEMPSUMMON_MANUAL_DESPAWN),
_timer(0), m_lifetime(0)
{
m_summonerGUID = owner ? owner->GetGUID() : 0;
m_unitTypeMask |= UNIT_MASK_SUMMON;
}
Unit* TempSummon::GetSummoner() const
{
return m_summonerGUID ? ObjectAccessor::GetUnit(*this, m_summonerGUID) : NULL;
}
void TempSummon::Update(uint32 diff)
{
Creature::Update(diff);
if (_deathState == DEAD)
{
UnSummon();
return;
}
switch (m_type)
{
case TEMPSUMMON_MANUAL_DESPAWN:
break;
case TEMPSUMMON_TIMED_DESPAWN:
{
if (_timer <= diff)
{
UnSummon();
return;
}
_timer -= diff;
break;
}
case TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT:
{
if (!isInCombat())
{
if (_timer <= diff)
{
UnSummon();
return;
}
_timer -= diff;
}
else if (_timer != m_lifetime)
_timer = m_lifetime;
break;
}
case TEMPSUMMON_CORPSE_TIMED_DESPAWN:
{
if (_deathState == CORPSE)
{
if (_timer <= diff)
{
UnSummon();
return;
}
_timer -= diff;
}
break;
}
case TEMPSUMMON_CORPSE_DESPAWN:
{
// if _deathState is DEAD, CORPSE was skipped
if (_deathState == CORPSE || _deathState == DEAD)
{
UnSummon();
return;
}
break;
}
case TEMPSUMMON_DEAD_DESPAWN:
{
if (_deathState == DEAD)
{
UnSummon();
return;
}
break;
}
case TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN:
{
// if _deathState is DEAD, CORPSE was skipped
if (_deathState == CORPSE || _deathState == DEAD)
{
UnSummon();
return;
}
if (!isInCombat())
{
if (_timer <= diff)
{
UnSummon();
return;
}
else
_timer -= diff;
}
else if (_timer != m_lifetime)
_timer = m_lifetime;
break;
}
case TEMPSUMMON_TIMED_OR_DEAD_DESPAWN:
{
// if _deathState is DEAD, CORPSE was skipped
if (_deathState == DEAD)
{
UnSummon();
return;
}
if (!isInCombat() && isAlive())
{
if (_timer <= diff)
{
UnSummon();
return;
}
else
_timer -= diff;
}
else if (_timer != m_lifetime)
_timer = m_lifetime;
break;
}
default:
UnSummon();
sLog->outError("Temporary summoned creature (entry: %u) have unknown type %u of ", GetEntry(), m_type);
break;
}
}
void TempSummon::InitStats(uint32 duration)
{
ASSERT(!isPet());
_timer = duration;
m_lifetime = duration;
if (m_type == TEMPSUMMON_MANUAL_DESPAWN)
m_type = (duration == 0) ? TEMPSUMMON_DEAD_DESPAWN : TEMPSUMMON_TIMED_DESPAWN;
Unit* owner = GetSummoner();
if (owner && isTrigger() && _spells[0])
{
setFaction(owner->getFaction());
SetLevel(owner->getLevel());
if (owner->GetTypeId() == TYPEID_PLAYER)
_ControlledByPlayer = true;
}
if (!m_Properties)
return;
if (owner)
{
if (uint32 slot = m_Properties->Slot)
{
if (owner->m_SummonSlot[slot] && owner->m_SummonSlot[slot] != GetGUID())
{
Creature* oldSummon = GetMap()->GetCreature(owner->m_SummonSlot[slot]);
if (oldSummon && oldSummon->isSummon())
oldSummon->ToTempSummon()->UnSummon();
}
owner->m_SummonSlot[slot] = GetGUID();
}
}
if (m_Properties->Faction)
setFaction(m_Properties->Faction);
else if (IsVehicle() && owner) // properties should be vehicle
setFaction(owner->getFaction());
}
void TempSummon::InitSummon()
{
Unit* owner = GetSummoner();
if (owner)
{
if (owner->GetTypeId() == TYPEID_UNIT && owner->ToCreature()->IsAIEnabled)
owner->ToCreature()->AI()->JustSummoned(this);
if (IsAIEnabled)
AI()->IsSummonedBy(owner);
}
}
void TempSummon::SetTempSummonType(TempSummonType type)
{
m_type = type;
}
void TempSummon::UnSummon(uint32 msTime)
{
if (msTime)
{
ForcedUnsummonDelayEvent* pEvent = new ForcedUnsummonDelayEvent(*this);
_Events.AddEvent(pEvent, _Events.CalculateTime(msTime));
return;
}
//ASSERT(!isPet());
if (isPet())
{
((Pet*)this)->Remove(PET_SLOT_OTHER_PET);
ASSERT(!IsInWorld());
return;
}
Unit* owner = GetSummoner();
if (owner && owner->GetTypeId() == TYPEID_UNIT && owner->ToCreature()->IsAIEnabled)
owner->ToCreature()->AI()->SummonedCreatureDespawn(this);
AddObjectToRemoveList();
}
bool ForcedUnsummonDelayEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/)
{
_owner.UnSummon();
return true;
}
void TempSummon::RemoveFromWorld()
{
if (!IsInWorld())
return;
if (m_Properties)
if (uint32 slot = m_Properties->Slot)
if (Unit* owner = GetSummoner())
if (owner->m_SummonSlot[slot] == GetGUID())
owner->m_SummonSlot[slot] = 0;
//if (GetOwnerGUID())
// sLog->outError("Unit %u has owner guid when removed from world", GetEntry());
Creature::RemoveFromWorld();
}
Minion::Minion(SummonPropertiesEntry const* properties, Unit* owner, bool isWorldObject) : TempSummon(properties, owner, isWorldObject), _owner(owner)
{
ASSERT(_owner);
m_unitTypeMask |= UNIT_MASK_MINION;
m_followAngle = PET_FOLLOW_ANGLE;
}
void Minion::InitStats(uint32 duration)
{
TempSummon::InitStats(duration);
SetReactState(REACT_PASSIVE);
SetCreatorGUID(_owner->GetGUID());
setFaction(_owner->getFaction());
_owner->SetMinion(this, true, PET_SLOT_UNK_SLOT);
}
void Minion::RemoveFromWorld()
{
if (!IsInWorld())
return;
_owner->SetMinion(this, false, PET_SLOT_UNK_SLOT);
TempSummon::RemoveFromWorld();
}
bool Minion::IsGuardianPet() const
{
return isPet() || (m_Properties && m_Properties->Category == SUMMON_CATEGORY_PET);
}
Guardian::Guardian(SummonPropertiesEntry const* properties, Unit* owner, bool isWorldObject) : Minion(properties, owner, isWorldObject), m_bonusSpellDamage(0)
{
memset(m_statFromOwner, 0, sizeof(float)*MAX_STATS);
m_unitTypeMask |= UNIT_MASK_GUARDIAN;
if (properties && properties->Type == SUMMON_TYPE_PET)
{
m_unitTypeMask |= UNIT_MASK_CONTROLABLE_GUARDIAN;
InitCharmInfo();
}
}
void Guardian::InitStats(uint32 duration)
{
Minion::InitStats(duration);
InitStatsForLevel(_owner->getLevel());
if (_owner->GetTypeId() == TYPEID_PLAYER && HasUnitTypeMask(UNIT_MASK_CONTROLABLE_GUARDIAN))
m_charmInfo->InitCharmCreateSpells();
SetReactState(REACT_AGGRESSIVE);
}
void Guardian::InitSummon()
{
TempSummon::InitSummon();
if (_owner->GetTypeId() == TYPEID_PLAYER
&& _owner->GetMinionGUID() == GetGUID()
&& !_owner->GetCharmGUID())
_owner->ToPlayer()->CharmSpellInitialize();
}
Puppet::Puppet(SummonPropertiesEntry const* properties, Unit* owner) : Minion(properties, owner, false) //maybe true?
{
ASSERT(owner->GetTypeId() == TYPEID_PLAYER);
_owner = (Player*)owner;
m_unitTypeMask |= UNIT_MASK_PUPPET;
}
void Puppet::InitStats(uint32 duration)
{
Minion::InitStats(duration);
SetLevel(_owner->getLevel());
SetReactState(REACT_PASSIVE);
}
void Puppet::InitSummon()
{
Minion::InitSummon();
if (!SetCharmedBy(_owner, CHARM_TYPE_POSSESS))
ASSERT(false);
}
void Puppet::Update(uint32 time)
{
Minion::Update(time);
//check if caster is channelling?
if (IsInWorld())
{
if (!isAlive())
{
UnSummon();
// TODO: why long distance .die does not remove it
}
}
}
void Puppet::RemoveFromWorld()
{
if (!IsInWorld())
return;
RemoveCharmedBy(NULL);
Minion::RemoveFromWorld();
}
| 412 | 0.957289 | 1 | 0.957289 | game-dev | MEDIA | 0.952071 | game-dev | 0.994965 | 1 | 0.994965 |
microsoft/botframework-components | 1,618 | skills/csharp/tests/itsmskill.tests/Flow/Utterances/ITSMTestUtterances.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Generic;
using Luis;
using Microsoft.Bot.Builder;
using static Luis.ITSMLuis;
namespace ITSMSkill.Tests.Flow.Utterances
{
public class ITSMTestUtterances : BaseTestUtterances<ITSMLuis>
{
public override ITSMLuis NoneIntent { get; } = new ITSMLuis
{
Intents = new Dictionary<Intent, IntentScore>
{
{ Intent.None, new IntentScore() { Score = TopIntentScore } }
}
};
protected void AddIntent(
string userInput,
Intent intent,
string[][] attributeType = null,
string[][] ticketState = null,
string[][] urgencyLevel = null,
string[] ticketNumber = null,
string[] closeReason = null,
string[] ticketTitle = null)
{
var resultIntent = new ITSMLuis
{
Text = userInput,
Intents = new Dictionary<Intent, IntentScore>
{
{ intent, new IntentScore() { Score = TopIntentScore } }
}
};
resultIntent.Entities = new _Entities
{
AttributeType = attributeType,
TicketState = ticketState,
UrgencyLevel = urgencyLevel,
TicketNumber = ticketNumber,
CloseReason = closeReason,
TicketTitle = ticketTitle
};
Add(userInput, resultIntent);
}
}
}
| 412 | 0.782846 | 1 | 0.782846 | game-dev | MEDIA | 0.344402 | game-dev | 0.888535 | 1 | 0.888535 |
EOS-team/EOS | 5,835 | src/embodied-intelligence/src/3D_human_pose_recognition/ios_sdk/UnityDEBUG/ForDebug/Library/PackageCache/com.unity.timeline@1.6.4/Editor/Window/ViewModel/TimelineWindowViewPrefs.cs | using UnityEngine;
using UnityEngine.Timeline;
using UnityObject = UnityEngine.Object;
using ViewModelsMap = System.Collections.Generic.Dictionary<UnityEngine.Timeline.TimelineAsset, UnityEditor.Timeline.ScriptableObjectViewPrefs<UnityEditor.Timeline.TimelineAssetViewModel>>;
using ViewModelsList = System.Collections.Generic.List<UnityEditor.Timeline.ScriptableObjectViewPrefs<UnityEditor.Timeline.TimelineAssetViewModel>>;
namespace UnityEditor.Timeline
{
static class TimelineWindowViewPrefs
{
public const string FilePath = "Library/Timeline";
static readonly ViewModelsMap k_ViewModelsMap = new ViewModelsMap();
static readonly ViewModelsList k_UnassociatedViewModels = new ViewModelsList();
public static int viewModelCount
{
get { return k_ViewModelsMap.Count + k_UnassociatedViewModels.Count; }
}
public static TimelineAssetViewModel GetOrCreateViewModel(TimelineAsset asset)
{
if (asset == null)
return CreateUnassociatedViewModel();
ScriptableObjectViewPrefs<TimelineAssetViewModel> vm;
if (k_ViewModelsMap.TryGetValue(asset, out vm))
return vm.viewModel;
return CreateViewModel(asset).viewModel;
}
public static TimelineAssetViewModel CreateUnassociatedViewModel()
{
var vm = new ScriptableObjectViewPrefs<TimelineAssetViewModel>(null, FilePath);
k_UnassociatedViewModels.Add(vm);
return vm.viewModel;
}
static ScriptableObjectViewPrefs<TimelineAssetViewModel> CreateViewModel(TimelineAsset asset)
{
var vm = new ScriptableObjectViewPrefs<TimelineAssetViewModel>(asset, FilePath);
k_ViewModelsMap.Add(asset, vm);
return vm;
}
public static void SaveViewModel(TimelineAsset asset)
{
if (asset == null)
return;
ScriptableObjectViewPrefs<TimelineAssetViewModel> vm;
if (!k_ViewModelsMap.TryGetValue(asset, out vm))
vm = CreateViewModel(asset);
vm.Save();
}
public static void SaveAll()
{
foreach (var kvp in k_ViewModelsMap)
kvp.Value.Save();
}
public static void UnloadViewModel(TimelineAsset asset)
{
ScriptableObjectViewPrefs<TimelineAssetViewModel> vm;
if (k_ViewModelsMap.TryGetValue(asset, out vm))
{
vm.Dispose();
k_ViewModelsMap.Remove(asset);
}
}
public static void UnloadAllViewModels()
{
foreach (var kvp in k_ViewModelsMap)
kvp.Value.Dispose();
foreach (var vm in k_UnassociatedViewModels)
vm.Dispose();
k_ViewModelsMap.Clear();
k_UnassociatedViewModels.Clear();
}
public static TrackViewModelData GetTrackViewModelData(TrackAsset track)
{
if (track == null)
return new TrackViewModelData();
if (track.timelineAsset == null)
return new TrackViewModelData();
var prefs = GetOrCreateViewModel(track.timelineAsset);
TrackViewModelData trackData;
if (prefs.tracksViewModelData.TryGetValue(track, out trackData))
{
return trackData;
}
trackData = new TrackViewModelData();
prefs.tracksViewModelData[track] = trackData;
return trackData;
}
public static bool IsTrackCollapsed(TrackAsset track)
{
if (track == null)
return true;
return GetTrackViewModelData(track).collapsed;
}
public static void SetTrackCollapsed(TrackAsset track, bool collapsed)
{
if (track == null)
return;
GetTrackViewModelData(track).collapsed = collapsed;
}
public static bool IsShowMarkers(TrackAsset track)
{
if (track == null)
return true;
return GetTrackViewModelData(track).showMarkers;
}
public static void SetTrackShowMarkers(TrackAsset track, bool collapsed)
{
if (track == null)
return;
GetTrackViewModelData(track).showMarkers = collapsed;
}
public static bool GetShowInlineCurves(TrackAsset track)
{
if (track == null)
return false;
return GetTrackViewModelData(track).showInlineCurves;
}
public static void SetShowInlineCurves(TrackAsset track, bool inlineOn)
{
if (track == null)
return;
GetTrackViewModelData(track).showInlineCurves = inlineOn;
}
public static float GetInlineCurveHeight(TrackAsset asset)
{
if (asset == null)
return TrackViewModelData.DefaultinlineAnimationCurveHeight;
return GetTrackViewModelData(asset).inlineAnimationCurveHeight;
}
public static void SetInlineCurveHeight(TrackAsset asset, float height)
{
if (asset != null)
GetTrackViewModelData(asset).inlineAnimationCurveHeight = height;
}
public static int GetTrackHeightExtension(TrackAsset asset)
{
if (asset == null)
return 0;
return GetTrackViewModelData(asset).trackHeightExtension;
}
public static void SetTrackHeightExtension(TrackAsset asset, int height)
{
if (asset != null)
GetTrackViewModelData(asset).trackHeightExtension = height;
}
}
}
| 412 | 0.814418 | 1 | 0.814418 | game-dev | MEDIA | 0.503875 | game-dev,desktop-app | 0.913507 | 1 | 0.913507 |
leixiaohua1020/simplest_ffmpeg_device | 4,527 | simplest_ffmpeg_readcamera/include/SDL/SDL_timer.h | /*
SDL - Simple DirectMedia Layer
Copyright (C) 1997-2012 Sam Lantinga
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Sam Lantinga
slouken@libsdl.org
*/
#ifndef _SDL_timer_h
#define _SDL_timer_h
/** @file SDL_timer.h
* Header for the SDL time management routines
*/
#include "SDL_stdinc.h"
#include "SDL_error.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/** This is the OS scheduler timeslice, in milliseconds */
#define SDL_TIMESLICE 10
/** This is the maximum resolution of the SDL timer on all platforms */
#define TIMER_RESOLUTION 10 /**< Experimentally determined */
/**
* Get the number of milliseconds since the SDL library initialization.
* Note that this value wraps if the program runs for more than ~49 days.
*/
extern DECLSPEC Uint32 SDLCALL SDL_GetTicks(void);
/** Wait a specified number of milliseconds before returning */
extern DECLSPEC void SDLCALL SDL_Delay(Uint32 ms);
/** Function prototype for the timer callback function */
typedef Uint32 (SDLCALL *SDL_TimerCallback)(Uint32 interval);
/**
* Set a callback to run after the specified number of milliseconds has
* elapsed. The callback function is passed the current timer interval
* and returns the next timer interval. If the returned value is the
* same as the one passed in, the periodic alarm continues, otherwise a
* new alarm is scheduled. If the callback returns 0, the periodic alarm
* is cancelled.
*
* To cancel a currently running timer, call SDL_SetTimer(0, NULL);
*
* The timer callback function may run in a different thread than your
* main code, and so shouldn't call any functions from within itself.
*
* The maximum resolution of this timer is 10 ms, which means that if
* you request a 16 ms timer, your callback will run approximately 20 ms
* later on an unloaded system. If you wanted to set a flag signaling
* a frame update at 30 frames per second (every 33 ms), you might set a
* timer for 30 ms:
* @code SDL_SetTimer((33/10)*10, flag_update); @endcode
*
* If you use this function, you need to pass SDL_INIT_TIMER to SDL_Init().
*
* Under UNIX, you should not use raise or use SIGALRM and this function
* in the same program, as it is implemented using setitimer(). You also
* should not use this function in multi-threaded applications as signals
* to multi-threaded apps have undefined behavior in some implementations.
*
* This function returns 0 if successful, or -1 if there was an error.
*/
extern DECLSPEC int SDLCALL SDL_SetTimer(Uint32 interval, SDL_TimerCallback callback);
/** @name New timer API
* New timer API, supports multiple timers
* Written by Stephane Peter <megastep@lokigames.com>
*/
/*@{*/
/**
* Function prototype for the new timer callback function.
* The callback function is passed the current timer interval and returns
* the next timer interval. If the returned value is the same as the one
* passed in, the periodic alarm continues, otherwise a new alarm is
* scheduled. If the callback returns 0, the periodic alarm is cancelled.
*/
typedef Uint32 (SDLCALL *SDL_NewTimerCallback)(Uint32 interval, void *param);
/** Definition of the timer ID type */
typedef struct _SDL_TimerID *SDL_TimerID;
/** Add a new timer to the pool of timers already running.
* Returns a timer ID, or NULL when an error occurs.
*/
extern DECLSPEC SDL_TimerID SDLCALL SDL_AddTimer(Uint32 interval, SDL_NewTimerCallback callback, void *param);
/**
* Remove one of the multiple timers knowing its ID.
* Returns a boolean value indicating success.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_RemoveTimer(SDL_TimerID t);
/*@}*/
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* _SDL_timer_h */
| 412 | 0.741803 | 1 | 0.741803 | game-dev | MEDIA | 0.375493 | game-dev | 0.623213 | 1 | 0.623213 |
QiLi111/NR-Rec-FUS | 3,129 | utils/monai/utils/decorators.py | # Copyright (c) MONAI Consortium
# 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.
from __future__ import annotations
from functools import wraps
__all__ = ["RestartGenerator", "MethodReplacer"]
from typing import Callable, Generator
class RestartGenerator:
"""
Wraps a generator callable which will be called whenever this class is iterated and its result returned. This is
used to create an iterator which can start iteration over the given generator multiple times.
"""
def __init__(self, create_gen: Callable[[], Generator]) -> None:
self.create_gen = create_gen
def __iter__(self) -> Generator:
return self.create_gen()
class MethodReplacer:
"""
Base class for method decorators which can be used to replace methods pass to replace_method() with wrapped versions.
"""
replace_list_name = "__replacemethods__"
def __init__(self, meth: Callable) -> None:
self.meth = meth
def replace_method(self, meth):
"""
Return a new method to replace `meth` in the instantiated object, or `meth` to do nothing.
"""
return meth
def __set_name__(self, owner, name):
"""
Add the (name,self.replace_method) pair to the list named by replace_list_name in `owner`, creating the list and
replacing the constructor of `owner` if necessary. The replaced constructor will call the old one then do the
replacing operation of substituting, for each (name,self.replace_method) pair, the named method with the returned
value from self.replace_method.
"""
entry = (name, owner, self.replace_method)
if not hasattr(owner, self.replace_list_name):
oldinit = owner.__init__
# replace the constructor with a new one which calls the old then replaces methods
@wraps(oldinit)
def newinit(_self, *args, **kwargs):
oldinit(_self, *args, **kwargs)
# replace each listed method of this newly constructed object
for m, owner, replacer in getattr(_self, self.replace_list_name):
if isinstance(_self, owner):
meth = getattr(_self, m)
newmeth = replacer(meth)
setattr(_self, m, newmeth)
owner.__init__ = newinit
setattr(owner, self.replace_list_name, [entry])
else:
namelist = getattr(owner, self.replace_list_name)
if not any(nl[0] == name for nl in namelist):
namelist.append(entry)
setattr(owner, name, self.meth)
| 412 | 0.787702 | 1 | 0.787702 | game-dev | MEDIA | 0.276231 | game-dev | 0.935565 | 1 | 0.935565 |
lua9520/source-engine-2018-cstrike15_src | 33,711 | tools/toolutils/BaseToolSystem.cpp | //====== Copyright 1996-2005, Valve Corporation, All rights reserved. =======
//
// Purpose: Core Movie Maker UI API
//
//=============================================================================
#include "toolutils/basetoolsystem.h"
#include "toolframework/ienginetool.h"
#include "vgui/IPanel.h"
#include "vgui_controls/Controls.h"
#include "vgui_controls/Menu.h"
#include "vgui/ISurface.h"
#include "vgui_controls/Panel.h"
#include "vgui_controls/FileOpenDialog.h"
#include "vgui_controls/MessageBox.h"
#include "vgui/Cursor.h"
#include "vgui/iinput.h"
#include "vgui/ivgui.h"
#include "vgui_controls/AnimationController.h"
#include "ienginevgui.h"
#include "toolui.h"
#include "toolutils/toolmenubar.h"
#include "vgui/ilocalize.h"
#include "toolutils/enginetools_int.h"
#include "toolutils/vgui_tools.h"
#include "icvar.h"
#include "tier1/convar.h"
#include "datamodel/dmelementfactoryhelper.h"
#include "filesystem.h"
#include "vgui_controls/savedocumentquery.h"
#include "vgui_controls/perforcefilelistframe.h"
#include "toolutils/miniviewport.h"
#include "materialsystem/imaterialsystem.h"
#include "materialsystem/imaterial.h"
#include "materialsystem/IMesh.h"
#include "toolutils/BaseStatusBar.h"
#include "movieobjects/movieobjects.h"
#include "vgui_controls/KeyBoardEditorDialog.h"
#include "vgui_controls/KeyBindingHelpDialog.h"
#include "dmserializers/idmserializers.h"
#include "tier2/renderutils.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
extern IMaterialSystem *MaterialSystem();
class CGlobalFlexController : public IGlobalFlexController
{
public:
virtual int FindGlobalFlexController( const char *name )
{
return clienttools->FindGlobalFlexcontroller( name );
}
virtual const char *GetGlobalFlexControllerName( int idx )
{
return clienttools->GetGlobalFlexControllerName( idx );
}
};
static CGlobalFlexController g_GlobalFlexController;
extern IGlobalFlexController *g_pGlobalFlexController;
//-----------------------------------------------------------------------------
// Singleton interfaces
//-----------------------------------------------------------------------------
IServerTools *servertools = NULL;
IClientTools *clienttools = NULL;
//-----------------------------------------------------------------------------
// External functions
//-----------------------------------------------------------------------------
void RegisterTool( IToolSystem *tool );
//-----------------------------------------------------------------------------
// Base tool system constructor
//-----------------------------------------------------------------------------
CBaseToolSystem::CBaseToolSystem( const char *pToolName /*="CBaseToolSystem"*/ ) :
BaseClass( NULL, pToolName ),
m_pBackground( 0 ),
m_pLogo( 0 )
{
RegisterTool( this );
SetAutoDelete( false );
m_bGameInputEnabled = false;
m_bFullscreenMode = false;
m_bIsActive = false;
m_bFullscreenToolModeEnabled = false;
m_MostRecentlyFocused = NULL;
SetKeyBoardInputEnabled( true );
input()->RegisterKeyCodeUnhandledListener( GetVPanel() );
m_pFileOpenStateMachine = new vgui::FileOpenStateMachine( this, this );
m_pFileOpenStateMachine->AddActionSignalTarget( this );
}
void CBaseToolSystem::ApplySchemeSettings(IScheme *pScheme)
{
BaseClass::ApplySchemeSettings(pScheme);
SetKeyBoardInputEnabled( true );
}
//-----------------------------------------------------------------------------
// Derived classes can implement this to get a new scheme to be applied to this tool
//-----------------------------------------------------------------------------
vgui::HScheme CBaseToolSystem::GetToolScheme()
{
return vgui::scheme()->LoadSchemeFromFile( "Resource/BoxRocket.res", GetToolName() );
}
//-----------------------------------------------------------------------------
// Called at the end of engine startup (after client .dll and server .dll have been loaded)
//-----------------------------------------------------------------------------
bool CBaseToolSystem::Init( )
{
// Read shared localization info
g_pVGuiLocalize->AddFile( "resource/dmecontrols_%language%.txt" );
g_pVGuiLocalize->AddFile( "resource/toolshared_%language%.txt" );
g_pVGuiLocalize->AddFile( "Resource/vgui_%language%.txt" );
g_pVGuiLocalize->AddFile( "Resource/platform_%language%.txt" );
g_pVGuiLocalize->AddFile( "resource/boxrocket_%language%.txt" );
// Create the tool workspace
SetParent( VGui_GetToolRootPanel() );
// Deal with scheme
vgui::HScheme hToolScheme = GetToolScheme();
if ( hToolScheme != 0 )
{
SetScheme( hToolScheme );
}
m_KeyBindingsHandle = Panel::CreateKeyBindingsContext( GetBindingsContextFile(), "GAME" );
SetKeyBindingsContext( m_KeyBindingsHandle );
LoadKeyBindings();
const char *pszBackground = GetBackgroundTextureName();
if ( pszBackground )
{
m_pBackground = materials->FindMaterial( GetBackgroundTextureName() , TEXTURE_GROUP_VGUI );
m_pBackground->IncrementReferenceCount();
}
const char *pszLogo = GetLogoTextureName();
if ( pszLogo )
{
m_pLogo = materials->FindMaterial( GetLogoTextureName(), TEXTURE_GROUP_VGUI );
m_pLogo->IncrementReferenceCount();
}
// Make the tool workspace the size of the screen
int w, h;
surface()->GetScreenSize( w, h );
SetBounds( 0, 0, w, h );
SetPaintBackgroundEnabled( true );
SetPaintBorderEnabled( false );
SetPaintEnabled( false );
SetCursor( vgui::dc_none );
SetVisible( false );
// Create the tool UI
m_pToolUI = new CToolUI( this, "ToolUI", this );
// Create the mini viewport
m_hMiniViewport = CreateMiniViewport( GetClientArea() );
Assert( m_hMiniViewport.Get() );
return true;
}
void CBaseToolSystem::ShowMiniViewport( bool state )
{
if ( !m_hMiniViewport.Get() )
return;
m_hMiniViewport->SetVisible( state );
}
void CBaseToolSystem::SetMiniViewportBounds( int x, int y, int width, int height )
{
if ( m_hMiniViewport )
{
m_hMiniViewport->SetBounds( x, y, width, height );
}
}
void CBaseToolSystem::SetMiniViewportText( const char *pText )
{
if ( m_hMiniViewport )
{
m_hMiniViewport->SetOverlayText( pText );
}
}
void CBaseToolSystem::GetMiniViewportEngineBounds( int &x, int &y, int &width, int &height )
{
if ( m_hMiniViewport )
{
m_hMiniViewport->GetEngineBounds( x, y, width, height );
}
}
vgui::Panel *CBaseToolSystem::GetMiniViewport( void )
{
return m_hMiniViewport;
}
//-----------------------------------------------------------------------------
// Shut down
//-----------------------------------------------------------------------------
void CBaseToolSystem::Shutdown()
{
if ( m_pBackground )
{
m_pBackground->DecrementReferenceCount();
}
if ( m_pLogo )
{
m_pLogo->DecrementReferenceCount();
}
if ( m_hMiniViewport.Get() )
{
delete m_hMiniViewport.Get();
}
// Delete ourselves
MarkForDeletion();
// Make sure anything "marked for deletion"
// actually gets deleted before this dll goes away
vgui::ivgui()->RunFrame();
}
//-----------------------------------------------------------------------------
// Can the tool quit?
//-----------------------------------------------------------------------------
bool CBaseToolSystem::CanQuit( const char* /*pExitMsg*/ )
{
return true;
}
//-----------------------------------------------------------------------------
// Client, server init + shutdown
//-----------------------------------------------------------------------------
bool CBaseToolSystem::ServerInit( CreateInterfaceFn serverFactory )
{
servertools = ( IServerTools * )serverFactory( VSERVERTOOLS_INTERFACE_VERSION, NULL );
if ( !servertools )
{
Error( "CBaseToolSystem::PostInit: Unable to get '%s' interface from game .dll\n", VSERVERTOOLS_INTERFACE_VERSION );
}
return true;
}
bool CBaseToolSystem::ClientInit( CreateInterfaceFn clientFactory )
{
clienttools = ( IClientTools * )clientFactory( VCLIENTTOOLS_INTERFACE_VERSION, NULL );
if ( !clienttools )
{
Error( "CBaseToolSystem::PostInit: Unable to get '%s' interface from client .dll\n", VCLIENTTOOLS_INTERFACE_VERSION );
}
else
{
g_pGlobalFlexController = &g_GlobalFlexController; // don't set this until clienttools is connected
}
return true;
}
void CBaseToolSystem::ServerShutdown()
{
servertools = NULL;
}
void CBaseToolSystem::ClientShutdown()
{
clienttools = NULL;
}
//-----------------------------------------------------------------------------
// Level init, shutdown for server
//-----------------------------------------------------------------------------
void CBaseToolSystem::ServerLevelInitPreEntity()
{
}
void CBaseToolSystem::ServerLevelInitPostEntity()
{
}
void CBaseToolSystem::ServerLevelShutdownPreEntity()
{
}
void CBaseToolSystem::ServerLevelShutdownPostEntity()
{
}
//-----------------------------------------------------------------------------
// Think methods
//-----------------------------------------------------------------------------
void CBaseToolSystem::ServerFrameUpdatePreEntityThink()
{
}
void CBaseToolSystem::Think( bool finalTick )
{
// run vgui animations
vgui::GetAnimationController()->UpdateAnimations( enginetools->Time() );
}
void CBaseToolSystem::PostToolMessage( HTOOLHANDLE hEntity, KeyValues *message )
{
return;
}
void CBaseToolSystem::ServerFrameUpdatePostEntityThink()
{
}
void CBaseToolSystem::ServerPreClientUpdate()
{
}
void CBaseToolSystem::ServerPreSetupVisibility()
{
}
const char* CBaseToolSystem::GetEntityData( const char *pActualEntityData )
{
return pActualEntityData;
}
void* CBaseToolSystem::QueryInterface( const char *pInterfaceName )
{
return NULL;
}
//-----------------------------------------------------------------------------
// Level init, shutdown for client
//-----------------------------------------------------------------------------
void CBaseToolSystem::ClientLevelInitPreEntity()
{
}
void CBaseToolSystem::ClientLevelInitPostEntity()
{
}
void CBaseToolSystem::ClientLevelShutdownPreEntity()
{
}
void CBaseToolSystem::ClientLevelShutdownPostEntity()
{
}
void CBaseToolSystem::ClientPreRender()
{
}
void CBaseToolSystem::ClientPostRender()
{
}
//-----------------------------------------------------------------------------
// Tool activation/deactivation
//-----------------------------------------------------------------------------
void CBaseToolSystem::OnToolActivate()
{
m_bIsActive = true;
UpdateUIVisibility( );
// FIXME: Note that this is necessary because IsGameInputEnabled depends on m_bIsActive at the moment
OnModeChanged();
input()->SetModalSubTree( VGui_GetToolRootPanel(), GetVPanel(), IsGameInputEnabled() );
input()->SetModalSubTreeReceiveMessages( !IsGameInputEnabled() );
m_pToolUI->UpdateMenuBarTitle();
}
void CBaseToolSystem::OnToolDeactivate()
{
m_bIsActive = false;
UpdateUIVisibility( );
// FIXME: Note that this is necessary because IsGameInputEnabled depends on m_bIsActive at the moment
OnModeChanged();
input()->ReleaseModalSubTree();
}
//-----------------------------------------------------------------------------
// Let tool override key events (ie ESC and ~)
//-----------------------------------------------------------------------------
bool CBaseToolSystem::TrapKey( ButtonCode_t key, bool down )
{
// Don't hook keyboard if not topmost
if ( !m_bIsActive )
return false; // didn't trap, continue processing
// This is a bit of a hack to work around the mouse capture bugs we seem to keep getting...
if ( !IsGameInputEnabled() && key == KEY_ESCAPE )
{
vgui::input()->SetMouseCapture( NULL );
}
// If in fullscreen toolMode, don't let ECSAPE bring up the game menu
if ( !m_bGameInputEnabled && m_bFullscreenMode && ( key == KEY_ESCAPE ) )
return true; // trapping this key, stop processing
if ( down )
{
if ( key == TOGGLE_WINDOWED_KEY_CODE )
{
SetMode( m_bGameInputEnabled, !m_bFullscreenMode );
return true; // trapping this key, stop processing
}
if ( key == TOGGLE_INPUT_KEY_CODE )
{
if ( input()->IsKeyDown( KEY_LCONTROL ) || input()->IsKeyDown( KEY_RCONTROL ) )
{
ToggleForceToolCamera();
}
else
{
SetMode( !m_bGameInputEnabled, m_bFullscreenMode );
}
return true; // trapping this key, stop processing
}
// If in IFM mode, let ~ switch to gameMode and toggle console
if ( !IsGameInputEnabled() && ( key == '~' || key == '`' ) )
{
SetMode( true, m_bFullscreenMode );
return false; // didn't trap, continue processing
}
}
return false; // didn't trap, continue processing
}
//-----------------------------------------------------------------------------
// Shows, hides the tool ui (menu, client area, status bar)
//-----------------------------------------------------------------------------
void CBaseToolSystem::SetToolUIVisible( bool bVisible )
{
if ( bVisible != m_pToolUI->IsVisible() )
{
m_pToolUI->SetVisible( bVisible );
m_pToolUI->InvalidateLayout();
}
}
//-----------------------------------------------------------------------------
// Computes whether vgui is visible or not
//-----------------------------------------------------------------------------
void CBaseToolSystem::UpdateUIVisibility()
{
bool bIsVisible = m_bIsActive && ( !IsGameInputEnabled() || !m_bFullscreenMode );
ShowUI( bIsVisible );
}
//-----------------------------------------------------------------------------
// Changes game input + fullscreen modes
//-----------------------------------------------------------------------------
void CBaseToolSystem::EnableFullscreenToolMode( bool bEnable )
{
m_bFullscreenToolModeEnabled = bEnable;
}
//-----------------------------------------------------------------------------
// Changed whether camera is forced to be tool camera
//-----------------------------------------------------------------------------
void CBaseToolSystem::ToggleForceToolCamera()
{
}
//-----------------------------------------------------------------------------
// Changes game input + fullscreen modes
//-----------------------------------------------------------------------------
void CBaseToolSystem::SetMode( bool bGameInputEnabled, bool bFullscreen )
{
Assert( m_bIsActive );
if ( !m_bFullscreenToolModeEnabled )
{
if ( !bGameInputEnabled )
{
bFullscreen = false;
}
}
if ( ( m_bFullscreenMode == bFullscreen ) && ( m_bGameInputEnabled == bGameInputEnabled ) )
return;
bool bOldGameInputEnabled = m_bGameInputEnabled;
m_bFullscreenMode = bFullscreen;
m_bGameInputEnabled = bGameInputEnabled;
UpdateUIVisibility();
if ( bOldGameInputEnabled != m_bGameInputEnabled )
{
Warning( "Input is now being sent to the %s\n", m_bGameInputEnabled ? "Game" : "Tools" );
// If switching from tool to game mode, release the mouse capture so that the
// tool knows that it is going to miss mouse events that are handed to the game.
if ( bGameInputEnabled == true )
{
input()->SetMouseCapture( NULL );
}
// The subtree starts at the tool system root panel. If game input is enabled then
// the subtree should not receive or process input messages, otherwise it should
Assert( input()->GetModalSubTree() );
if ( input()->GetModalSubTree() )
{
input()->SetModalSubTreeReceiveMessages( !m_bGameInputEnabled );
}
enginetools->OnModeChanged( m_bGameInputEnabled );
}
if ( m_pToolUI )
{
m_pToolUI->UpdateMenuBarTitle();
}
OnModeChanged( );
}
//-----------------------------------------------------------------------------
// Keybinding
//-----------------------------------------------------------------------------
void CBaseToolSystem::LoadKeyBindings()
{
ReloadKeyBindings( m_KeyBindingsHandle );
}
void CBaseToolSystem::ShowKeyBindingsEditor( Panel *panel, KeyBindingContextHandle_t handle )
{
if ( !m_hKeyBindingsEditor.Get() )
{
// Show the editor
m_hKeyBindingsEditor = new CKeyBoardEditorDialog( GetClientArea(), panel, handle );
m_hKeyBindingsEditor->DoModal();
}
}
void CBaseToolSystem::ShowKeyBindingsHelp( Panel *panel, KeyBindingContextHandle_t handle, vgui::KeyCode boundKey, int modifiers )
{
if ( m_hKeyBindingsHelp.Get() )
{
m_hKeyBindingsHelp->HelpKeyPressed();
return;
}
m_hKeyBindingsHelp = new CKeyBindingHelpDialog( GetClientArea(), panel, handle, boundKey, modifiers );
}
vgui::KeyBindingContextHandle_t CBaseToolSystem::GetKeyBindingsHandle()
{
return m_KeyBindingsHandle;
}
void CBaseToolSystem::OnEditKeyBindings()
{
Panel *tool = GetMostRecentlyFocusedTool();
if ( tool )
{
ShowKeyBindingsEditor( tool, tool->GetKeyBindingsContext() );
}
}
void CBaseToolSystem::OnKeyBindingHelp()
{
Panel *tool = GetMostRecentlyFocusedTool();
if ( tool )
{
CUtlVector< BoundKey_t * > list;
LookupBoundKeys( "keybindinghelp", list );
if ( list.Count() > 0 )
{
ShowKeyBindingsHelp( tool, tool->GetKeyBindingsContext(), (KeyCode)list[ 0 ]->keycode, list[ 0 ]->modifiers );
}
}
}
//-----------------------------------------------------------------------------
// Registers tool window
//-----------------------------------------------------------------------------
void CBaseToolSystem::RegisterToolWindow( vgui::PHandle hPanel )
{
int i = m_Tools.AddToTail( hPanel );
m_Tools[i]->SetKeyBindingsContext( m_KeyBindingsHandle );
}
void CBaseToolSystem::UnregisterAllToolWindows()
{
m_Tools.RemoveAll();
m_MostRecentlyFocused = NULL;
}
//-----------------------------------------------------------------------------
// Destroys all tool windows containers
//-----------------------------------------------------------------------------
void CBaseToolSystem::DestroyToolContainers()
{
int c = ToolWindow::GetToolWindowCount();
for ( int i = c - 1; i >= 0 ; --i )
{
ToolWindow *kill = ToolWindow::GetToolWindow( i );
delete kill;
}
}
Panel *CBaseToolSystem::GetMostRecentlyFocusedTool()
{
VPANEL focus = input()->GetFocus();
int c = m_Tools.Count();
for ( int i = 0; i < c; ++i )
{
Panel *p = m_Tools[ i ].Get();
if ( !p )
continue;
// Not a visible tool
if ( !p->GetParent() )
continue;
bool hasFocus = p->HasFocus();
bool focusOnChild = focus && ipanel()->HasParent(focus, p->GetVPanel());
if ( !hasFocus && !focusOnChild )
{
continue;
}
return p;
}
return m_MostRecentlyFocused.Get();
}
void CBaseToolSystem::PostMessageToActiveTool( KeyValues *pKeyValues, float flDelay )
{
Panel *pMostRecent = GetMostRecentlyFocusedTool();
if ( pMostRecent )
{
Panel::PostMessage( pMostRecent->GetVPanel(), pKeyValues, flDelay );
}
}
void CBaseToolSystem::PostMessageToActiveTool( const char *msg, float flDelay )
{
Panel *pMostRecent = GetMostRecentlyFocusedTool();
if ( pMostRecent )
{
Panel::PostMessage( pMostRecent->GetVPanel(), new KeyValues( msg ), flDelay );
}
}
void CBaseToolSystem::PostMessageToAllTools( KeyValues *message )
{
int nCount = enginetools->GetToolCount();
for ( int i = 0; i < nCount; ++i )
{
IToolSystem *pToolSystem = const_cast<IToolSystem*>( enginetools->GetToolSystem( i ) );
pToolSystem->PostToolMessage( HTOOLHANDLE_INVALID, message );
}
}
void CBaseToolSystem::OnThink()
{
BaseClass::OnThink();
VPANEL focus = input()->GetFocus();
int c = m_Tools.Count();
for ( int i = 0; i < c; ++i )
{
Panel *p = m_Tools[ i ].Get();
if ( !p )
continue;
// Not a visible tool
Panel *pPage = p->GetParent();
if ( !pPage )
continue;
bool hasFocus = p->HasFocus();
bool bFocusOnTab = false;
bool focusOnChild = false;
if ( !hasFocus )
{
PropertySheet *pSheet = dynamic_cast< PropertySheet * >( pPage );
if ( pSheet )
{
Panel *pActiveTab = pSheet->GetActiveTab();
if ( pActiveTab )
{
bFocusOnTab = ( ( focus == pActiveTab->GetVPanel() ) || // Tab itself has focus
ipanel()->HasParent( focus, pActiveTab->GetVPanel() ) ); // Tab is parent of panel that has focus (in case we add subpanels to tabs)
}
}
focusOnChild = focus && ipanel()->HasParent(focus, p->GetVPanel());
}
if ( !hasFocus && !focusOnChild && !bFocusOnTab )
continue;
if ( m_MostRecentlyFocused != p )
{
m_MostRecentlyFocused = p;
}
break;
}
}
//-----------------------------------------------------------------------------
// Let tool override viewport for engine
//-----------------------------------------------------------------------------
void CBaseToolSystem::AdjustEngineViewport( int& x, int& y, int& width, int& height )
{
if ( !m_hMiniViewport.Get() )
return;
bool enabled;
int vpx, vpy, vpw, vph;
m_hMiniViewport->GetViewport( enabled, vpx, vpy, vpw, vph );
if ( !enabled )
return;
x = vpx;
y = vpy;
width = vpw;
height = vph;
}
//-----------------------------------------------------------------------------
// Let tool override view/camera
//-----------------------------------------------------------------------------
bool CBaseToolSystem::SetupEngineView( Vector &origin, QAngle &angles, float &fov )
{
return false;
}
//-----------------------------------------------------------------------------
// Let tool override microphone
//-----------------------------------------------------------------------------
bool CBaseToolSystem::SetupAudioState( AudioState_t &audioState )
{
return false;
}
//-----------------------------------------------------------------------------
// Should the game be allowed to render the view?
//-----------------------------------------------------------------------------
bool CBaseToolSystem::ShouldGameRenderView()
{
// Render through mini viewport unless in fullscreen mode
if ( !IsVisible() )
{
return true;
}
if ( !m_hMiniViewport.Get() )
return true;
if ( !m_hMiniViewport->IsVisible() )
{
return true;
}
// Route through mini viewport
return false;
}
bool CBaseToolSystem::ShouldGamePlaySounds()
{
return true;
}
bool CBaseToolSystem::IsThirdPersonCamera()
{
return false;
}
bool CBaseToolSystem::IsToolRecording()
{
return false;
}
IMaterialProxy *CBaseToolSystem::LookupProxy( const char *proxyName )
{
return NULL;
}
bool CBaseToolSystem::GetSoundSpatialization( int iUserData, int guid, SpatializationInfo_t& info )
{
// Always hearable (no changes)
return true;
}
void CBaseToolSystem::HostRunFrameBegin()
{
}
void CBaseToolSystem::HostRunFrameEnd()
{
}
void CBaseToolSystem::RenderFrameBegin()
{
// If we can't see the engine window, do nothing
if ( !IsVisible() || !IsActiveTool() )
return;
if ( !m_hMiniViewport.Get() || !m_hMiniViewport->IsVisible() )
return;
m_hMiniViewport->RenderFrameBegin();
}
void CBaseToolSystem::RenderFrameEnd()
{
}
void CBaseToolSystem::VGui_PreRender( int paintMode )
{
}
void CBaseToolSystem::VGui_PostRender( int paintMode )
{
}
void CBaseToolSystem::VGui_PreSimulate()
{
if ( !m_bIsActive )
return;
// only show the gameUI when in gameMode
vgui::VPANEL gameui = enginevgui->GetPanel( PANEL_GAMEUIDLL );
#if defined( TOOLFRAMEWORK_VGUI_REFACTOR )
vgui::VPANEL gameuiBackground = enginevgui->GetPanel( PANEL_GAMEUIBACKGROUND );
#endif
if ( gameui != 0 )
{
bool wantsToBeSeen = IsGameInputEnabled() && (enginetools->IsGamePaused() || !enginetools->IsInGame() || enginetools->IsConsoleVisible());
vgui::ipanel()->SetVisible(gameui, wantsToBeSeen);
#if defined( TOOLFRAMEWORK_VGUI_REFACTOR )
vgui::ipanel()->SetVisible(gameuiBackground, wantsToBeSeen);
#endif
}
// if there's no map loaded and we're in fullscreen toolMode, switch to gameMode
// otherwise there's nothing to see or do...
if ( !IsGameInputEnabled() && !IsVisible() && !enginetools->IsInGame() )
{
SetMode( true, m_bFullscreenMode );
}
}
void CBaseToolSystem::VGui_PostSimulate()
{
}
const char *CBaseToolSystem::MapName() const
{
return enginetools->GetCurrentMap();
}
//-----------------------------------------------------------------------------
// Shows or hides the UI
//-----------------------------------------------------------------------------
bool CBaseToolSystem::ShowUI( bool bVisible )
{
bool bPrevVisible = IsVisible();
if ( bPrevVisible == bVisible )
return bPrevVisible;
SetMouseInputEnabled( bVisible );
SetVisible( bVisible );
// Hide loading image if using bx movie UI
// A bit of a hack because it more or less tunnels through to the client .dll, but the moviemaker assumes
// single player anyway...
if ( bVisible )
{
ConVar *pCv = ( ConVar * )cvar->FindVar( "cl_showpausedimage" );
if ( pCv )
{
pCv->SetValue( 0 );
}
}
return bPrevVisible;
}
//-----------------------------------------------------------------------------
// Gets the action target to sent to panels so that the tool system's OnCommand is called
//-----------------------------------------------------------------------------
vgui::Panel *CBaseToolSystem::GetActionTarget()
{
return this;
}
//-----------------------------------------------------------------------------
// Derived classes implement this to create a custom menubar
//-----------------------------------------------------------------------------
vgui::MenuBar *CBaseToolSystem::CreateMenuBar(CBaseToolSystem *pParent )
{
return new vgui::MenuBar( pParent, "ToolMenuBar" );
}
//-----------------------------------------------------------------------------
// Purpose: Derived classes implement this to create a custom status bar, or return NULL for no status bar
//-----------------------------------------------------------------------------
vgui::Panel *CBaseToolSystem::CreateStatusBar( vgui::Panel *pParent )
{
return new CBaseStatusBar( this, "Status Bar" );
}
//-----------------------------------------------------------------------------
// Gets at the action menu
//-----------------------------------------------------------------------------
vgui::Menu *CBaseToolSystem::GetActionMenu()
{
return m_hActionMenu;
}
//-----------------------------------------------------------------------------
// Returns the client area
//-----------------------------------------------------------------------------
vgui::Panel* CBaseToolSystem::GetClientArea()
{
return m_pToolUI->GetClientArea();
}
//-----------------------------------------------------------------------------
// Returns the menu bar
//-----------------------------------------------------------------------------
vgui::MenuBar* CBaseToolSystem::GetMenuBar()
{
return m_pToolUI->GetMenuBar();
}
//-----------------------------------------------------------------------------
// Returns the status bar
//-----------------------------------------------------------------------------
vgui::Panel* CBaseToolSystem::GetStatusBar()
{
return m_pToolUI->GetStatusBar();
}
//-----------------------------------------------------------------------------
// Pops up the action menu
//-----------------------------------------------------------------------------
void CBaseToolSystem::OnMousePressed( vgui::MouseCode code )
{
if ( code == MOUSE_RIGHT )
{
InitActionMenu();
}
else
{
BaseClass::OnMousePressed( code );
}
}
//-----------------------------------------------------------------------------
// Creates the action menu
//-----------------------------------------------------------------------------
void CBaseToolSystem::InitActionMenu()
{
ShutdownActionMenu();
// Let the tool system create the action menu
m_hActionMenu = CreateActionMenu( this );
if ( m_hActionMenu.Get() )
{
m_hActionMenu->SetVisible(true);
PositionActionMenu();
m_hActionMenu->RequestFocus();
}
}
//-----------------------------------------------------------------------------
// Destroy action menu
//-----------------------------------------------------------------------------
void CBaseToolSystem::ShutdownActionMenu()
{
if ( m_hActionMenu.Get() )
{
m_hActionMenu->MarkForDeletion();
m_hActionMenu = NULL;
}
}
void CBaseToolSystem::UpdateMenu( vgui::Menu *menu )
{
// Nothing
}
//-----------------------------------------------------------------------------
// Positions the action menu when it's time to pop it up
//-----------------------------------------------------------------------------
void CBaseToolSystem::PositionActionMenu()
{
// get cursor position, this is local to this text edit window
int cursorX, cursorY;
input()->GetCursorPos(cursorX, cursorY);
// relayout the menu immediately so that we know it's size
m_hActionMenu->InvalidateLayout(true);
// Get the menu size
int menuWide, menuTall;
m_hActionMenu->GetSize( menuWide, menuTall );
// work out where the cursor is and therefore the best place to put the menu
int wide, tall;
GetSize( wide, tall );
if (wide - menuWide > cursorX)
{
// menu hanging right
if (tall - menuTall > cursorY)
{
// menu hanging down
m_hActionMenu->SetPos(cursorX, cursorY);
}
else
{
// menu hanging up
m_hActionMenu->SetPos(cursorX, cursorY - menuTall);
}
}
else
{
// menu hanging left
if (tall - menuTall > cursorY)
{
// menu hanging down
m_hActionMenu->SetPos(cursorX - menuWide, cursorY);
}
else
{
// menu hanging up
m_hActionMenu->SetPos(cursorX - menuWide, cursorY - menuTall);
}
}
}
//-----------------------------------------------------------------------------
// Handles the clear recent files message
//-----------------------------------------------------------------------------
void CBaseToolSystem::OnClearRecent()
{
m_RecentFiles.Clear();
m_RecentFiles.SaveToRegistry( GetRegistryName() );
}
//-----------------------------------------------------------------------------
// Called by the file open state machine
//-----------------------------------------------------------------------------
void CBaseToolSystem::OnFileStateMachineFinished( KeyValues *pKeyValues )
{
KeyValues *pContext = pKeyValues->GetFirstTrueSubKey();
bool bWroteFile = pKeyValues->GetInt( "wroteFile", 0 ) != 0;
vgui::FileOpenStateMachine::CompletionState_t state = (vgui::FileOpenStateMachine::CompletionState_t)pKeyValues->GetInt( "completionState", vgui::FileOpenStateMachine::IN_PROGRESS );
const char *pFileType = pKeyValues->GetString( "fileType" );
OnFileOperationCompleted( pFileType, bWroteFile, state, pContext );
}
//-----------------------------------------------------------------------------
// Show the File browser dialog
//-----------------------------------------------------------------------------
void CBaseToolSystem::OpenFile( const char *pOpenFileType, const char *pSaveFileName, const char *pSaveFileType, int nFlags, KeyValues *pContextKeyValues )
{
m_pFileOpenStateMachine->OpenFile( pOpenFileType, pContextKeyValues, pSaveFileName, pSaveFileType, nFlags );
}
void CBaseToolSystem::OpenFile( const char *pOpenFileName, const char *pOpenFileType, const char *pSaveFileName, const char *pSaveFileType, int nFlags, KeyValues *pContextKeyValues )
{
m_pFileOpenStateMachine->OpenFile( pOpenFileName, pOpenFileType, pContextKeyValues, pSaveFileName, pSaveFileType, nFlags );
}
//-----------------------------------------------------------------------------
// Used to save a specified file, and deal with all the lovely dialogs
//-----------------------------------------------------------------------------
void CBaseToolSystem::SaveFile( const char *pFileName, const char *pFileType, int nFlags, KeyValues *pContextKeyValues )
{
m_pFileOpenStateMachine->SaveFile( pContextKeyValues, pFileName, pFileType, nFlags );
}
//-----------------------------------------------------------------------------
// Paints the background
//-----------------------------------------------------------------------------
void CBaseToolSystem::PaintBackground()
{
int w, h;
GetSize( w, h );
int x, y;
GetPos( x, y );
LocalToScreen( x, y );
CMatRenderContextPtr pRenderContext( materials );
if ( m_pBackground )
{
int texWide = m_pBackground->GetMappingWidth();
int texTall = m_pBackground->GetMappingHeight();
float maxu = (float)w / (float)texWide;
float maxv = (float)h / (float)texTall;
RenderQuad( m_pBackground, x, y, w, h, surface()->GetZPos(), 0.0f, 0.0f, maxu, maxv, Color( 255, 255, 255, 255 ) );
}
bool hasDoc = HasDocument();
if ( m_pLogo )
{
int texWide = m_pLogo->GetMappingWidth();
float logoAspectRatio = 0.442;
if ( hasDoc )
{
int logoW = texWide / 2;
int logoH = logoW * logoAspectRatio;
x = w - logoW - 15;
y = h - logoH - 30;
w = logoW;
h = logoH;
}
else
{
int logoW = texWide;
int logoH = logoW * logoAspectRatio;
x = ( w - logoW ) / 2;
y = ( h - logoH ) / 2;
w = logoW;
h = logoH;
}
int alpha = hasDoc ? 0 : 255;
RenderQuad( m_pLogo, x, y, w, h, surface()->GetZPos(), 0.0f, 0.0f, 1.0f, 1.0f, Color( 255, 255, 255, alpha ) );
}
}
const char *CBaseToolSystem::GetBackgroundTextureName()
{
return "vgui/tools/ifm/ifm_background";
}
bool CBaseToolSystem::HasDocument()
{
return false;
}
CMiniViewport *CBaseToolSystem::CreateMiniViewport( vgui::Panel *parent )
{
int w, h;
surface()->GetScreenSize( w, h );
CMiniViewport *vp = new CMiniViewport( parent, "MiniViewport" );
Assert( vp );
vp->SetVisible( true );
int menuBarHeight = 28;
int titleBarHeight = 22;
int offset = 4;
vp->SetBounds( ( 2 * w / 3 ) - offset, menuBarHeight + offset, w / 3, h / 3 + titleBarHeight);
return vp;
}
void CBaseToolSystem::ComputeMenuBarTitle( char *buf, size_t buflen )
{
Q_snprintf( buf, buflen, ": %s [ %s - Switch Mode ] [ %s - Full Screen ]", IsGameInputEnabled() ? "Game Mode" : "Tool Mode", TOGGLE_INPUT_KEY_NAME, TOGGLE_WINDOWED_KEY_NAME );
}
void CBaseToolSystem::OnUnhandledMouseClick( int code )
{
if ( (MouseCode)code == MOUSE_LEFT )
{
// If tool ui is visible and we're running game in a window
// and they click on the ifm it'll be unhandled, but in this case
// we'll switch back to the IFM mode
if ( !IsFullscreen() && IsGameInputEnabled() )
{
SetMode( false, m_bFullscreenMode );
}
}
}
| 412 | 0.972155 | 1 | 0.972155 | game-dev | MEDIA | 0.630892 | game-dev | 0.693883 | 1 | 0.693883 |
revbayes/revbayes | 1,562 | src/revlanguage/functions/math/Func_betaBrokenStick.h | #ifndef Func_betaBrokenStick_H
#define Func_betaBrokenStick_H
#include "ModelVector.h"
#include "RlSimplex.h"
#include "RlTypedFunction.h"
#include <map>
#include <string>
namespace RevLanguage {
class Func_betaBrokenStick : public TypedFunction<Simplex> {
public:
Func_betaBrokenStick();
// Basic utility functions
Func_betaBrokenStick* clone(void) const; //!< Clone the object
static const std::string& getClassName(void); //!< Get class name
static const TypeSpec& getClassTypeSpec(void); //!< Get class type spec
std::string getFunctionName(void) const; //!< Get the primary name of the function in Rev
const TypeSpec& getTypeSpec(void) const; //!< Get language type of the object
// Regular functions
RevBayesCore::TypedFunction<RevBayesCore::Simplex>* createFunction(void) const; //!< Create internal function object
const ArgumentRules& getArgumentRules(void) const; //!< Get argument rules
};
}
#endif
| 412 | 0.712104 | 1 | 0.712104 | game-dev | MEDIA | 0.566923 | game-dev | 0.573212 | 1 | 0.573212 |
hannoL/AREsoft | 7,470 | tools/ded/soot/soot-2.3.0/src/soot/dava/toolkits/base/finders/ExceptionNode.java | /* Soot - a J*va Optimization Framework
* Copyright (C) 2003 Jerome Miecznikowski
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
package soot.dava.toolkits.base.finders;
import soot.*;
import java.util.*;
import soot.util.*;
import soot.dava.internal.asg.*;
public class ExceptionNode
{
private final IterableSet body;
private IterableSet tryBody, catchBody;
private boolean dirty;
private LinkedList exitList, catchList;
private SootClass exception;
private HashMap<IterableSet,SootClass> catch2except;
private AugmentedStmt handlerAugmentedStmt;
public ExceptionNode( IterableSet tryBody, SootClass exception, AugmentedStmt handlerAugmentedStmt)
{
this.tryBody = tryBody;
this.catchBody = null;
this.exception = exception;
this.handlerAugmentedStmt = handlerAugmentedStmt;
body = new IterableSet();
body.addAll( tryBody);
dirty = true;
exitList = null;
catchList = null;
catch2except = null;
}
public boolean add_TryStmts( Collection c)
{
Iterator it = c.iterator();
while (it.hasNext())
if (add_TryStmt( (AugmentedStmt) it.next()) == false)
return false;
return true;
}
public boolean add_TryStmt( AugmentedStmt as)
{
if ((body.contains( as)) || (tryBody.contains( as)))
return false;
body.add( as);
tryBody.add( as);
return true;
}
public void refresh_CatchBody( ExceptionFinder ef)
{
if (catchBody != null)
body.removeAll( catchBody);
catchBody = ef.get_CatchBody( handlerAugmentedStmt);
body.addAll( catchBody);
}
public IterableSet get_Body()
{
return body;
}
public IterableSet get_TryBody()
{
return tryBody;
}
public IterableSet get_CatchBody()
{
return catchBody;
}
public boolean remove( AugmentedStmt as)
{
if (body.contains( as) == false)
return false;
if (tryBody.contains( as))
tryBody.remove( as);
else if ((catchBody != null) && (catchBody.contains( as))) {
catchBody.remove( as);
dirty = true;
}
else
return false;
body.remove( as);
return true;
}
public List get_CatchExits()
{
if (catchBody == null)
return null;
if (dirty) {
exitList = new LinkedList();
dirty = false;
Iterator it = catchBody.iterator();
while (it.hasNext()) {
AugmentedStmt as = (AugmentedStmt) it.next();
Iterator sit = as.bsuccs.iterator();
while (sit.hasNext())
if (catchBody.contains( sit.next()) == false) {
exitList.add( as);
break;
}
}
}
return exitList;
}
public void splitOff_ExceptionNode( IterableSet newTryBody, AugmentedStmtGraph asg, IterableSet enlist)
{
IterableSet oldTryBody = new IterableSet();
oldTryBody.addAll( tryBody);
IterableSet oldBody = new IterableSet();
oldBody.addAll( body);
Iterator it = newTryBody.iterator();
while (it.hasNext()) {
AugmentedStmt as = (AugmentedStmt) it.next();
if (remove( as) == false) {
StringBuffer b = new StringBuffer();
it = newTryBody.iterator();
while (it.hasNext())
b.append( "\n" + ((AugmentedStmt) it.next()).toString());
b.append( "\n-");
it = oldTryBody.iterator();
while (it.hasNext())
b.append( "\n" + ((AugmentedStmt) it.next()).toString());
b.append( "\n-");
it = oldBody.iterator();
while (it.hasNext())
b.append( "\n" + ((AugmentedStmt) it.next()).toString());
b.append( "\n-");
throw new RuntimeException( "Tried to split off a new try body that isn't in the old one.\n"+ as +"\n - " + b.toString());
}
}
asg.clone_Body( catchBody);
AugmentedStmt
oldCatchTarget = handlerAugmentedStmt,
newCatchTarget = asg.get_CloneOf( handlerAugmentedStmt);
Iterator tbit = newTryBody.iterator();
while (tbit.hasNext()) {
AugmentedStmt as = (AugmentedStmt) tbit.next();
as.remove_CSucc( oldCatchTarget);
oldCatchTarget.remove_CPred( as);
}
tbit = tryBody.iterator();
while (tbit.hasNext()) {
AugmentedStmt as = (AugmentedStmt) tbit.next();
as.remove_CSucc( newCatchTarget);
newCatchTarget.remove_CPred( as);
}
Iterator enlit = enlist.snapshotIterator();
while (enlit.hasNext()) {
ExceptionNode en = (ExceptionNode) enlit.next();
if (this == en)
continue;
if (catchBody.isSupersetOf( en.get_Body())) {
IterableSet clonedTryBody = new IterableSet();
Iterator trit = en.get_TryBody().iterator();
while (trit.hasNext())
clonedTryBody.add( asg.get_CloneOf( (AugmentedStmt) trit.next()));
enlist.addLast( new ExceptionNode( clonedTryBody, en.exception, asg.get_CloneOf( en.handlerAugmentedStmt)));
}
}
enlist.addLast( new ExceptionNode( newTryBody, exception, asg.get_CloneOf( handlerAugmentedStmt)));
enlit = enlist.iterator();
while (enlit.hasNext())
((ExceptionNode) enlit.next()).refresh_CatchBody( ExceptionFinder.v());
asg.find_Dominators();
}
public void add_CatchBody( ExceptionNode other)
{
if (other.get_CatchList() == null) {
add_CatchBody( other.get_CatchBody(), other.get_Exception());
return;
}
Iterator it = other.get_CatchList().iterator();
while (it.hasNext()) {
IterableSet c = (IterableSet) it.next();
add_CatchBody( c, other.get_Exception( c));
}
}
public void add_CatchBody( IterableSet newCatchBody, SootClass except)
{
if (catchList == null) {
catchList = new LinkedList();
catchList.addLast( catchBody);
catch2except = new HashMap<IterableSet,SootClass>();
catch2except.put( catchBody, exception);
}
body.addAll( newCatchBody);
catchList.addLast( newCatchBody);
catch2except.put( newCatchBody, except);
}
public List get_CatchList()
{
List l = catchList;
if (l == null) {
l = new LinkedList();
l.add( catchBody);
}
return l;
}
public Map get_ExceptionMap()
{
Map m = catch2except;
if (m == null) {
m = new HashMap();
m.put( catchBody, exception);
}
return m;
}
public SootClass get_Exception()
{
return exception;
}
public SootClass get_Exception( IterableSet catchBody)
{
if (catch2except == null)
return exception;
return catch2except.get( catchBody);
}
public void dump()
{
G.v().out.println("try {");
Iterator tit = get_TryBody().iterator();
while (tit.hasNext())
G.v().out.println( "\t" + tit.next());
G.v().out.println( "}");
Iterator cit = get_CatchList().iterator();
while (cit.hasNext()) {
IterableSet catchBody = (IterableSet) cit.next();
G.v().out.println( "catch " + get_ExceptionMap().get( catchBody) + " {");
Iterator cbit = catchBody.iterator();
while (cbit.hasNext())
G.v().out.println( "\t" + cbit.next());
G.v().out.println("}");
}
}
}
| 412 | 0.938283 | 1 | 0.938283 | game-dev | MEDIA | 0.171113 | game-dev | 0.96779 | 1 | 0.96779 |
josh-m/RW-Decompile | 3,384 | RimWorld/ResourceCounter.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Verse;
namespace RimWorld
{
public sealed class ResourceCounter
{
private Map map;
private Dictionary<ThingDef, int> countedAmounts = new Dictionary<ThingDef, int>();
private static List<ThingDef> resources = new List<ThingDef>();
public int Silver
{
get
{
return this.GetCount(ThingDefOf.Silver);
}
}
public float TotalHumanEdibleNutrition
{
get
{
float num = 0f;
foreach (KeyValuePair<ThingDef, int> current in this.countedAmounts)
{
if (current.Key.IsNutritionGivingIngestible && current.Key.ingestible.HumanEdible)
{
num += current.Key.GetStatValueAbstract(StatDefOf.Nutrition, null) * (float)current.Value;
}
}
return num;
}
}
public Dictionary<ThingDef, int> AllCountedAmounts
{
get
{
return this.countedAmounts;
}
}
public ResourceCounter(Map map)
{
this.map = map;
this.ResetResourceCounts();
}
public static void ResetDefs()
{
ResourceCounter.resources.Clear();
ResourceCounter.resources.AddRange(from def in DefDatabase<ThingDef>.AllDefs
where def.CountAsResource
orderby def.resourceReadoutPriority descending
select def);
}
public void ResetResourceCounts()
{
this.countedAmounts.Clear();
for (int i = 0; i < ResourceCounter.resources.Count; i++)
{
this.countedAmounts.Add(ResourceCounter.resources[i], 0);
}
}
public int GetCount(ThingDef rDef)
{
if (rDef.resourceReadoutPriority == ResourceCountPriority.Uncounted)
{
return 0;
}
int result;
if (this.countedAmounts.TryGetValue(rDef, out result))
{
return result;
}
Log.Error("Looked for nonexistent key " + rDef + " in counted resources.", false);
this.countedAmounts.Add(rDef, 0);
return 0;
}
public int GetCountIn(ThingRequestGroup group)
{
int num = 0;
foreach (KeyValuePair<ThingDef, int> current in this.countedAmounts)
{
if (group.Includes(current.Key))
{
num += current.Value;
}
}
return num;
}
public int GetCountIn(ThingCategoryDef cat)
{
int num = 0;
for (int i = 0; i < cat.childThingDefs.Count; i++)
{
num += this.GetCount(cat.childThingDefs[i]);
}
for (int j = 0; j < cat.childCategories.Count; j++)
{
if (!cat.childCategories[j].resourceReadoutRoot)
{
num += this.GetCountIn(cat.childCategories[j]);
}
}
return num;
}
public void ResourceCounterTick()
{
if (Find.TickManager.TicksGame % 204 == 0)
{
this.UpdateResourceCounts();
}
}
public void UpdateResourceCounts()
{
this.ResetResourceCounts();
List<SlotGroup> allGroupsListForReading = this.map.haulDestinationManager.AllGroupsListForReading;
for (int i = 0; i < allGroupsListForReading.Count; i++)
{
SlotGroup slotGroup = allGroupsListForReading[i];
foreach (Thing current in slotGroup.HeldThings)
{
Thing innerIfMinified = current.GetInnerIfMinified();
if (innerIfMinified.def.CountAsResource && this.ShouldCount(innerIfMinified))
{
Dictionary<ThingDef, int> dictionary;
ThingDef def;
(dictionary = this.countedAmounts)[def = innerIfMinified.def] = dictionary[def] + innerIfMinified.stackCount;
}
}
}
}
private bool ShouldCount(Thing t)
{
return !t.IsNotFresh();
}
}
}
| 412 | 0.899231 | 1 | 0.899231 | game-dev | MEDIA | 0.680321 | game-dev | 0.980899 | 1 | 0.980899 |
LandSandBoat/server | 3,807 | scripts/mixins/families/eruca.lua | --[[
https://ffxiclopedia.fandom.com/wiki/Category:Crawlers
Eruca mobs can optionally be modified by calling xi.mix.eruca.config(mob, params) from within onMobSpawn.
params is a table that can contain the following keys:
sleepHour : changes hour at which eruca crawlers naturally fall asleep (default: 18)
wakeHour : changes hour at which eruca crawlers naturally wake (default: 6)
Example:
xi.mix.eruca.config(mob, {
sleepHour = 20,
wakeHour = 4,
})
--]]
require('scripts/globals/mixins')
require('scripts/globals/magic')
-----------------------------------
xi = xi or {}
xi.mix = xi.mix or {}
xi.mix.eruca = xi.mix.eruca or {}
g_mixins = g_mixins or {}
g_mixins.families = g_mixins.families or {}
local function bedTime(mob)
mob:setAnimationSub(mob:getAnimationSub() + 1)
mob:setMobMod(xi.mobMod.NO_MOVE, 1)
mob:setMobMod(xi.mobMod.NO_AGGRO, 1)
mob:setMobMod(xi.mobMod.NO_LINK, 1)
mob:setMagicCastingEnabled(false)
mob:setLocalVar('ResleepTime', 0)
end
local function wakeUp(mob)
mob:setAnimationSub(mob:getAnimationSub() - 1)
mob:setMobMod(xi.mobMod.NO_MOVE, 0)
mob:setMobMod(xi.mobMod.NO_AGGRO, 0)
mob:setMobMod(xi.mobMod.NO_LINK, 0)
mob:setMagicCastingEnabled(true)
mob:setLocalVar('ResleepTime', 0)
end
xi.mix.eruca.config = function(mob, params)
if params.sleepHour and type(params.sleepHour) == 'number' then
mob:setLocalVar('[eruca]sleepHour', params.sleepHour)
end
if params.wakeHour and type(params.wakeHour) == 'number' then
mob:setLocalVar('[eruca]wakeHour', params.wakeHour)
end
end
g_mixins.families.eruca = function(erucaMob)
-- these defaults can be overwritten by using xi.mix.eruca.config() in onMobSpawn. sleepHour must be > wakeHour to function properly.
erucaMob:addListener('SPAWN', 'ERUCA_SPAWN', function(mob)
mob:setLocalVar('[eruca]sleepHour', 18)
mob:setLocalVar('[eruca]wakeHour', 6)
end)
erucaMob:addListener('ROAM_TICK', 'ERUCA_ROAM_TICK', function(mob)
local currentHour = VanadielHour()
local sleepHour = mob:getLocalVar('[eruca]sleepHour')
local subAnimation = mob:getAnimationSub()
if
subAnimation == 0 and
(currentHour >= sleepHour or currentHour < mob:getLocalVar('[eruca]wakeHour')) and
not mob:isEngaged()
then
local resleepTime = mob:getLocalVar('ResleepTime')
if resleepTime ~= 0 and mob:checkDistance(mob:getSpawnPos()) > 25 then
mob:setLocalVar('ResleepTime', GetSystemTime() + 120) -- Reset sleep timer until crawler returns home
elseif resleepTime <= GetSystemTime() then -- No timer was set (normal behavior) OR crawler has been back home for 2 minutes since disengaged
bedTime(mob)
end
elseif
subAnimation == 1 and
currentHour < sleepHour and
currentHour >= mob:getLocalVar('[eruca]wakeHour')
then
wakeUp(mob)
end
if
VanadielDayElement() == xi.element.FIRE and
mob:getMod(xi.mod.REGAIN) == 0
then
mob:setMod(xi.mod.REGAIN, 30)
elseif
VanadielDayElement() ~= xi.element.FIRE and
mob:getMod(xi.mod.REGAIN) ~= 0
then
mob:setMod(xi.mod.REGAIN, 0)
end
end)
erucaMob:addListener('ENGAGE', 'ERUCA_ENGAGE', function(mob, target)
if mob:getAnimationSub() == 1 then
wakeUp(mob)
end
end)
erucaMob:addListener('DISENGAGE', 'ERUCA_DISENGAGE', function(mob)
mob:setLocalVar('ResleepTime', GetSystemTime() + 120) -- Eruca crawlers go back to sleep exactly 2 minutes after they were engaged.
end)
end
return g_mixins.families.eruca
| 412 | 0.681956 | 1 | 0.681956 | game-dev | MEDIA | 0.922967 | game-dev | 0.861804 | 1 | 0.861804 |
Mod-Of-Theseus/Mod-Of-Theseus | 1,925 | Items/Blinds.lua | SMODS.Blind { -- by sephdotwav, art by inspectnerd
key = 'angel',
atlas = 'Blinds',
pos = {y = 1},
discovered = true,
boss = {min = 1},
boss_colour = HEX('c3e1ed'),
recalc_debuff = function(self, card, from_blind)
return card.area ~= G.jokers and not G.GAME.blind.disabled
end,
modify_hand = function(self, cards, poker_hands, text, mult, hand_chips)
for k, v in ipairs(cards) do
v:set_debuff(false)
end
return mult, hand_chips, false
end,
}
SMODS.Blind { -- by sephdotwav, art by inspectnerd
key = "demon",
atlas = "Blinds",
pos = {y = 0},
discovered = true,
boss = {min = 3},
boss_colour = HEX("a1261d"),
loc_vars = function(self)
return {
vars = {
G.GAME.probabilities.normal,
},
}
end,
collection_loc_vars = function(self)
return {
vars = {
1,
},
}
end,
modify_hand = function(self, cards, poker_hands, text, mult, hand_chips)
for k, v in ipairs(cards) do
if not G.GAME.blind.disabled and (pseudorandom(pseudoseed("demon")) < (G.GAME.probabilities.normal / 3)) then
v:set_debuff(true)
end
end
return mult, hand_chips, false
end,
}
SMODS.Blind { -- by sephdotwav, art by inspectnerd
key = "lapis_loupe",
atlas = "BlindsFinisher",
pos = {y = 0},
discovered = true,
mult = 5,
boss = {showdown = true},
boss_colour = HEX("1c53a8"),
set_blind = function(self)
self.hands_sub = G.GAME.round_resets.hands - 1
ease_hands_played(-self.hands_sub)
ease_discard(#G.deck.cards-1)
end,
disable = function(self)
ease_hands_played(self.hands_sub)
end,
press_play = function(self)
ease_discard(-G.GAME.current_round.discards_left)
end
} | 412 | 0.856536 | 1 | 0.856536 | game-dev | MEDIA | 0.965203 | game-dev | 0.879768 | 1 | 0.879768 |
folgerwang/UnrealEngine | 43,253 | Engine/Plugins/FX/Niagara/Source/Niagara/Private/NiagaraDataInterfaceCollisionQuery.cpp | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
#include "NiagaraDataInterfaceCollisionQuery.h"
#include "NiagaraTypes.h"
#include "NiagaraCustomVersion.h"
#include "NiagaraWorldManager.h"
#include "ShaderParameterUtils.h"
#include "GlobalDistanceFieldParameters.h"
#include "Shader.h"
//////////////////////////////////////////////////////////////////////////
//Color Curve
FCriticalSection UNiagaraDataInterfaceCollisionQuery::CriticalSection;
UNiagaraDataInterfaceCollisionQuery::UNiagaraDataInterfaceCollisionQuery(FObjectInitializer const& ObjectInitializer)
: Super(ObjectInitializer)
{
TraceChannelEnum = FindObject<UEnum>(ANY_PACKAGE, TEXT("ECollisionChannel"), true);
}
bool UNiagaraDataInterfaceCollisionQuery::InitPerInstanceData(void* PerInstanceData, FNiagaraSystemInstance* InSystemInstance)
{
CQDIPerInstanceData *PIData = new (PerInstanceData) CQDIPerInstanceData;
PIData->SystemInstance = InSystemInstance;
if (InSystemInstance)
{
PIData->CollisionBatch.Init(InSystemInstance->GetIDName(), InSystemInstance->GetComponent()->GetWorld());
}
return true;
}
void UNiagaraDataInterfaceCollisionQuery::PostInitProperties()
{
Super::PostInitProperties();
//Can we register data interfaces as regular types and fold them into the FNiagaraVariable framework for UI and function calls etc?
if (HasAnyFlags(RF_ClassDefaultObject))
{
FNiagaraTypeRegistry::Register(FNiagaraTypeDefinition(GetClass()), true, false, false);
}
}
void UNiagaraDataInterfaceCollisionQuery::PostLoad()
{
Super::PostLoad();
const int32 NiagaraVer = GetLinkerCustomVersion(FNiagaraCustomVersion::GUID);
}
void UNiagaraDataInterfaceCollisionQuery::GetFunctions(TArray<FNiagaraFunctionSignature>& OutFunctions)
{
FNiagaraFunctionSignature Sig3;
Sig3.Name = TEXT("PerformCollisionQuery");
Sig3.bMemberFunction = true;
Sig3.bRequiresContext = false;
Sig3.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition(GetClass()), TEXT("CollisionQuery")));
//Sig3.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetBoolDef(), TEXT("PerformQuery")));
Sig3.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetIntDef(), TEXT("ReturnQueryID")));
Sig3.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetVec3Def(), TEXT("ParticlePosition")));
Sig3.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetVec3Def(), TEXT("Direction")));
Sig3.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetFloatDef(), TEXT("DeltaTime")));
Sig3.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetFloatDef(), TEXT("CollisionSize")));
Sig3.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetFloatDef(), TEXT("DepthBounds")));
Sig3.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetIntDef(), TEXT("QueryID")));
Sig3.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetBoolDef(), TEXT("CollisionValid")));
Sig3.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetVec3Def(), TEXT("CollisionPos")));
Sig3.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetVec3Def(), TEXT("CollisionNormal")));
Sig3.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetFloatDef(), TEXT("Friction")));
Sig3.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetFloatDef(), TEXT("Restitution")));
OutFunctions.Add(Sig3);
FNiagaraFunctionSignature Sig;
Sig.Name = TEXT("SubmitQuery");
Sig.bMemberFunction = true;
Sig.bRequiresContext = false;
Sig.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition(GetClass()), TEXT("CollisionQuery")));
Sig.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetVec3Def(), TEXT("ParticlePosition")));
Sig.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetVec3Def(), TEXT("ParticleVelocity")));
Sig.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetFloatDef(), TEXT("DeltaTime")));
Sig.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetIntDef(), TEXT("CollisionID")));
OutFunctions.Add(Sig);
FNiagaraFunctionSignature Sig2;
Sig2.Name = TEXT("ReadQuery");
Sig2.bMemberFunction = true;
Sig2.bRequiresContext = false;
Sig2.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition(GetClass()), TEXT("CollisionQuery")));
Sig2.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetIntDef(), TEXT("CollisionID")));
Sig2.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetBoolDef(), TEXT("CollisionValid")));
Sig2.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetVec3Def(), TEXT("CollisionPos")));
Sig2.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetVec3Def(), TEXT("CollisionVelocity")));
Sig2.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetVec3Def(), TEXT("CollisionNormal")));
OutFunctions.Add(Sig2);
FNiagaraFunctionSignature SigGpu;
SigGpu.Name = TEXT("PerformCollisionQueryGPUShader");
SigGpu.bMemberFunction = true;
SigGpu.bRequiresContext = false;
SigGpu.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition(GetClass()), TEXT("CollisionQuery")));
SigGpu.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetVec3Def(), TEXT("DepthSamplePosWorld")));
SigGpu.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetVec3Def(), TEXT("TraceEndWorld")));
SigGpu.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetFloatDef(), TEXT("SceneDepthBounds")));
SigGpu.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetFloatDef(), TEXT("ParticleRadius")));
SigGpu.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetBoolDef(), TEXT("UseMeshDistanceField")));
SigGpu.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetBoolDef(), TEXT("CollisionValid")));
SigGpu.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetVec3Def(), TEXT("CollisionPosWorld")));
SigGpu.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetVec3Def(), TEXT("CollisionNormal")));
OutFunctions.Add(SigGpu);
FNiagaraFunctionSignature SigDepth;
SigDepth.Name = TEXT("QuerySceneDepthGPU");
SigDepth.bMemberFunction = true;
SigDepth.bRequiresContext = false;
SigDepth.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition(GetClass()), TEXT("CollisionQuery")));
SigDepth.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetVec3Def(), TEXT("DepthSamplePosWorld")));
SigDepth.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetFloatDef(), TEXT("SceneDepth")));
SigDepth.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetVec3Def(), TEXT("CameraPosWorld")));
SigDepth.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetBoolDef(), TEXT("IsInsideView")));
SigDepth.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetVec3Def(), TEXT("SamplePosWorld")));
SigDepth.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetVec3Def(), TEXT("SampleWorldNormal")));
OutFunctions.Add(SigDepth);
FNiagaraFunctionSignature SigMeshField;
SigMeshField.Name = TEXT("QueryMeshDistanceFieldGPU");
SigMeshField.bMemberFunction = true;
SigMeshField.bRequiresContext = false;
SigMeshField.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition(GetClass()), TEXT("CollisionQuery")));
SigMeshField.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetVec3Def(), TEXT("FieldSamplePosWorld")));
SigMeshField.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetFloatDef(), TEXT("DistanceToNearestSurface")));
SigMeshField.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetVec3Def(), TEXT("FieldGradient")));
OutFunctions.Add(SigMeshField);
FNiagaraFunctionSignature SigCpuSync;
SigCpuSync.Name = TEXT("PerformCollisionQuerySyncCPU");
SigCpuSync.bMemberFunction = true;
SigCpuSync.bRequiresContext = false;
SigCpuSync.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition(GetClass()), TEXT("CollisionQuery")));
SigCpuSync.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetVec3Def(), TEXT("TraceStartWorld")));
SigCpuSync.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetVec3Def(), TEXT("TraceEndWorld")));
SigCpuSync.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition(TraceChannelEnum), TEXT("TraceChannel")));
SigCpuSync.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetBoolDef(), TEXT("CollisionValid")));
SigCpuSync.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetBoolDef(), TEXT("IsTraceInsideMesh")));
SigCpuSync.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetVec3Def(), TEXT("CollisionPosWorld")));
SigCpuSync.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetVec3Def(), TEXT("CollisionNormal")));
SigCpuSync.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetFloatDef(), TEXT("CollisionMaterialFriction")));
SigCpuSync.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetFloatDef(), TEXT("CollisionMaterialRestitution")));
OutFunctions.Add(SigCpuSync);
FNiagaraFunctionSignature SigCpuAsync;
SigCpuAsync.Name = TEXT("PerformCollisionQueryAsyncCPU");
SigCpuAsync.bMemberFunction = true;
SigCpuAsync.bRequiresContext = false;
SigCpuAsync.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition(GetClass()), TEXT("CollisionQuery")));
SigCpuAsync.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetIntDef(), TEXT("PreviousFrameQueryID")));
SigCpuAsync.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetVec3Def(), TEXT("TraceStartWorld")));
SigCpuAsync.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetVec3Def(), TEXT("TraceEndWorld")));
SigCpuAsync.Inputs.Add(FNiagaraVariable(FNiagaraTypeDefinition(TraceChannelEnum), TEXT("TraceChannel")));
SigCpuAsync.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetIntDef(), TEXT("NextFrameQueryID")));
SigCpuAsync.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetBoolDef(), TEXT("CollisionValid")));
SigCpuAsync.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetBoolDef(), TEXT("IsTraceInsideMesh")));
SigCpuAsync.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetVec3Def(), TEXT("CollisionPosWorld")));
SigCpuAsync.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetVec3Def(), TEXT("CollisionNormal")));
SigCpuAsync.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetFloatDef(), TEXT("CollisionMaterialFriction")));
SigCpuAsync.Outputs.Add(FNiagaraVariable(FNiagaraTypeDefinition::GetFloatDef(), TEXT("CollisionMaterialRestitution")));
OutFunctions.Add(SigCpuAsync);
}
// build the shader function HLSL; function name is passed in, as it's defined per-DI; that way, configuration could change
// the HLSL in the spirit of a static switch
// TODO: need a way to identify each specific function here
//
bool UNiagaraDataInterfaceCollisionQuery::GetFunctionHLSL(const FName& DefinitionFunctionName, FString InstanceFunctionName, FNiagaraDataInterfaceGPUParamInfo& ParamInfo, FString& OutHLSL)
{
// a little tricky, since we've got two functions for submitting and retrieving a query; we store submitted queries per thread group,
// assuming it'll usually be the same thread trying to call ReadQuery for a particular QueryID, that submitted it in the first place.
if (DefinitionFunctionName == TEXT("PerformCollisionQuery"))
{
OutHLSL += TEXT("void ") + InstanceFunctionName + TEXT("(in int InQueryID, in float3 In_ParticlePos, in float3 In_ParticleVel, in float In_DeltaSeconds, float CollisionRadius, in float CollisionDepthBounds, \
out int Out_QueryID, out bool OutCollisionValid, out float3 Out_CollisionPos, out float3 Out_CollisionNormal, out float Out_Friction, out float Out_Restitution) \n{\n");
// get the screen position
OutHLSL += TEXT("\
OutCollisionValid = false;\n\
Out_QueryID = InQueryID;\n\
Out_CollisionPos = In_ParticlePos;\n\
Out_CollisionNormal = float3(0.0, 0.0, 1.0);\n\
Out_Friction = 0.0;\n\
Out_Restitution = 1.0;\n\
float3 DeltaPosition = In_DeltaSeconds * In_ParticleVel; \
float3 CollisionOffset = normalize(DeltaPosition) * CollisionRadius;\
float3 CollisionPosition = In_ParticlePos + CollisionOffset; \n\
float3 NewPosition = In_ParticlePos.xyz + DeltaPosition; \
float4 SamplePosition = float4(CollisionPosition + View.PreViewTranslation, 1); \n\
float4 ClipPosition = mul(SamplePosition, View.TranslatedWorldToClip);\n\
float2 ScreenPosition = ClipPosition.xy / ClipPosition.w;\n\
// Don't try to collide if the particle falls outside the view.\n\
if (all(abs(ScreenPosition.xy) <= float2(1, 1)))\n\
{\n\
// Sample the depth buffer to get a world position near the particle.\n\
float2 ScreenUV = ScreenPosition * View.ScreenPositionScaleBias.xy + View.ScreenPositionScaleBias.wz;\n\
float SceneDepth = CalcSceneDepth(ScreenUV);\n\
if (abs(ClipPosition.w - SceneDepth) < CollisionDepthBounds)\n\
{\n\
// Reconstruct world position.\n\
float3 WorldPosition = WorldPositionFromSceneDepth(ScreenPosition.xy, SceneDepth);\n\
// Sample the normal buffer to create a plane to collide against.\n\
float3 WorldNormal = Texture2DSampleLevel(SceneTexturesStruct.GBufferATexture, SceneTexturesStruct.GBufferATextureSampler, ScreenUV, 0).xyz * 2.0 - 1.0;\n\
float4 CollisionPlane = float4(WorldNormal, dot(WorldPosition.xyz, WorldNormal));\n\
// Compute the portion of velocity normal to the collision plane.\n\
float VelocityDot = dot(CollisionPlane.xyz, DeltaPosition.xyz);\n\
float d_back = (dot(CollisionPlane.xyz, In_ParticlePos.xyz) + CollisionRadius - CollisionPlane.w);\n\
float d_front = (dot(CollisionPlane.xyz, NewPosition.xyz) - CollisionRadius - CollisionPlane.w);\n\
// distance to the plane from current and predicted position\n\
if (d_back >= 0.0f && d_front <= 0.0f && VelocityDot < 0.0f)\n\
{\n\
OutCollisionValid = true;\n\
Out_CollisionPos = In_ParticlePos + (WorldNormal*d_back);\n\
Out_CollisionNormal = WorldNormal;\n\
Out_Friction = 0.0f;\n\
Out_Restitution = 1.0f;\n\
Out_QueryID = 0;\
}\n\
else\n\
{\n\
OutCollisionValid = false; \n\
}\n\
}\n\
}\n}\n\n");
}
else if (DefinitionFunctionName == TEXT("PerformCollisionQueryGPUShader"))
{
FString SceneDepthFunction = InstanceFunctionName + TEXT("_SceneDepthCollision");
FString DistanceFieldFunction = InstanceFunctionName + TEXT("_DistanceFieldCollision");
OutHLSL += TEXT("void ") + SceneDepthFunction + TEXT("(in float3 In_SamplePos, in float3 In_TraceEndPos, in float CollisionDepthBounds, in float ParticleRadius, out bool OutCollisionValid, out float3 Out_CollisionPos, out float3 Out_CollisionNormal) \n{\n\
OutCollisionValid = false;\n\
Out_CollisionPos = In_SamplePos;\n\
Out_CollisionNormal = float3(0.0, 0.0, 1.0);\n\
float4 SamplePosition = float4(In_SamplePos + View.PreViewTranslation, 1); \n\
float4 ClipPosition = mul(SamplePosition, View.TranslatedWorldToClip);\n\
float2 ScreenPosition = ClipPosition.xy / ClipPosition.w;\n\
// Don't try to collide if the particle falls outside the view.\n\
if (all(abs(ScreenPosition.xy) <= float2(1, 1)))\n\
{\n\
// Sample the depth buffer to get a world position near the particle.\n\
float2 ScreenUV = ScreenPosition * View.ScreenPositionScaleBias.xy + View.ScreenPositionScaleBias.wz;\n\
float SceneDepth = CalcSceneDepth(ScreenUV);\n\
if (abs(ClipPosition.w - SceneDepth) < CollisionDepthBounds)\n\
{\n\
// Reconstruct world position.\n\
float3 WorldPosition = WorldPositionFromSceneDepth(ScreenPosition.xy, SceneDepth);\n\
// Sample the normal buffer to create a plane to collide against.\n\
float3 WorldNormal = Texture2DSampleLevel(SceneTexturesStruct.GBufferATexture, SceneTexturesStruct.GBufferATextureSampler, ScreenUV, 0).xyz * 2.0 - 1.0;\n\
float4 CollisionPlane = float4(WorldNormal, dot(WorldPosition.xyz, WorldNormal));\n\
// Compute the portion of velocity normal to the collision plane.\n\
float VelocityDot = dot(CollisionPlane.xyz, (In_TraceEndPos - In_SamplePos).xyz);\n\
float d_back = (dot(CollisionPlane.xyz, In_SamplePos.xyz) + ParticleRadius - CollisionPlane.w);\n\
float d_front = (dot(CollisionPlane.xyz, In_TraceEndPos.xyz) - ParticleRadius - CollisionPlane.w);\n\
// distance to the plane from current and predicted position\n\
if (d_back >= 0.0f && d_front <= 0.0f && VelocityDot < 0.0f)\n\
{\n\
OutCollisionValid = true;\n\
Out_CollisionPos = In_SamplePos + (WorldNormal*d_back);\n\
Out_CollisionNormal = WorldNormal;\n\
}\n\
}\n\
}\
\n}\n\n");
OutHLSL += TEXT("void ") + DistanceFieldFunction + TEXT("(in float3 InPosition, in float3 In_TraceEndPos, out bool OutCollisionValid, out float3 Out_CollisionPos, out float3 Out_CollisionNormal)\n{\n\
float DistanceToNearestSurface = GetDistanceToNearestSurfaceGlobal(InPosition);\n\
if (DistanceToNearestSurface < length(In_TraceEndPos - InPosition))\n\
{\n\
OutCollisionValid = true;\n\
Out_CollisionNormal = normalize(GetDistanceFieldGradientGlobal(InPosition));\n\
Out_CollisionPos = InPosition - Out_CollisionNormal * DistanceToNearestSurface;\n\
}\n\
else\n\
{\n\
OutCollisionValid = false;\n\
Out_CollisionNormal = float3(0.0, 0.0, 1.0);\n\
Out_CollisionPos = InPosition;\n\
}\n}\n\n");
OutHLSL += TEXT("void ") + InstanceFunctionName + TEXT("(in float3 In_SamplePos, in float3 In_TraceEndPos, in float CollisionDepthBounds, ") +
TEXT("in float ParticleRadius, in bool UseMeshDistanceField, out bool OutCollisionValid, out float3 Out_CollisionPos, out float3 Out_CollisionNormal) \n{\n");
OutHLSL += TEXT("\
if (UseMeshDistanceField)\n\
{\n\
") + DistanceFieldFunction + TEXT("(In_SamplePos, In_TraceEndPos, OutCollisionValid, Out_CollisionPos, Out_CollisionNormal);\n\
}\n\
else\n\
{\n\
") + SceneDepthFunction + TEXT("(In_SamplePos, In_TraceEndPos, CollisionDepthBounds, ParticleRadius, OutCollisionValid, Out_CollisionPos, Out_CollisionNormal);\n\
}\n}\n\n");
}
else if (DefinitionFunctionName == TEXT("QuerySceneDepthGPU"))
{
OutHLSL += TEXT("void ") + InstanceFunctionName + TEXT("(in float3 In_SamplePos, out float Out_SceneDepth, out float3 Out_CameraPosWorld, out bool Out_IsInsideView, out float3 Out_WorldPos, out float3 Out_WorldNormal) \n{\n");
OutHLSL += TEXT("\
Out_SceneDepth = -1;\n\
Out_WorldPos = float3(0.0, 0.0, 0.0);\n\
Out_WorldNormal = float3(0.0, 0.0, 1.0);\n\
Out_IsInsideView = true;\n\
Out_CameraPosWorld.xyz = View.WorldCameraOrigin.xyz;\n\
float4 SamplePosition = float4(In_SamplePos + View.PreViewTranslation, 1);\n\
float4 ClipPosition = mul(SamplePosition, View.TranslatedWorldToClip);\n\
float2 ScreenPosition = ClipPosition.xy / ClipPosition.w;\n\
// Check if the sample is inside the view.\n\
if (all(abs(ScreenPosition.xy) <= float2(1, 1)))\n\
{\n\
// Sample the depth buffer to get a world position near the sample position.\n\
float2 ScreenUV = ScreenPosition * View.ScreenPositionScaleBias.xy + View.ScreenPositionScaleBias.wz;\n\
float SceneDepth = CalcSceneDepth(ScreenUV);\n\
Out_SceneDepth = SceneDepth;\n\
// Reconstruct world position.\n\
Out_WorldPos = WorldPositionFromSceneDepth(ScreenPosition.xy, SceneDepth);\n\
// Sample the normal buffer\n\
Out_WorldNormal = Texture2DSampleLevel(SceneTexturesStruct.GBufferATexture, SceneTexturesStruct.GBufferATextureSampler, ScreenUV, 0).xyz * 2.0 - 1.0;\n\
}\n\
else\n\
{\n\
Out_IsInsideView = false;\n\
}\n}\n\n");
}
else if (DefinitionFunctionName == TEXT("QueryMeshDistanceFieldGPU"))
{
OutHLSL += TEXT("void ") + InstanceFunctionName + TEXT("(in float3 In_SamplePos, out float Out_DistanceToNearestSurface, out float3 Out_FieldGradient) \n{\n");
OutHLSL += TEXT("\
Out_DistanceToNearestSurface = GetDistanceToNearestSurfaceGlobal(In_SamplePos);\n\
Out_FieldGradient = GetDistanceFieldGradientGlobal(In_SamplePos);\
\n}\n\n");
}
return true;
}
void UNiagaraDataInterfaceCollisionQuery::GetParameterDefinitionHLSL(FNiagaraDataInterfaceGPUParamInfo& ParamInfo, FString& OutHLSL)
{
// we don't need to add these to hlsl, as they're already in common.ush
}
DEFINE_NDI_DIRECT_FUNC_BINDER(UNiagaraDataInterfaceCollisionQuery, SubmitQuery);
DEFINE_NDI_DIRECT_FUNC_BINDER(UNiagaraDataInterfaceCollisionQuery, ReadQuery);
DEFINE_NDI_DIRECT_FUNC_BINDER(UNiagaraDataInterfaceCollisionQuery, PerformQuery);
DEFINE_NDI_DIRECT_FUNC_BINDER(UNiagaraDataInterfaceCollisionQuery, PerformQuerySyncCPU);
DEFINE_NDI_DIRECT_FUNC_BINDER(UNiagaraDataInterfaceCollisionQuery, PerformQueryAsyncCPU);
DEFINE_NDI_DIRECT_FUNC_BINDER(UNiagaraDataInterfaceCollisionQuery, PerformQueryGPU);
DEFINE_NDI_DIRECT_FUNC_BINDER(UNiagaraDataInterfaceCollisionQuery, QuerySceneDepth);
DEFINE_NDI_DIRECT_FUNC_BINDER(UNiagaraDataInterfaceCollisionQuery, QueryMeshDistanceField);
void UNiagaraDataInterfaceCollisionQuery::GetVMExternalFunction(const FVMExternalFunctionBindingInfo& BindingInfo, void* InstanceData, FVMExternalFunction &OutFunc)
{
CQDIPerInstanceData *InstData = (CQDIPerInstanceData *)InstanceData;
if (BindingInfo.Name == TEXT("SubmitQuery") /*&& BindingInfo.GetNumInputs() == 3 && BindingInfo.GetNumOutputs() == 1*/)
{
NDI_FUNC_BINDER(UNiagaraDataInterfaceCollisionQuery, SubmitQuery)::Bind(this, OutFunc);
}
else if (BindingInfo.Name == TEXT("ReadQuery") /*&& BindingInfo.GetNumInputs() == 1 && BindingInfo.GetNumOutputs() == 4*/)
{
NDI_FUNC_BINDER(UNiagaraDataInterfaceCollisionQuery, ReadQuery)::Bind(this, OutFunc);
}
else if (BindingInfo.Name == TEXT("PerformCollisionQuery") /*&& BindingInfo.GetNumInputs() == 1 && BindingInfo.GetNumOutputs() == 4*/)
{
NDI_FUNC_BINDER(UNiagaraDataInterfaceCollisionQuery, PerformQuery)::Bind(this, OutFunc);
}
else if (BindingInfo.Name == TEXT("PerformCollisionQuerySyncCPU"))
{
NDI_FUNC_BINDER(UNiagaraDataInterfaceCollisionQuery, PerformQuerySyncCPU)::Bind(this, OutFunc);
}
else if (BindingInfo.Name == TEXT("PerformCollisionQueryAsyncCPU"))
{
NDI_FUNC_BINDER(UNiagaraDataInterfaceCollisionQuery, PerformQueryAsyncCPU)::Bind(this, OutFunc);
}
else if (BindingInfo.Name == TEXT("PerformCollisionQueryGPUShader"))
{
NDI_FUNC_BINDER(UNiagaraDataInterfaceCollisionQuery, PerformQueryGPU)::Bind(this, OutFunc);
}
else if (BindingInfo.Name == TEXT("QuerySceneDepthGPU"))
{
NDI_FUNC_BINDER(UNiagaraDataInterfaceCollisionQuery, QuerySceneDepth)::Bind(this, OutFunc);
}
else if (BindingInfo.Name == TEXT("QueryMeshDistanceFieldGPU"))
{
NDI_FUNC_BINDER(UNiagaraDataInterfaceCollisionQuery, QueryMeshDistanceField)::Bind(this, OutFunc);
}
else
{
UE_LOG(LogNiagara, Error, TEXT("Could not find data interface external function. %s\n"),
*BindingInfo.Name.ToString());
}
}
void UNiagaraDataInterfaceCollisionQuery::PerformQuery(FVectorVMContext& Context)
{
//PerformType PerformParam(Context);
VectorVM::FExternalFuncInputHandler<int32> InIDParam(Context);
VectorVM::FExternalFuncInputHandler<float> PosParamX(Context);
VectorVM::FExternalFuncInputHandler<float> PosParamY(Context);
VectorVM::FExternalFuncInputHandler<float> PosParamZ(Context);
VectorVM::FExternalFuncInputHandler<float> DirParamX(Context);
VectorVM::FExternalFuncInputHandler<float> DirParamY(Context);
VectorVM::FExternalFuncInputHandler<float> DirParamZ(Context);
VectorVM::FExternalFuncInputHandler<float> DTParam(Context);
VectorVM::FExternalFuncInputHandler<float> SizeParam(Context);
VectorVM::FExternalFuncInputHandler<float> DepthBoundsParam(Context);
VectorVM::FUserPtrHandler<CQDIPerInstanceData> InstanceData(Context);
VectorVM::FExternalFuncRegisterHandler<int32> OutQueryID(Context);
VectorVM::FExternalFuncRegisterHandler<int32> OutQueryValid(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionPosX(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionPosY(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionPosZ(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionNormX(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionNormY(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionNormZ(Context);
VectorVM::FExternalFuncRegisterHandler<float> Friction(Context);
VectorVM::FExternalFuncRegisterHandler<float> Restitution(Context);
FScopeLock ScopeLock(&CriticalSection);
for (int32 i = 0; i < Context.NumInstances; ++i)
{
// submit a query, get query id in return
//if (PerformParam.Get())
{
FVector Pos(PosParamX.Get(), PosParamY.Get(), PosParamZ.Get());
FVector Dir(DirParamX.Get(), DirParamY.Get(), DirParamZ.Get());
ensure(!Pos.ContainsNaN());
float Dt = DTParam.Get();
float Size = SizeParam.Get();
*OutQueryID.GetDest() = InstanceData->CollisionBatch.SubmitQuery(Pos, Dir, Size, Dt);
}
// try to retrieve a query with the supplied query ID
FNiagaraDICollsionQueryResult Res;
int32 ID = InIDParam.Get();
bool Valid = InstanceData->CollisionBatch.GetQueryResult(ID, Res);
if (Valid)
{
*OutQueryValid.GetDest() = 0xFFFFFFFF; //->SetValue(true);
*OutCollisionPosX.GetDest() = Res.CollisionPos.X;
*OutCollisionPosY.GetDest() = Res.CollisionPos.Y;
*OutCollisionPosZ.GetDest() = Res.CollisionPos.Z;
*OutCollisionNormX.GetDest() = Res.CollisionNormal.X;
*OutCollisionNormY.GetDest() = Res.CollisionNormal.Y;
*OutCollisionNormZ.GetDest() = Res.CollisionNormal.Z;
*Friction.GetDest() = Res.Friction;
*Restitution.GetDest() = Res.Restitution;
}
else
{
*OutQueryValid.GetDest() = 0;// ->SetValue(false);
*OutCollisionPosX.GetDest() = 0.0f;
*OutCollisionPosY.GetDest() = 0.0f;
*OutCollisionPosZ.GetDest() = 0.0f;
*OutCollisionNormX.GetDest() = 0.0f;
*OutCollisionNormY.GetDest() = 0.0f;
*OutCollisionNormZ.GetDest() = 0.0f;
*Friction.GetDest() = 0.0f;
*Restitution.GetDest() = 0.0f;
}
//PerformParam.Advance();
InIDParam.Advance();
OutQueryValid.Advance();
OutCollisionPosX.Advance();
OutCollisionPosY.Advance();
OutCollisionPosZ.Advance();
OutCollisionNormX.Advance();
OutCollisionNormY.Advance();
OutCollisionNormZ.Advance();
Friction.Advance();
Restitution.Advance();
PosParamX.Advance();
PosParamY.Advance();
PosParamZ.Advance();
DirParamX.Advance();
DirParamY.Advance();
DirParamZ.Advance();
DTParam.Advance();
SizeParam.Advance();
DepthBoundsParam.Advance();
OutQueryID.Advance();
}
}
void UNiagaraDataInterfaceCollisionQuery::PerformQuerySyncCPU(FVectorVMContext & Context)
{
VectorVM::FExternalFuncInputHandler<float> StartPosParamX(Context);
VectorVM::FExternalFuncInputHandler<float> StartPosParamY(Context);
VectorVM::FExternalFuncInputHandler<float> StartPosParamZ(Context);
VectorVM::FExternalFuncInputHandler<float> EndPosParamX(Context);
VectorVM::FExternalFuncInputHandler<float> EndPosParamY(Context);
VectorVM::FExternalFuncInputHandler<float> EndPosParamZ(Context);
VectorVM::FExternalFuncInputHandler<ECollisionChannel> TraceChannelParam(Context);
VectorVM::FUserPtrHandler<CQDIPerInstanceData> InstanceData(Context);
VectorVM::FExternalFuncRegisterHandler<int32> OutQueryValid(Context);
VectorVM::FExternalFuncRegisterHandler<int32> OutInsideMesh(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionPosX(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionPosY(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionPosZ(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionNormX(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionNormY(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionNormZ(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutFriction(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutRestitution(Context);
FScopeLock ScopeLock(&CriticalSection);
for (int32 i = 0; i < Context.NumInstances; ++i)
{
FVector Pos(StartPosParamX.GetAndAdvance(), StartPosParamY.GetAndAdvance(), StartPosParamZ.GetAndAdvance());
FVector Dir(EndPosParamX.GetAndAdvance(), EndPosParamY.GetAndAdvance(), EndPosParamZ.GetAndAdvance());
ECollisionChannel TraceChannel = TraceChannelParam.GetAndAdvance();
ensure(!Pos.ContainsNaN());
FNiagaraDICollsionQueryResult Res;
bool Valid = InstanceData->CollisionBatch.PerformQuery(Pos, Dir, Res, TraceChannel);
if (Valid)
{
*OutQueryValid.GetDestAndAdvance() = 0xFFFFFFFF; //->SetValue(true);
*OutInsideMesh.GetDestAndAdvance() = Res.IsInsideMesh ? 0xFFFFFFFF : 0;
*OutCollisionPosX.GetDestAndAdvance() = Res.CollisionPos.X;
*OutCollisionPosY.GetDestAndAdvance() = Res.CollisionPos.Y;
*OutCollisionPosZ.GetDestAndAdvance() = Res.CollisionPos.Z;
*OutCollisionNormX.GetDestAndAdvance() = Res.CollisionNormal.X;
*OutCollisionNormY.GetDestAndAdvance() = Res.CollisionNormal.Y;
*OutCollisionNormZ.GetDestAndAdvance() = Res.CollisionNormal.Z;
*OutFriction.GetDestAndAdvance() = Res.Friction;
*OutRestitution.GetDestAndAdvance() = Res.Restitution;
}
else
{
*OutQueryValid.GetDestAndAdvance() = 0; //->SetValue(false);
*OutInsideMesh.GetDestAndAdvance() = 0;
*OutCollisionPosX.GetDestAndAdvance() = 0.0f;
*OutCollisionPosY.GetDestAndAdvance() = 0.0f;
*OutCollisionPosZ.GetDestAndAdvance() = 0.0f;
*OutCollisionNormX.GetDestAndAdvance() = 0.0f;
*OutCollisionNormY.GetDestAndAdvance() = 0.0f;
*OutCollisionNormZ.GetDestAndAdvance() = 0.0f;
*OutFriction.GetDestAndAdvance() = 0.0f;
*OutRestitution.GetDestAndAdvance() = 0.0f;
}
}
}
void UNiagaraDataInterfaceCollisionQuery::PerformQueryAsyncCPU(FVectorVMContext & Context)
{
VectorVM::FExternalFuncInputHandler<int32> InIDParam(Context);
VectorVM::FExternalFuncInputHandler<float> StartPosParamX(Context);
VectorVM::FExternalFuncInputHandler<float> StartPosParamY(Context);
VectorVM::FExternalFuncInputHandler<float> StartPosParamZ(Context);
VectorVM::FExternalFuncInputHandler<float> EndPosParamX(Context);
VectorVM::FExternalFuncInputHandler<float> EndPosParamY(Context);
VectorVM::FExternalFuncInputHandler<float> EndPosParamZ(Context);
VectorVM::FExternalFuncInputHandler<ECollisionChannel> TraceChannelParam(Context);
VectorVM::FUserPtrHandler<CQDIPerInstanceData> InstanceData(Context);
VectorVM::FExternalFuncRegisterHandler<int32> OutQueryID(Context);
VectorVM::FExternalFuncRegisterHandler<int32> OutQueryValid(Context);
VectorVM::FExternalFuncRegisterHandler<int32> OutInsideMesh(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionPosX(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionPosY(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionPosZ(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionNormX(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionNormY(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionNormZ(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutFriction(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutRestitution(Context);
FScopeLock ScopeLock(&CriticalSection);
for (int32 i = 0; i < Context.NumInstances; ++i)
{
FVector Pos(StartPosParamX.GetAndAdvance(), StartPosParamY.GetAndAdvance(), StartPosParamZ.GetAndAdvance());
FVector Dir(EndPosParamX.GetAndAdvance(), EndPosParamY.GetAndAdvance(), EndPosParamZ.GetAndAdvance());
ECollisionChannel TraceChannel = TraceChannelParam.GetAndAdvance();
ensure(!Pos.ContainsNaN());
*OutQueryID.GetDestAndAdvance() = InstanceData->CollisionBatch.SubmitQuery(Pos, Dir, TraceChannel);
// try to retrieve a query with the supplied query ID
FNiagaraDICollsionQueryResult Res;
int32 ID = InIDParam.GetAndAdvance();
bool Valid = InstanceData->CollisionBatch.GetQueryResult(ID, Res);
if (Valid)
{
*OutQueryValid.GetDestAndAdvance() = 0xFFFFFFFF; //->SetValue(true);
*OutInsideMesh.GetDestAndAdvance() = Res.IsInsideMesh ? 0xFFFFFFFF : 0;
*OutCollisionPosX.GetDestAndAdvance() = Res.CollisionPos.X;
*OutCollisionPosY.GetDestAndAdvance() = Res.CollisionPos.Y;
*OutCollisionPosZ.GetDestAndAdvance() = Res.CollisionPos.Z;
*OutCollisionNormX.GetDestAndAdvance() = Res.CollisionNormal.X;
*OutCollisionNormY.GetDestAndAdvance() = Res.CollisionNormal.Y;
*OutCollisionNormZ.GetDestAndAdvance() = Res.CollisionNormal.Z;
*OutFriction.GetDestAndAdvance() = Res.Friction;
*OutRestitution.GetDestAndAdvance() = Res.Restitution;
}
else
{
*OutQueryValid.GetDestAndAdvance() = 0; //->SetValue(false);
*OutInsideMesh.GetDestAndAdvance() = 0;
*OutCollisionPosX.GetDestAndAdvance() = 0.0f;
*OutCollisionPosY.GetDestAndAdvance() = 0.0f;
*OutCollisionPosZ.GetDestAndAdvance() = 0.0f;
*OutCollisionNormX.GetDestAndAdvance() = 0.0f;
*OutCollisionNormY.GetDestAndAdvance() = 0.0f;
*OutCollisionNormZ.GetDestAndAdvance() = 0.0f;
*OutFriction.GetDestAndAdvance() = 0.0f;
*OutRestitution.GetDestAndAdvance() = 0.0f;
}
}
}
void UNiagaraDataInterfaceCollisionQuery::PerformQueryGPU(FVectorVMContext& Context)
{
UE_LOG(LogNiagara, Error, TEXT("GPU only function 'PerformQueryGPU' called on CPU VM, check your module code to fix."));
VectorVM::FExternalFuncInputHandler<float> StartPosParamX(Context);
VectorVM::FExternalFuncInputHandler<float> StartPosParamY(Context);
VectorVM::FExternalFuncInputHandler<float> StartPosParamZ(Context);
VectorVM::FExternalFuncInputHandler<float> EndPosParamX(Context);
VectorVM::FExternalFuncInputHandler<float> EndPosParamY(Context);
VectorVM::FExternalFuncInputHandler<float> EndPosParamZ(Context);
VectorVM::FExternalFuncInputHandler<float> SceneDepthBoundsParam(Context);
VectorVM::FExternalFuncInputHandler<float> ParticleRadiusParam(Context);
VectorVM::FExternalFuncInputHandler<int32> UseDistanceFieldParam(Context);
VectorVM::FUserPtrHandler<CQDIPerInstanceData> InstanceData(Context);
VectorVM::FExternalFuncRegisterHandler<int32> OutQueryValid(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionPosX(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionPosY(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionPosZ(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionNormX(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionNormY(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionNormZ(Context);
FScopeLock ScopeLock(&CriticalSection);
for (int32 i = 0; i < Context.NumInstances; ++i)
{
*OutQueryValid.GetDestAndAdvance() = 0;// ->SetValue(false);
*OutCollisionPosX.GetDestAndAdvance() = 0.0f;
*OutCollisionPosY.GetDestAndAdvance() = 0.0f;
*OutCollisionPosZ.GetDestAndAdvance() = 0.0f;
*OutCollisionNormX.GetDestAndAdvance() = 0.0f;
*OutCollisionNormY.GetDestAndAdvance() = 0.0f;
*OutCollisionNormZ.GetDestAndAdvance() = 1.0f;
}
}
void UNiagaraDataInterfaceCollisionQuery::QuerySceneDepth(FVectorVMContext & Context)
{
UE_LOG(LogNiagara, Error, TEXT("GPU only function 'QuerySceneDepthGPU' called on CPU VM, check your module code to fix."));
VectorVM::FExternalFuncInputHandler<float> SamplePosParamX(Context);
VectorVM::FExternalFuncInputHandler<float> SamplePosParamY(Context);
VectorVM::FExternalFuncInputHandler<float> SamplePosParamZ(Context);
VectorVM::FUserPtrHandler<CQDIPerInstanceData> InstanceData(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutSceneDepth(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCameraPosX(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCameraPosY(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCameraPosZ(Context);
VectorVM::FExternalFuncRegisterHandler<int32> OutIsInsideView(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutWorldPosX(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutWorldPosY(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutWorldPosZ(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutWorldNormX(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutWorldNormY(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutWorldNormZ(Context);
FScopeLock ScopeLock(&CriticalSection);
for (int32 i = 0; i < Context.NumInstances; ++i)
{
*OutSceneDepth.GetDestAndAdvance() = -1;
*OutIsInsideView.GetDestAndAdvance() = 0;
*OutWorldPosX.GetDestAndAdvance() = 0.0f;
*OutWorldPosY.GetDestAndAdvance() = 0.0f;
*OutWorldPosZ.GetDestAndAdvance() = 0.0f;
*OutWorldNormX.GetDestAndAdvance() = 0.0f;
*OutWorldNormY.GetDestAndAdvance() = 0.0f;
*OutWorldNormZ.GetDestAndAdvance() = 1.0f;
*OutCameraPosX.GetDestAndAdvance() = 0.0f;
*OutCameraPosY.GetDestAndAdvance() = 0.0f;
*OutCameraPosZ.GetDestAndAdvance() = 0.0f;
}
}
void UNiagaraDataInterfaceCollisionQuery::QueryMeshDistanceField(FVectorVMContext& Context)
{
UE_LOG(LogNiagara, Error, TEXT("GPU only function 'QueryMeshDistanceFieldGPU' called on CPU VM, check your module code to fix."));
VectorVM::FExternalFuncInputHandler<float> SamplePosParamX(Context);
VectorVM::FExternalFuncInputHandler<float> SamplePosParamY(Context);
VectorVM::FExternalFuncInputHandler<float> SamplePosParamZ(Context);
VectorVM::FUserPtrHandler<CQDIPerInstanceData> InstanceData(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutSurfaceDistance(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutFieldGradientX(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutFieldGradientY(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutFieldGradientZ(Context);
FScopeLock ScopeLock(&CriticalSection);
for (int32 i = 0; i < Context.NumInstances; ++i)
{
*OutSurfaceDistance.GetDestAndAdvance() = -1;
*OutFieldGradientX.GetDestAndAdvance() = 0.0f;
*OutFieldGradientY.GetDestAndAdvance() = 0.0f;
*OutFieldGradientZ.GetDestAndAdvance() = 1.0f;
}
}
void UNiagaraDataInterfaceCollisionQuery::SubmitQuery(FVectorVMContext& Context)
{
VectorVM::FExternalFuncInputHandler<float> PosParamX(Context);
VectorVM::FExternalFuncInputHandler<float> PosParamY(Context);
VectorVM::FExternalFuncInputHandler<float> PosParamZ(Context);
VectorVM::FExternalFuncInputHandler<float> VelParamX(Context);
VectorVM::FExternalFuncInputHandler<float> VelParamY(Context);
VectorVM::FExternalFuncInputHandler<float> VelParamZ(Context);
VectorVM::FExternalFuncInputHandler<float> DTParam(Context);
VectorVM::FUserPtrHandler<CQDIPerInstanceData> InstanceData(Context);
FScopeLock ScopeLock(&CriticalSection);
VectorVM::FExternalFuncRegisterHandler<int32> OutQueryID(Context);
for (int32 i = 0; i < Context.NumInstances; ++i)
{
FVector Pos(PosParamX.Get(), PosParamY.Get(), PosParamZ.Get());
FVector Vel(VelParamX.Get(), VelParamY.Get(), VelParamZ.Get());
ensure(!Pos.ContainsNaN());
ensure(!Vel.ContainsNaN());
float Dt = DTParam.Get();
*OutQueryID.GetDest() = InstanceData->CollisionBatch.SubmitQuery(Pos, Vel, 0.0f, Dt);
PosParamX.Advance();
PosParamY.Advance();
PosParamZ.Advance();
VelParamX.Advance();
VelParamY.Advance();
VelParamZ.Advance();
DTParam.Advance();
OutQueryID.Advance();
}
}
void UNiagaraDataInterfaceCollisionQuery::ReadQuery(FVectorVMContext& Context)
{
VectorVM::FExternalFuncInputHandler<int32> IDParam(Context);
VectorVM::FUserPtrHandler<CQDIPerInstanceData> InstanceData(Context);
VectorVM::FExternalFuncRegisterHandler<int32> OutQueryValid(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionPosX(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionPosY(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionPosZ(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionVelX(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionVelY(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionVelZ(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionNormX(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionNormY(Context);
VectorVM::FExternalFuncRegisterHandler<float> OutCollisionNormZ(Context);
FScopeLock ScopeLock(&CriticalSection);
for (int32 i = 0; i < Context.NumInstances; ++i)
{
FNiagaraDICollsionQueryResult Res;
int32 ID = IDParam.Get();
bool Valid = InstanceData->CollisionBatch.GetQueryResult(ID, Res);
if (Valid)
{
*OutQueryValid.GetDest() = 0xFFFFFFFF; //->SetValue(true);
*OutCollisionPosX.GetDest() = Res.CollisionPos.X;
*OutCollisionPosY.GetDest() = Res.CollisionPos.Y;
*OutCollisionPosZ.GetDest() = Res.CollisionPos.Z;
*OutCollisionVelX.GetDest() = Res.CollisionVelocity.X;
*OutCollisionVelY.GetDest() = Res.CollisionVelocity.Y;
*OutCollisionVelZ.GetDest() = Res.CollisionVelocity.Z;
*OutCollisionNormX.GetDest() = Res.CollisionNormal.X;
*OutCollisionNormY.GetDest() = Res.CollisionNormal.Y;
*OutCollisionNormZ.GetDest() = Res.CollisionNormal.Z;
}
else
{
*OutQueryValid.GetDest() = 0;// ->SetValue(false);
}
IDParam.Advance();
OutQueryValid.Advance();
OutCollisionPosX.Advance();
OutCollisionPosY.Advance();
OutCollisionPosZ.Advance();
OutCollisionVelX.Advance();
OutCollisionVelY.Advance();
OutCollisionVelZ.Advance();
OutCollisionNormX.Advance();
OutCollisionNormY.Advance();
OutCollisionNormZ.Advance();
}
}
bool UNiagaraDataInterfaceCollisionQuery::PerInstanceTick(void* PerInstanceData, FNiagaraSystemInstance* InSystemInstance, float DeltaSeconds)
{
return false;
}
bool UNiagaraDataInterfaceCollisionQuery::PerInstanceTickPostSimulate(void* PerInstanceData, FNiagaraSystemInstance* InSystemInstance, float DeltaSeconds)
{
CQDIPerInstanceData *PIData = static_cast<CQDIPerInstanceData*>(PerInstanceData);
PIData->CollisionBatch.Tick(ENiagaraSimTarget::CPUSim);
PIData->CollisionBatch.ClearWrite();
return false;
}
//////////////////////////////////////////////////////////////////////////
struct FNiagaraDataInterfaceParametersCS_CollisionQuery : public FNiagaraDataInterfaceParametersCS
{
virtual void Bind(const FNiagaraDataInterfaceParamRef& ParamRef, const class FShaderParameterMap& ParameterMap) override
{
PassUniformBuffer.Bind(ParameterMap, FSceneTexturesUniformParameters::StaticStructMetadata.GetShaderVariableName());
GlobalDistanceFieldParameters.Bind(ParameterMap);
if (GlobalDistanceFieldParameters.IsBound())
{
GNiagaraViewDataManager.SetGlobalDistanceFieldUsage();
}
}
virtual void Serialize(FArchive& Ar) override
{
Ar << PassUniformBuffer;
Ar << GlobalDistanceFieldParameters;
}
virtual void Set(FRHICommandList& RHICmdList, FNiagaraShader* Shader, class UNiagaraDataInterface* DataInterface, void* PerInstanceData) const override
{
check(IsInRenderingThread());
const FComputeShaderRHIParamRef ComputeShaderRHI = Shader->GetComputeShader();
TUniformBufferRef<FSceneTexturesUniformParameters> SceneTextureUniformParams = GNiagaraViewDataManager.GetSceneTextureUniformParameters();
SetUniformBufferParameter(RHICmdList, ComputeShaderRHI, PassUniformBuffer/*Shader->GetUniformBufferParameter(SceneTexturesUniformBufferStruct)*/, SceneTextureUniformParams);
if (GlobalDistanceFieldParameters.IsBound())
{
GNiagaraViewDataManager.SetGlobalDistanceFieldUsage();
GlobalDistanceFieldParameters.Set(RHICmdList, ComputeShaderRHI, *GNiagaraViewDataManager.GetGlobalDistanceFieldParameters());
}
}
private:
/** The SceneDepthTexture parameter for depth buffer collision. */
FShaderUniformBufferParameter PassUniformBuffer;
FGlobalDistanceFieldParameters GlobalDistanceFieldParameters;
};
FNiagaraDataInterfaceParametersCS* UNiagaraDataInterfaceCollisionQuery::ConstructComputeParameters() const
{
return new FNiagaraDataInterfaceParametersCS_CollisionQuery();
} | 412 | 0.820532 | 1 | 0.820532 | game-dev | MEDIA | 0.394439 | game-dev | 0.790986 | 1 | 0.790986 |
contextgarden/context | 4,429 | tex/context/base/mkxl/trac-jus.lmt | if not modules then modules = { } end modules ['trac-jus'] = {
version = 1.001,
comment = "companion to trac-jus.mkiv",
author = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright = "PRAGMA ADE / ConTeXt Development Team",
license = "see context related readme files"
}
local checkers = typesetters.checkers or { }
typesetters.checkers = checkers
----- report_justification = logs.reporter("visualize","justification")
local a_alignstate <const> = attributes.private("alignstate")
local a_justification <const> = attributes.private("justification")
local nuts = nodes.nuts
local getfield = nuts.getfield
local getlist = nuts.getlist
local getattr = nuts.getattr
local setattr = nuts.setattr
local setlist = nuts.setlist
local setlink = nuts.setlink
local getwidth = nuts.getwidth
local findtail = nuts.tail
local nexthlist = nuts.traversers.hlist
local getdimensions = nuts.dimensions
local copylist = nuts.copylist
local tracedrule = nodes.tracers.pool.nuts.rule
local nodepool = nuts.pool
local new_hlist = nodepool.hlist
local new_kern = nodepool.kern
local hlist_code <const> = nodes.nodecodes.hlist
local texsetattribute = tex.setattribute
local unsetvalue <const> = attributes.unsetvalue
local enableaction = nodes.tasks.enableaction
local min_threshold = 0
local max_threshold = 0
local function set(n)
enableaction("mvlbuilders", "typesetters.checkers.handler")
enableaction("vboxbuilders","typesetters.checkers.handler")
texsetattribute(a_justification,n or 1)
function typesetters.checkers.set(n)
texsetattribute(a_justification,n or 1)
end
end
local function reset()
texsetattribute(a_justification,unsetvalue)
end
checkers.set = set
checkers.reset = reset
interfaces.implement {
name = "showjustification",
actions = set
}
trackers.register("visualizers.justification", function(v)
if v then
set(1)
else
reset()
end
end)
function checkers.handler(head)
for current in nexthlist, head do
if getattr(current,a_justification) == 1 then
setattr(current,a_justification,0) -- kind of reset
local width = getwidth(current)
if width > 0 then
local list = getlist(current)
if list then
local naturalwidth, naturalheight, naturaldepth = getdimensions(list)
local delta = naturalwidth - width
if naturalwidth == 0 or delta == 0 then
-- special box
elseif delta >= max_threshold then
local rule = new_hlist(tracedrule(delta,naturalheight,naturaldepth,getfield(list,"glueset") == 1 and "trace:dr" or "trace:db"))
setlink(findtail(list),rule)
setlist(current,list)
elseif delta <= min_threshold then
local alignstate = getattr(list,a_alignstate)
if alignstate == 1 then
local rule = new_hlist(tracedrule(-delta,naturalheight,naturaldepth,"trace:dc"))
setlink(rule,list)
setlist(current,rule)
elseif alignstate == 2 then
local lrule = new_hlist(tracedrule(-delta/2,naturalheight,naturaldepth,"trace:dy"))
local rrule = copylist(lrule)
setlink(lrule,list)
setlink(findtail(list),new_kern(delta/2),rrule)
setlist(current,lrule)
elseif alignstate == 3 then
local rule = new_hlist(tracedrule(-delta,naturalheight,naturaldepth,"trace:dm"))
setlink(findtail(list),new_kern(delta),rule)
setlist(current,list)
else
local rule = new_hlist(tracedrule(-delta,naturalheight,naturaldepth,"trace:dg"))
setlink(findtail(list),new_kern(delta),rule)
setlist(current,list)
end
end
end
end
end
end
return head
end
| 412 | 0.965891 | 1 | 0.965891 | game-dev | MEDIA | 0.152168 | game-dev | 0.968573 | 1 | 0.968573 |
Aizistral-Studios/Enigmatic-Legacy | 2,127 | src/main/java/com/aizistral/enigmaticlegacy/enchantments/SlayerEnchantment.java | package com.aizistral.enigmaticlegacy.enchantments;
import static com.aizistral.enigmaticlegacy.objects.RegisteredMeleeAttack.getRegisteredAttackStregth;
import com.aizistral.enigmaticlegacy.EnigmaticLegacy;
import com.aizistral.enigmaticlegacy.config.OmniconfigHandler;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.monster.Monster;
import net.minecraft.world.item.AxeItem;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.enchantment.DamageEnchantment;
import net.minecraft.world.item.enchantment.Enchantment;
import net.minecraft.world.item.enchantment.EnchantmentCategory;
public class SlayerEnchantment extends Enchantment {
public SlayerEnchantment(EquipmentSlot... slots) {
super(Enchantment.Rarity.COMMON, EnchantmentCategory.WEAPON, slots);
}
@Override
public int getMinCost(int enchantmentLevel) {
return 5 + (enchantmentLevel - 1) * 8;
}
@Override
public int getMaxCost(int enchantmentLevel) {
return this.getMinCost(enchantmentLevel) + 20;
}
@Override
public int getMaxLevel() {
return 5;
}
@Override
public boolean canApplyAtEnchantingTable(ItemStack stack) {
return this.canEnchant(stack) && super.canApplyAtEnchantingTable(stack);
}
@Override
public boolean checkCompatibility(Enchantment ench) {
return !(ench instanceof DamageEnchantment) && super.checkCompatibility(ench);
}
@Override
public boolean canEnchant(ItemStack stack) {
return OmniconfigHandler.isItemEnabled(this) && (stack.getItem() instanceof AxeItem ? true : stack.canApplyAtEnchantingTable(this));
}
@Override
public boolean isAllowedOnBooks() {
return OmniconfigHandler.isItemEnabled(this);
}
@Override
public boolean isDiscoverable() {
return OmniconfigHandler.isItemEnabled(this);
}
public float bonusDamageByCreature(LivingEntity attacker, LivingEntity living, int level) {
float calculated = living instanceof Monster ? level * 1.5F : 0F;
calculated*= getRegisteredAttackStregth(attacker);
return calculated;
}
}
| 412 | 0.698892 | 1 | 0.698892 | game-dev | MEDIA | 0.99493 | game-dev | 0.743508 | 1 | 0.743508 |
Fr4nkFletcher/ESP32-Marauder-Cheap-Yellow-Display | 2,206 | ESP32-1732S019/libraries/ArduinoJson/src/ArduinoJson/Collection/CollectionData.hpp | // ArduinoJson - https://arduinojson.org
// Copyright © 2014-2023, Benoit BLANCHON
// MIT License
#pragma once
#include <ArduinoJson/Namespace.hpp>
#include <ArduinoJson/Polyfills/assert.hpp>
#include <stddef.h> // size_t
ARDUINOJSON_BEGIN_PRIVATE_NAMESPACE
class MemoryPool;
class VariantData;
class VariantSlot;
class CollectionData {
VariantSlot* head_;
VariantSlot* tail_;
public:
// Must be a POD!
// - no constructor
// - no destructor
// - no virtual
// - no inheritance
// Array only
VariantData* addElement(MemoryPool* pool);
VariantData* getElement(size_t index) const;
VariantData* getOrAddElement(size_t index, MemoryPool* pool);
void removeElement(size_t index);
// Object only
template <typename TAdaptedString>
VariantData* addMember(TAdaptedString key, MemoryPool* pool);
template <typename TAdaptedString>
VariantData* getMember(TAdaptedString key) const;
template <typename TAdaptedString>
VariantData* getOrAddMember(TAdaptedString key, MemoryPool* pool);
template <typename TAdaptedString>
void removeMember(TAdaptedString key) {
removeSlot(getSlot(key));
}
template <typename TAdaptedString>
bool containsKey(const TAdaptedString& key) const;
// Generic
void clear();
size_t memoryUsage() const;
size_t size() const;
VariantSlot* addSlot(MemoryPool*);
void removeSlot(VariantSlot* slot);
bool copyFrom(const CollectionData& src, MemoryPool* pool);
VariantSlot* head() const {
return head_;
}
void movePointers(ptrdiff_t stringDistance, ptrdiff_t variantDistance);
private:
VariantSlot* getSlot(size_t index) const;
template <typename TAdaptedString>
VariantSlot* getSlot(TAdaptedString key) const;
VariantSlot* getPreviousSlot(VariantSlot*) const;
};
inline const VariantData* collectionToVariant(
const CollectionData* collection) {
const void* data = collection; // prevent warning cast-align
return reinterpret_cast<const VariantData*>(data);
}
inline VariantData* collectionToVariant(CollectionData* collection) {
void* data = collection; // prevent warning cast-align
return reinterpret_cast<VariantData*>(data);
}
ARDUINOJSON_END_PRIVATE_NAMESPACE
| 412 | 0.942657 | 1 | 0.942657 | game-dev | MEDIA | 0.517535 | game-dev | 0.754723 | 1 | 0.754723 |
AionGermany/aion-germany | 8,875 | AL-Game/src/com/aionemu/gameserver/services/PunishmentService.java | /**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning 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.
*
* Aion-Lightning 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 Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.aionemu.gameserver.services;
import java.util.Calendar;
import java.util.concurrent.Future;
import com.aionemu.commons.database.dao.DAOManager;
import com.aionemu.gameserver.configs.main.GSConfig;
import com.aionemu.gameserver.dao.PlayerPunishmentsDAO;
import com.aionemu.gameserver.model.TaskId;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.network.aion.serverpackets.SM_CAPTCHA;
import com.aionemu.gameserver.network.aion.serverpackets.SM_QUIT_RESPONSE;
import com.aionemu.gameserver.network.aion.serverpackets.SM_SYSTEM_MESSAGE;
import com.aionemu.gameserver.network.chatserver.ChatServer;
import com.aionemu.gameserver.services.teleport.TeleportService2;
import com.aionemu.gameserver.utils.PacketSendUtility;
import com.aionemu.gameserver.utils.ThreadPoolManager;
import com.aionemu.gameserver.world.World;
import com.aionemu.gameserver.world.WorldMapType;
/**
* @author lord_rex, Cura, nrg
*/
public class PunishmentService {
/**
* This method will handle unbanning a character
*
* @param player
* @param state
* @param delayInMinutes
*/
public static void unbanChar(int playerId) {
DAOManager.getDAO(PlayerPunishmentsDAO.class).unpunishPlayer(playerId, PunishmentType.CHARBAN);
}
/**
* This method will handle banning a character
*
* @param player
* @param state
* @param delayInMinutes
*/
public static void banChar(int playerId, int dayCount, String reason) {
DAOManager.getDAO(PlayerPunishmentsDAO.class).punishPlayer(playerId, PunishmentType.CHARBAN, calculateDuration(dayCount), reason);
// if player is online - kick him
Player player = World.getInstance().findPlayer(playerId);
if (player != null) {
player.getClientConnection().close(new SM_QUIT_RESPONSE(), false);
}
}
/**
* Calculates the timestamp when a given number of days is over
*
* @param dayCount
* @return timeStamp
*/
public static long calculateDuration(int dayCount) {
if (dayCount == 0) {
return Integer.MAX_VALUE; // int because client handles this with seconds timestamp in int
}
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, +dayCount);
return ((cal.getTimeInMillis() - System.currentTimeMillis()) / 1000);
}
/**
* This method will handle moving or removing a player from prison
*
* @param player
* @param state
* @param delayInMinutes
*/
public static void setIsInPrison(Player player, boolean state, long delayInMinutes, String reason) {
stopPrisonTask(player, false);
if (state) {
long prisonTimer = player.getPrisonTimer();
if (delayInMinutes > 0) {
prisonTimer = delayInMinutes * 60000L;
schedulePrisonTask(player, prisonTimer);
PacketSendUtility.sendMessage(player, "You have been teleported to prison for a time of " + delayInMinutes + " minutes.\n If you disconnect the time stops and the timer of the prison'll see at your next login.");
}
if (GSConfig.ENABLE_CHAT_SERVER) {
ChatServer.getInstance().sendPlayerLogout(player);
}
player.setStartPrison(System.currentTimeMillis());
TeleportService2.teleportToPrison(player);
DAOManager.getDAO(PlayerPunishmentsDAO.class).punishPlayer(player, PunishmentType.PRISON, reason);
}
else {
PacketSendUtility.sendMessage(player, "You come out of prison.");
if (GSConfig.ENABLE_CHAT_SERVER) {
PacketSendUtility.sendMessage(player, "To use global chats again relog!");
}
player.setPrisonTimer(0);
TeleportService2.moveToBindLocation(player, true);
DAOManager.getDAO(PlayerPunishmentsDAO.class).unpunishPlayer(player.getObjectId(), PunishmentType.PRISON);
}
}
/**
* This method will stop the prison task
*
* @param playerObjId
*/
public static void stopPrisonTask(Player player, boolean save) {
Future<?> prisonTask = player.getController().getTask(TaskId.PRISON);
if (prisonTask != null) {
if (save) {
long delay = player.getPrisonTimer();
if (delay < 0) {
delay = 0;
}
player.setPrisonTimer(delay);
}
player.getController().cancelTask(TaskId.PRISON);
}
}
/**
* This method will update the prison status
*
* @param player
*/
public static void updatePrisonStatus(final Player player) {
if (player.isInPrison()) {
long prisonTimer = player.getPrisonTimer();
if (prisonTimer > 0) {
schedulePrisonTask(player, prisonTimer);
int timeInPrison = (int) (prisonTimer / 60000);
if (timeInPrison <= 0) {
timeInPrison = 1;
}
PacketSendUtility.sendMessage(player, "You are still in prison for " + timeInPrison + " minute" + (timeInPrison > 1 ? "s" : "") + ".");
player.setStartPrison(System.currentTimeMillis());
}
if (player.getWorldId() != WorldMapType.DF_PRISON.getId() && player.getWorldId() != WorldMapType.LF_PRISON.getId()) {
PacketSendUtility.sendMessage(player, "You will be teleported to prison in one minute!");
ThreadPoolManager.getInstance().schedule(new Runnable() {
@Override
public void run() {
TeleportService2.teleportToPrison(player);
}
}, 60000);
}
}
}
/**
* This method will schedule a prison task
*
* @param player
* @param prisonTimer
*/
private static void schedulePrisonTask(final Player player, long prisonTimer) {
player.setPrisonTimer(prisonTimer);
player.getController().addTask(TaskId.PRISON, ThreadPoolManager.getInstance().schedule(new Runnable() {
@Override
public void run() {
setIsInPrison(player, false, 0, "");
}
}, prisonTimer));
}
/**
* This method will handle can or cant gathering
*
* @param player
* @param captchaCount
* @param state
* @param delay
* @author Cura
*/
public static void setIsNotGatherable(Player player, int captchaCount, boolean state, long delay) {
stopGatherableTask(player, false);
if (state) {
if (captchaCount < 3) {
PacketSendUtility.sendPacket(player, new SM_CAPTCHA(captchaCount + 1, player.getCaptchaImage()));
}
else {
player.setCaptchaWord(null);
player.setCaptchaImage(null);
}
player.setGatherableTimer(delay);
player.setStopGatherable(System.currentTimeMillis());
scheduleGatherableTask(player, delay);
DAOManager.getDAO(PlayerPunishmentsDAO.class).punishPlayer(player, PunishmentType.GATHER, "Possible gatherbot");
}
else {
PacketSendUtility.sendPacket(player, new SM_SYSTEM_MESSAGE(1400269));
player.setCaptchaWord(null);
player.setCaptchaImage(null);
player.setGatherableTimer(0);
player.setStopGatherable(0);
DAOManager.getDAO(PlayerPunishmentsDAO.class).unpunishPlayer(player.getObjectId(), PunishmentType.GATHER);
}
}
/**
* This method will stop the gathering task
*
* @param player
* @param save
* @author Cura
*/
public static void stopGatherableTask(Player player, boolean save) {
Future<?> gatherableTask = player.getController().getTask(TaskId.GATHERABLE);
if (gatherableTask != null) {
if (save) {
long delay = player.getGatherableTimer();
if (delay < 0) {
delay = 0;
}
player.setGatherableTimer(delay);
}
player.getController().cancelTask(TaskId.GATHERABLE);
}
}
/**
* This method will update the gathering status
*
* @param player
* @author Cura
*/
public static void updateGatherableStatus(Player player) {
if (player.isNotGatherable()) {
long gatherableTimer = player.getGatherableTimer();
if (gatherableTimer > 0) {
scheduleGatherableTask(player, gatherableTimer);
player.setStopGatherable(System.currentTimeMillis());
}
}
}
/**
* This method will schedule a gathering task
*
* @param player
* @param gatherableTimer
* @author Cura
*/
private static void scheduleGatherableTask(final Player player, long gatherableTimer) {
player.setGatherableTimer(gatherableTimer);
player.getController().addTask(TaskId.GATHERABLE, ThreadPoolManager.getInstance().schedule(new Runnable() {
@Override
public void run() {
setIsNotGatherable(player, 0, false, 0);
}
}, gatherableTimer));
}
/**
* PunishmentType
*
* @author Cura
*/
public enum PunishmentType {
PRISON,
GATHER,
CHARBAN
}
}
| 412 | 0.757232 | 1 | 0.757232 | game-dev | MEDIA | 0.387324 | game-dev | 0.774064 | 1 | 0.774064 |
google/google-ctf | 1,565 | 2024/hackceler8/rounds/round_1/server/game/engine/venatizer.py | # Copyright 2024 Google LLC
#
# 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
#
# https://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.
import logging
from game.components.wall import Wall
class FakeSize:
def __init__(self, width, height):
self.width = width
self.height = height
class FakeCoord:
def __init__(self, x, y):
self.x = x
self.y = y
class Venatizer:
def __init__(self, game):
self.game = game
self.map = self.game.tiled_map
self.max_x = self.map.size.width
self.max_y = self.map.size.height
self.counter = 0
# How many tiles per second are being nuked
self.advancement_speed = 5
self.wall_width = self.map.tile_size.width
def tick(self):
w = Wall(
coords=FakeCoord(self.counter // self.advancement_speed * self.wall_width,
10000),
x1=self.counter // self.advancement_speed * self.wall_width,
x2=self.counter // self.advancement_speed * self.wall_width + self.wall_width,
y1=0,
y2=10000,
name="killawall")
self.game.objects.append(w)
self.counter += 1
return
| 412 | 0.583997 | 1 | 0.583997 | game-dev | MEDIA | 0.693818 | game-dev | 0.541697 | 1 | 0.541697 |
basiclab/TTSG | 2,605 | safebench/scenario/scenario_data/scenic_data/scenario_5/behavior_1_opt.scenic | '''The ego is driving straight through an intersection when a crossing vehicle runs the red light and unexpectedly accelerates, forcing the ego to quickly reassess the situation and perform a collision avoidance maneuver.
'''
Town = globalParameters.town
EgoSpawnPt = globalParameters.spawnPt
yaw = globalParameters.yaw
lanePts = globalParameters.lanePts
egoTrajectory = PolylineRegion(globalParameters.waypoints)
param map = localPath(f'../maps/{Town}.xodr')
param carla_map = Town
model scenic.simulators.carla.model
EGO_MODEL = "vehicle.lincoln.mkz_2017"
## MONITORS
monitor TrafficLights:
freezeTrafficLights()
while True:
if withinDistanceToTrafficLight(ego, 100):
setClosestTrafficLightStatus(ego, "green")
if withinDistanceToTrafficLight(AdvAgent, 100):
setClosestTrafficLightStatus(AdvAgent, "red")
wait
behavior AdvBehavior():
while (distance to self) > 60:
wait
do FollowTrajectoryBehavior(globalParameters.OPT_ADV_SPEED, advTrajectory) until (distance to self) < globalParameters.OPT_ADV_DISTANCE or (distance from self to egoTrajectory) < globalParameters.OPT_STOP_DISTANCE
while (distance from self to egoTrajectory) > globalParameters.OPT_STOP_DISTANCE:
take SetThrottleAction(globalParameters.OPT_THROTTLE)
while True:
take SetSpeedAction(0)
param OPT_GEO_Y_DISTANCE = Range(-5, 10)
param OPT_ADV_SPEED = Range(5, 15)
param OPT_ADV_DISTANCE = Range(0, 20)
param OPT_THROTTLE = Range(0.5, 1)
param OPT_STOP_DISTANCE = Range(0, 2)
egoInitLane = network.laneAt(lanePts[0])
egoManeuver = Uniform(*filter(lambda m: m.type is ManeuverType.STRAIGHT, egoInitLane.maneuvers))
advManeuvers = filter(lambda i: i.type == ManeuverType.STRAIGHT, egoManeuver.conflictingManeuvers)
if len(advManeuvers.sample()):
advManeuver = Uniform(*advManeuvers)
else:
# route 6 has some problems
advManeuver = egoManeuver.conflictingManeuvers[0]
advTrajectory = [advManeuver.startLane, advManeuver.connectingLane, advManeuver.endLane]
IntSpawnPt = advManeuver.connectingLane.centerline.start
ego = Car at EgoSpawnPt,
with heading yaw,
with regionContainedIn None,
with blueprint EGO_MODEL
AdvAgent = Car following roadDirection from IntSpawnPt for globalParameters.OPT_GEO_Y_DISTANCE,
with heading IntSpawnPt.heading,
with regionContainedIn None,
with behavior AdvBehavior()
require -160 deg <= RelativeHeading(AdvAgent) <= -20 deg
require any([AdvAgent.position in traj for traj in [advManeuver.startLane, advManeuver.connectingLane, advManeuver.endLane]]) | 412 | 0.888139 | 1 | 0.888139 | game-dev | MEDIA | 0.482705 | game-dev | 0.965553 | 1 | 0.965553 |
Rouesvm/Backpacks-Polymer | 4,859 | src/main/java/com/rouesvm/servback/compat/trinkets/BackpackTrinket.java | package com.rouesvm.servback.compat.trinkets;
import com.rouesvm.servback.content.component.UpgradeContainerComponent;
import com.rouesvm.servback.content.item.BundleGuiItem;
import com.rouesvm.servback.registry.BackpackDataComponentTypes;
import com.rouesvm.servback.technical.config.Configuration;
import com.rouesvm.servback.technical.cosmetic.BackHolder;
import com.rouesvm.servback.technical.cosmetic.CosmeticManager;
import com.rouesvm.servback.technical.manager.BackpackManager;
import com.rouesvm.servback.technical.manager.BackpackUUID;
import dev.emi.trinkets.api.*;
import net.fabricmc.fabric.api.event.player.UseBlockCallback;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemPlacementContext;
import net.minecraft.item.ItemStack;
import net.minecraft.registry.Registries;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.world.World;
import java.util.UUID;
public class BackpackTrinket implements Trinket {
public static void initialize() {
UseBlockCallback.EVENT.register(BackpackTrinket::tryPlaceBackpack);
Registries.ITEM.stream()
.filter(item -> item instanceof BundleGuiItem)
.forEach(item -> TrinketsApi.registerTrinket(item, new BackpackTrinket()));
}
@Override
public void tick(ItemStack stack, SlotReference slot, LivingEntity entity) {
if (!Configuration.instance().display_back) return;
if (entity instanceof ServerPlayerEntity player) {
CosmeticManager manager = CosmeticManager.manager();
if (!manager.hasInstance(player)) manager.getOrCreateInstance(player, stack);
UUID uuid = BackpackUUID.getStackUUID(stack);
if (uuid == null) return;
UpgradeContainerComponent component = stack.get(BackpackDataComponentTypes.UPGRADE_CONTAINER);
if (component != null) component.getBaseUpgrades().forEach((upgrade) ->
upgrade.tick(player.getEntityWorld(), player.getEntityPos(), BackpackManager.getInventory(uuid))
);
}
}
@Override
public void onEquip(ItemStack stack, SlotReference slot, LivingEntity entity) {
if (!Configuration.instance().display_back) return;
if (entity instanceof ServerPlayerEntity player) {
CosmeticManager.manager().getOrCreateInstance(player, stack);
}
}
@Override
public void onUnequip(ItemStack stack, SlotReference slot, LivingEntity entity) {
if (!Configuration.instance().display_back) return;
if (entity instanceof ServerPlayerEntity player) {
CosmeticManager manager = CosmeticManager.manager();
BackHolder holder = manager.getOrCreateInstance(player, stack);
holder.destroy();
manager.removeInstance(player);
}
}
public static ActionResult tryPlaceBackpack(PlayerEntity player, World world, Hand hand, BlockHitResult blockHitResult) {
if (!world.isClient()) {
if (!Configuration.instance().placeable) return ActionResult.PASS;
ItemStack stack = getStackInBackSlot(player);
if (!stack.isEmpty()
&& player.isSneaking()
&& player.getMainHandStack().isEmpty()
&& player.getOffHandStack().isEmpty())
{
BundleGuiItem item = (BundleGuiItem) stack.getItem();
ItemPlacementContext context = new ItemPlacementContext(player, hand, stack, blockHitResult);
item.place(context);
return ActionResult.SUCCESS;
}
}
return ActionResult.PASS;
}
public static void equipStack(PlayerEntity player, ItemStack stack) {
TrinketItem.equipItem(player, stack);
}
public static boolean isBackSlotOccupied(PlayerEntity player) {
return !getStackInBackSlot(player).isEmpty();
}
private static ItemStack getStackInBackSlot(PlayerEntity player) {
return TrinketsApi.getTrinketComponent(player)
.map(BackpackTrinket::findBundleItem)
.orElse(ItemStack.EMPTY);
}
private static ItemStack findBundleItem(TrinketComponent component) {
for (var group : component.getInventory().values()) {
for (var inv : group.values()) {
for (int i = 0; i < inv.size(); i++) {
ItemStack stack = inv.getStack(i);
if (!stack.isEmpty() && stack.getItem() instanceof BundleGuiItem) {
return stack;
}
}
}
}
return ItemStack.EMPTY;
}
}
| 412 | 0.954206 | 1 | 0.954206 | game-dev | MEDIA | 0.996621 | game-dev | 0.975288 | 1 | 0.975288 |
StranikS-Scan/WorldOfTanks-Decompiled | 7,244 | source/res/scripts/client/gui/game_control/gift_system_controller.py | # Python bytecode 2.7 (decompiled from Python 2.7)
# Embedded file name: scripts/client/gui/game_control/gift_system_controller.py
import typing
from bootcamp.BootCampEvents import g_bootcampEvents
from constants import Configs
from Event import Event, EventManager
from gifts.gifts_common import ClientReqStrategy
from gui.ClientUpdateManager import g_clientUpdateManager
from gui.gift_system.hubs import createGiftEventHub
from gui.gift_system.hubs.base.hub_core import IGiftEventHub
from gui.gift_system.requesters.history_requester import GiftSystemHistoryRequester
from gui.gift_system.requesters.state_requester import GiftSystemWebStateRequester
from gui.gift_system.wrappers import skipNoHubsAction
from helpers import dependency
from helpers.server_settings import GiftSystemConfig
from skeletons.gui.game_control import IGiftSystemController
from skeletons.gui.lobby_context import ILobbyContext
from skeletons.gui.shared import IItemsCache
if typing.TYPE_CHECKING:
from gui.gift_system.wrappers import GiftsHistoryData, GiftsWebState
from gui.shared import events
from helpers.server_settings import ServerSettings, GiftEventConfig
class GiftSystemController(IGiftSystemController):
__itemsCache = dependency.descriptor(IItemsCache)
__lobbyContext = dependency.descriptor(ILobbyContext)
def __init__(self):
self.__em = EventManager()
self.onEventHubsCreated = Event(self.__em)
self.onEventHubsDestroyed = Event(self.__em)
self.__isLobbyInited = False
self.__serverSettings = None
self.__giftSystemSettings = None
self.__eventHubs = {}
self.__historyRequester = GiftSystemHistoryRequester(self.__onHistoryReceived)
self.__webStateRequester = GiftSystemWebStateRequester(self.__onWebStateReceived)
return
def init(self):
super(GiftSystemController, self).init()
g_bootcampEvents.onBootcampFinished += self.__onBootcampFinished
def fini(self):
g_bootcampEvents.onBootcampFinished -= self.__onBootcampFinished
self.__historyRequester.destroy()
self.__webStateRequester.destroy()
self.__em.clear()
def onAccountBecomePlayer(self):
self.__onServerSettingsChanged(self.__lobbyContext.getServerSettings())
def onAccountBecomeNonPlayer(self):
self.__clear()
def onDisconnected(self):
self.__clear()
if self.__serverSettings is not None:
self.__serverSettings.onServerSettingsChange -= self.__onGiftSettingsChanged
self.__destroyEventHubs(set(self.__eventHubs.keys()), onDisconnect=True)
self.__serverSettings = self.__giftSystemSettings = None
return
def onLobbyInited(self, event=None):
self.__updateLobbyState(isLobbyInited=True)
self.__onWebStateReadyChanged(strategy=ClientReqStrategy.AUTO)
self.__onHistoryReadyChanged(self.__itemsCache.items.giftSystem.isHistoryReady)
self.__updateReadyListening()
def getEventHub(self, eventID):
return self.__eventHubs.get(eventID)
def getSettings(self):
return self.__giftSystemSettings
def requestWebState(self, eventID):
if eventID not in self.__eventHubs:
return
self.__onWebStateReadyChanged(strategy=ClientReqStrategy.DEMAND, eventIDs=[eventID])
def __clear(self):
self.__updateLobbyState(isLobbyInited=False)
self.__webStateRequester.stop()
self.__historyRequester.stop()
g_clientUpdateManager.removeObjectCallbacks(self)
def __onBootcampFinished(self):
for eventHub in self.__eventHubs.itervalues():
eventHub.reset()
def __onGiftSettingsChanged(self, diff):
if Configs.GIFTS_CONFIG.value in diff:
self.__updateGiftSettings()
def __onHistoryReadyChanged(self, isHistoryReady):
if not isHistoryReady:
return
reqEventIDs = set((eID for eID, eHub in self.__eventHubs.iteritems() if eHub.isHistoryRequired()))
self.__historyRequester.request(reqEventIDs)
def __onHistoryReceived(self, history):
for eventID, eventHub in ((eID, eHub) for eID, eHub in self.__eventHubs.iteritems() if eID in history):
eventHub.processHistory(history[eventID])
self.__onWebStateReadyChanged(strategy=ClientReqStrategy.AUTO)
def __onWebStateReadyChanged(self, strategy, eventIDs=None):
eventIDs = eventIDs or self.__eventHubs.keys()
reqEventIDs = set((eID for eID in eventIDs if self.__eventHubs[eID].isWebStateRequired(strategy)))
self.__webStateRequester.request(reqEventIDs)
def __onWebStateReceived(self, webState):
for eventID, eventHub in ((eID, eHub) for eID, eHub in self.__eventHubs.iteritems() if eID in webState):
eventHub.processWebState(webState[eventID])
def __onServerSettingsChanged(self, serverSettings):
if self.__serverSettings is not None:
self.__serverSettings.onServerSettingsChange -= self.__onGiftSettingsChanged
self.__serverSettings = serverSettings
self.__serverSettings.onServerSettingsChange += self.__onGiftSettingsChanged
self.__updateGiftSettings()
return
@skipNoHubsAction
def __createEventHubs(self, hubsToCreate, eventsSettings):
for eventID in hubsToCreate:
self.__eventHubs[eventID] = createGiftEventHub(eventID, eventsSettings[eventID], self.__isLobbyInited)
self.onEventHubsCreated(hubsToCreate)
@skipNoHubsAction
def __destroyEventHubs(self, hubsToDestroy, onDisconnect=False):
if not onDisconnect:
self.onEventHubsDestroyed(hubsToDestroy)
for eventID in hubsToDestroy:
self.__eventHubs[eventID].destroy()
del self.__eventHubs[eventID]
@skipNoHubsAction
def __updateEventHubs(self, hubsToUpdate, eventsSettings):
for eventID in hubsToUpdate:
self.__eventHubs[eventID].updateSettings(eventsSettings[eventID])
def __updateEventHubsSettings(self, prevSettings, newSettings):
prevEvents, newEvents = prevSettings.events, newSettings.events
prevEventsIDs, newEventsIDs = set(prevEvents.keys()), set(newEvents.keys())
self.__destroyEventHubs(prevEventsIDs - newEventsIDs)
self.__updateEventHubs(prevEventsIDs & newEventsIDs, newEvents)
self.__createEventHubs(newEventsIDs - prevEventsIDs, newEvents)
def __updateGiftSettings(self):
prevSettings = self.__giftSystemSettings or GiftSystemConfig()
self.__giftSystemSettings = self.__serverSettings.giftSystemConfig
self.__updateEventHubsSettings(prevSettings, self.__giftSystemSettings)
def __updateLobbyState(self, isLobbyInited=False):
self.__isLobbyInited = isLobbyInited
for eventHub in self.__eventHubs.itervalues():
eventHub.getMessenger().setMessagesAllowed(isLobbyInited)
def __updateReadyListening(self):
g_clientUpdateManager.removeObjectCallbacks(self)
if [ eventHub for eventHub in self.__eventHubs.itervalues() if eventHub.isHistoryRequired() ]:
g_clientUpdateManager.addCallbacks({'cache.giftsData.isReady': self.__onHistoryReadyChanged})
| 412 | 0.535159 | 1 | 0.535159 | game-dev | MEDIA | 0.418303 | game-dev,desktop-app | 0.770904 | 1 | 0.770904 |
OpenGLInsights/OpenGLInsightsCode | 5,713 | Chapter 07 Procedural Textures in GLSL/demo2/tiles.frag | #version 120
// Cellular noise ("Worley noise") in 3D in GLSL.
// Copyright (c) Stefan Gustavson 2011-04-19. All rights reserved.
// This code is released under the conditions of the MIT license.
// See LICENSE file for details.
// Permutation polynomial: (34x^2 + x) mod 289
vec3 permute(vec3 x) {
return mod((34.0 * x + 1.0) * x, 289.0);
}
// Cellular noise, returning F1 and F2 in a vec2.
// 3x3x3 search region for good F2 everywhere, but a lot
// slower than the 2x2x2 version.
// The code below is a bit scary even to its author,
// but it has at least half decent performance on a
// modern GPU. In any case, it beats any software
// implementation of Worley noise hands down.
vec2 cellular(vec3 P) {
#define K 0.142857142857 // 1/7
#define Ko 0.428571428571 // 1/2-K/2
#define K2 0.020408163265306 // 1/(7*7)
#define Kz 0.166666666667 // 1/6
#define Kzo 0.416666666667 // 1/2-1/6*2
#define jitter 1.0 // smaller jitter gives more regular pattern
vec3 Pi = mod(floor(P), 289.0);
vec3 Pf = fract(P) - 0.5;
vec3 Pfx = Pf.x + vec3(1.0, 0.0, -1.0);
vec3 Pfy = Pf.y + vec3(1.0, 0.0, -1.0);
vec3 Pfz = Pf.z + vec3(1.0, 0.0, -1.0);
vec3 p = permute(Pi.x + vec3(-1.0, 0.0, 1.0));
vec3 p1 = permute(p + Pi.y - 1.0);
vec3 p2 = permute(p + Pi.y);
vec3 p3 = permute(p + Pi.y + 1.0);
vec3 p11 = permute(p1 + Pi.z - 1.0);
vec3 p12 = permute(p1 + Pi.z);
vec3 p13 = permute(p1 + Pi.z + 1.0);
vec3 p21 = permute(p2 + Pi.z - 1.0);
vec3 p22 = permute(p2 + Pi.z);
vec3 p23 = permute(p2 + Pi.z + 1.0);
vec3 p31 = permute(p3 + Pi.z - 1.0);
vec3 p32 = permute(p3 + Pi.z);
vec3 p33 = permute(p3 + Pi.z + 1.0);
vec3 ox11 = fract(p11*K) - Ko;
vec3 oy11 = mod(floor(p11*K), 7.0)*K - Ko;
vec3 oz11 = floor(p11*K2)*Kz - Kzo; // p11 < 289 guaranteed
vec3 ox12 = fract(p12*K) - Ko;
vec3 oy12 = mod(floor(p12*K), 7.0)*K - Ko;
vec3 oz12 = floor(p12*K2)*Kz - Kzo;
vec3 ox13 = fract(p13*K) - Ko;
vec3 oy13 = mod(floor(p13*K), 7.0)*K - Ko;
vec3 oz13 = floor(p13*K2)*Kz - Kzo;
vec3 ox21 = fract(p21*K) - Ko;
vec3 oy21 = mod(floor(p21*K), 7.0)*K - Ko;
vec3 oz21 = floor(p21*K2)*Kz - Kzo;
vec3 ox22 = fract(p22*K) - Ko;
vec3 oy22 = mod(floor(p22*K), 7.0)*K - Ko;
vec3 oz22 = floor(p22*K2)*Kz - Kzo;
vec3 ox23 = fract(p23*K) - Ko;
vec3 oy23 = mod(floor(p23*K), 7.0)*K - Ko;
vec3 oz23 = floor(p23*K2)*Kz - Kzo;
vec3 ox31 = fract(p31*K) - Ko;
vec3 oy31 = mod(floor(p31*K), 7.0)*K - Ko;
vec3 oz31 = floor(p31*K2)*Kz - Kzo;
vec3 ox32 = fract(p32*K) - Ko;
vec3 oy32 = mod(floor(p32*K), 7.0)*K - Ko;
vec3 oz32 = floor(p32*K2)*Kz - Kzo;
vec3 ox33 = fract(p33*K) - Ko;
vec3 oy33 = mod(floor(p33*K), 7.0)*K - Ko;
vec3 oz33 = floor(p33*K2)*Kz - Kzo;
vec3 dx11 = Pfx + jitter*ox11;
vec3 dy11 = Pfy.x + jitter*oy11;
vec3 dz11 = Pfz.x + jitter*oz11;
vec3 dx12 = Pfx + jitter*ox12;
vec3 dy12 = Pfy.x + jitter*oy12;
vec3 dz12 = Pfz.y + jitter*oz12;
vec3 dx13 = Pfx + jitter*ox13;
vec3 dy13 = Pfy.x + jitter*oy13;
vec3 dz13 = Pfz.z + jitter*oz13;
vec3 dx21 = Pfx + jitter*ox21;
vec3 dy21 = Pfy.y + jitter*oy21;
vec3 dz21 = Pfz.x + jitter*oz21;
vec3 dx22 = Pfx + jitter*ox22;
vec3 dy22 = Pfy.y + jitter*oy22;
vec3 dz22 = Pfz.y + jitter*oz22;
vec3 dx23 = Pfx + jitter*ox23;
vec3 dy23 = Pfy.y + jitter*oy23;
vec3 dz23 = Pfz.z + jitter*oz23;
vec3 dx31 = Pfx + jitter*ox31;
vec3 dy31 = Pfy.z + jitter*oy31;
vec3 dz31 = Pfz.x + jitter*oz31;
vec3 dx32 = Pfx + jitter*ox32;
vec3 dy32 = Pfy.z + jitter*oy32;
vec3 dz32 = Pfz.y + jitter*oz32;
vec3 dx33 = Pfx + jitter*ox33;
vec3 dy33 = Pfy.z + jitter*oy33;
vec3 dz33 = Pfz.z + jitter*oz33;
vec3 d11 = dx11 * dx11 + dy11 * dy11 + dz11 * dz11;
vec3 d12 = dx12 * dx12 + dy12 * dy12 + dz12 * dz12;
vec3 d13 = dx13 * dx13 + dy13 * dy13 + dz13 * dz13;
vec3 d21 = dx21 * dx21 + dy21 * dy21 + dz21 * dz21;
vec3 d22 = dx22 * dx22 + dy22 * dy22 + dz22 * dz22;
vec3 d23 = dx23 * dx23 + dy23 * dy23 + dz23 * dz23;
vec3 d31 = dx31 * dx31 + dy31 * dy31 + dz31 * dz31;
vec3 d32 = dx32 * dx32 + dy32 * dy32 + dz32 * dz32;
vec3 d33 = dx33 * dx33 + dy33 * dy33 + dz33 * dz33;
// Sort out the two smallest distances (F1, F2)
#if 0
// Cheat and sort out only F1
vec3 d1 = min(min(d11,d12), d13);
vec3 d2 = min(min(d21,d22), d23);
vec3 d3 = min(min(d31,d32), d33);
vec3 d = min(min(d1,d2), d3);
d.x = min(min(d.x,d.y),d.z);
return sqrt(d.xx); // F1 duplicated, no F2 computed
#else
// Do it right and sort out both F1 and F2
vec3 d1a = min(d11, d12);
d12 = max(d11, d12);
d11 = min(d1a, d13); // Smallest now not in d12 or d13
d13 = max(d1a, d13);
d12 = min(d12, d13); // 2nd smallest now not in d13
vec3 d2a = min(d21, d22);
d22 = max(d21, d22);
d21 = min(d2a, d23); // Smallest now not in d22 or d23
d23 = max(d2a, d23);
d22 = min(d22, d23); // 2nd smallest now not in d23
vec3 d3a = min(d31, d32);
d32 = max(d31, d32);
d31 = min(d3a, d33); // Smallest now not in d32 or d33
d33 = max(d3a, d33);
d32 = min(d32, d33); // 2nd smallest now not in d33
vec3 da = min(d11, d21);
d21 = max(d11, d21);
d11 = min(da, d31); // Smallest now in d11
d31 = max(da, d31); // 2nd smallest now not in d31
d11.xy = (d11.x < d11.y) ? d11.xy : d11.yx;
d11.xz = (d11.x < d11.z) ? d11.xz : d11.zx; // d11.x now smallest
d12 = min(d12, d21); // 2nd smallest now not in d21
d12 = min(d12, d22); // nor in d22
d12 = min(d12, d31); // nor in d31
d12 = min(d12, d32); // nor in d32
d11.yz = min(d11.yz,d12.xy); // nor in d12.yz
d11.y = min(d11.y,d12.z); // Only two more to go
d11.y = min(d11.y,d11.z); // Done! (Phew!)
return sqrt(d11.xy); // F1, F2
#endif
}
varying vec3 vTexCoord3D;
void main(void) {
vec2 F = cellular(vTexCoord3D.xyz);
float n = 0.1+F.y-F.x;
gl_FragColor = vec4(n*0.6, n*1.1, n*0.5, 1.0);
}
| 412 | 0.649573 | 1 | 0.649573 | game-dev | MEDIA | 0.484981 | game-dev,graphics-rendering | 0.978082 | 1 | 0.978082 |
BigheadSMZ/Zelda-LA-DX-HD-Updated | 6,112 | ladxhd_game_source_code/InGame/GameObjects/Things/ObjPullLever.cs | using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using ProjectZ.InGame.GameObjects.Base;
using ProjectZ.InGame.GameObjects.Base.CObjects;
using ProjectZ.InGame.GameObjects.Base.Components;
using ProjectZ.InGame.Map;
using ProjectZ.InGame.SaveLoad;
using ProjectZ.InGame.Things;
namespace ProjectZ.InGame.GameObjects.Things
{
internal class ObjPullLever : GameObject
{
private readonly DictAtlasEntry _dictLever;
private readonly DictAtlasEntry _dictLeverTop;
// currently only supports one lever per map
public static float LeverState;
private CPosition _position;
private Rectangle _field;
private Point _startPosition;
private string _openStrKey;
private const int MinLeverLength = 4;
private const int MaxLeverLength = 47;
private const float PullSpeed = 0.24f;
private readonly float RetractingSpeed;
private const float OpenSpeed = 0.25f;
private float _length = MinLeverLength; // 4 - 47
private bool _isOpening;
private bool _isGrabbed;
private bool _wasPulled;
public ObjPullLever() : base("pull_lever") { }
public ObjPullLever(Map.Map map, int posX, int posY, float retractingSpeed, string openStrKey) : base(map)
{
_startPosition = new Point(posX + 8, posY);
_position = new CPosition(posX + 8, posY + _length + 16, 0);
//EntitySize = new Rectangle(-8, -56, 16, 56);
RetractingSpeed = retractingSpeed;
_openStrKey = openStrKey;
LeverState = 1;
_field = map.GetField(posX, posY, 12);
_dictLever = Resources.GetSprite("pull_lever");
_dictLeverTop = Resources.GetSprite("pull_lever_top");
var collisionBox = new CBox(_position, -2, -56, 0, 4, 54, 8);
if (!string.IsNullOrEmpty(_openStrKey))
AddComponent(KeyChangeListenerComponent.Index, new KeyChangeListenerComponent(OnKeyChange));
AddComponent(CarriableComponent.Index, new CarriableComponent(
new CRectangle(_position, new Rectangle(-3, -4, 6, 2)), null, null, null)
{ StartGrabbing = StartGrabbing, Pull = OnPull });
AddComponent(CollisionComponent.Index, new BoxCollisionComponent(collisionBox, Values.CollisionTypes.Normal));
AddComponent(UpdateComponent.Index, new UpdateComponent(Update));
AddComponent(DrawComponent.Index, new DrawComponent(Draw, Values.LayerBottom, _position));
}
private void OnKeyChange()
{
var openState = Game1.GameManager.SaveManager.GetString(_openStrKey, "0");
if (openState == "1")
{
_isOpening = true;
Game1.GameManager.SaveManager.SetString(_openStrKey, "0");
}
}
private void StartGrabbing()
{
if (MapManager.ObjLink.Direction != 1)
return;
UpdatePlayerPosition();
}
private bool OnPull(Vector2 direction)
{
if (MapManager.ObjLink.Direction != 1)
return false;
_isGrabbed = true;
// Rather than check both values, just check Y and zero out X.
if (direction.Y < 0)
return true;
else
direction = new Vector2(0, direction.Y);
// play soundeffect on pull
if (!_wasPulled && direction.Y > 0)
Game1.GameManager.PlaySoundEffect("D378-17-11");
_wasPulled = direction.Y > 0;
_position.Move(direction * PullSpeed);
_length = _position.Y - 16 - _startPosition.Y;
if (_length > MaxLeverLength)
{
_length = MaxLeverLength;
_position.Set(new Vector2(_startPosition.X, _startPosition.Y + 16 + _length));
}
UpdateLeverState(direction.Y * (PullSpeed + 0.01f) * Game1.TimeMultiplier);
UpdatePlayerPosition();
// this is used to not continuously play the pull animation
if (_length == MaxLeverLength)
return false;
return true;
}
private void UpdatePlayerPosition()
{
// set the position of the player
MapManager.ObjLink.EntityPosition.Set(new Vector2(
_position.X, _position.Y + MapManager.ObjLink.BodyRectangle.Height - 2));
}
private void UpdateLeverState(float offset)
{
LeverState += offset / (MaxLeverLength - MinLeverLength);
LeverState = Math.Clamp(LeverState, 0, 1);
}
private void Update()
{
var insideRoom = _field.Contains(MapManager.ObjLink.EntityPosition.Position);
if (insideRoom)
_isOpening = false;
if (_isOpening)
UpdateLeverState(OpenSpeed * Game1.TimeMultiplier);
else if (!_isGrabbed && insideRoom)
UpdateLeverState(-RetractingSpeed * Game1.TimeMultiplier);
// move the lever back to the starting position
if (!_isGrabbed)
{
_position.Move(new Vector2(0, -RetractingSpeed));
if (_position.Y < _startPosition.Y + 16 + MinLeverLength)
_position.Set(new Vector2(_startPosition.X, _startPosition.Y + 16 + MinLeverLength));
_length = _position.Y - 16 - _startPosition.Y;
}
_isGrabbed = false;
}
private void Draw(SpriteBatch spriteBatch)
{
// thing
spriteBatch.Draw(_dictLeverTop.Texture,
new Rectangle(_startPosition.X - 2, _startPosition.Y, 4, (int)_length + 1), _dictLeverTop.ScaledRectangle, Color.White);
// pull thing
spriteBatch.Draw(_dictLever.Texture,
new Vector2(_position.X - 8, _position.Y - 16), _dictLever.ScaledRectangle, Color.White);
}
}
} | 412 | 0.94981 | 1 | 0.94981 | game-dev | MEDIA | 0.929398 | game-dev | 0.998093 | 1 | 0.998093 |
canton7/StateMechanic | 1,014 | Samples/CustomBaseState.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StateMechanic;
namespace Samples
{
public class CustomBaseState : StateBase<CustomBaseState>
{
protected override bool CanTransition(IEvent @event, CustomBaseState to)
{
// Can abort the transition, like a transition guard
return true;
}
protected override void OnEntry(StateHandlerInfo<CustomBaseState> info)
{
// Custom code which isn't in the entry handler
base.OnEntry(info);
}
protected override void OnExit(StateHandlerInfo<CustomBaseState> info)
{
// Custom code which isn't in the exit handler
base.OnExit(info);
}
protected override CustomBaseState HandleEvent(IEvent @event)
{
// Can force transition to a particular state, like a dynamic transition
return null;
}
}
}
| 412 | 0.777008 | 1 | 0.777008 | game-dev | MEDIA | 0.632452 | game-dev | 0.540103 | 1 | 0.540103 |
Stefanuk12/ROBLOX | 2,153 | Games/Rolling Thunder/AimLock.lua | -- // Dependencies
local AimingNPC = loadstring(game:HttpGet("https://raw.githubusercontent.com/Stefanuk12/ROBLOX/master/Universal/Aiming/NPC.lua"))()
-- // Services
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")
local Workspace = game:GetService("Workspace")
local RunService = game:GetService("RunService")
local UserInputService = game:GetService("UserInputService")
-- // Vars
local LocalPlayer = Players.LocalPlayer
local Network = debug.getupvalue(require(ReplicatedStorage.Network), 2)
AimingNPC.RaycastIgnore = {LocalPlayer.Character, CurrentCamera}
AimingNPC.FOV = 150
local ThunderSettings = {
AimLock = true,
AimLockKeybind = Enum.KeyCode.W
}
getgenv().ThunderSettings = ThunderSettings
-- // Parse ignored stuff
for _, child in ipairs(Workspace.Walls:GetChildren()) do
-- // Make sure can't collide
if (child:IsA("BasePart") and not child.CanCollide) then
-- // Add to ignored
table.insert(AimingNPC.RaycastIgnore, child)
end
end
-- // Check if an object is an NPC
function AimingNPC.IsNPC(Object)
return Object:FindFirstChild("Humanoid") and not Players:FindFirstChild(Object.Name)
end
-- // Override
function AimingNPC.GetNPCs()
-- // Vars
local NPCs = {}
-- // Loop through Workspace children
for _, child in ipairs(Workspace:GetChildren()) do
-- // Make sure is an NPC
if (AimingNPC.IsNPC(child)) then
-- // Add it
local NPC = child
table.insert(NPCs, NPC)
end
end
-- // Return
return NPCs
end
-- // Constant Loop
RunService:BindToRenderStep("AimLock", 0, function()
-- // Make sure aimlock is enabled and we have a target
if (ThunderSettings.AimLock and AimingNPC.Check() and UserInputService:IsKeyDown(ThunderSettings.AimLockKeybind)) then
-- // Vars
local CurrentCamera = Workspace.CurrentCamera
local SelectedPart = AimingNPC.SelectedPart
-- // Set the camera to face towards the Hit
CurrentCamera.CFrame = CFrame.lookAt(CurrentCamera.CFrame.Position, SelectedPart.Position)
end
end) | 412 | 0.935433 | 1 | 0.935433 | game-dev | MEDIA | 0.951052 | game-dev | 0.877854 | 1 | 0.877854 |
CoalitionArma/Coalition-Reforger-Framework | 7,550 | Worlds/COALobby/Rostov/Harry_TVT_AcornKing_Layers/obj.layer | SCR_BaseTriggerEntity ObjObj {
coords 3586.549 71.569 7578.35
userScript " void respawnOpfor()"\
" {"\
" if (RplSession.Mode() == RplMode.Dedicated) "\
" {"\
" CRF_Gamemode gm = CRF_Gamemode.GetInstance();"\
" gm.m_iOPFORTickets = 100;"\
" gm.RespawnSide(\"OPFOR\");"\
" GetGame().GetCallqueue().CallLater(respawnOpforCleanup, 10000, false);"\
" }"\
" }"\
" "\
" void respawnOpforCleanup()"\
" {"\
" if (RplSession.Mode() == RplMode.Dedicated) "\
" {"\
" CRF_Gamemode gm = CRF_Gamemode.GetInstance();"\
" gm.m_iOPFORTickets = 0;"\
" }"\
" }"\
" "\
" void unlockZone2()"\
" {"\
" IEntity zoneMarkers = GetGame().GetWorld().FindEntityByName(\"zone1markers\");"\
" SCR_EntityHelper.DeleteEntityAndChildren(zoneMarkers);"\
" SCR_PopUpNotification.GetInstance().PopupMsg(\"Zone 2 is now unlocked\", duration: 10);"\
" }"\
" "\
" void unlockZone3()"\
" {"\
" IEntity zoneMarkers = GetGame().GetWorld().FindEntityByName(\"zone2markers\");"\
" SCR_EntityHelper.DeleteEntityAndChildren(zoneMarkers);"\
" SCR_PopUpNotification.GetInstance().PopupMsg(\"Zone 3 is now unlocked\", duration: 10);"\
" }"
}
$grp GenericEntity : "{3FD3F403025BBDF5}Prefabs/Props/Military/SupplyBox/SupplyStack/SupplyStack_Large_01/SupplyStack_Large_01_storage.et" {
ObjA {
components {
SCR_DestructionMultiPhaseComponent "{5624A88D86EFE8BA}" {
Enabled 1
}
}
coords 3362.514 87.031 7482.474
destructor ""\
" SCR_PopUpNotification.GetInstance().PopupMsg(\"OBJ 1 destroyed. Opfor respawns in 10 sec. Zone 2 unlocks in 2 min.\", duration: 10);"\
" "\
" if (RplSession.Mode() == RplMode.Dedicated)"\
" {"\
" int playerCount = GetGame().GetPlayerManager().GetPlayerCount();"\
" int bluforCount = Math.Ceil(playerCount / 5 * 3);"\
" CRF_Gamemode gm = CRF_Gamemode.GetInstance();"\
" gm.m_iBLUFORTickets = gm.m_iBLUFORTickets + Math.Ceil(bluforCount * 0.5);"\
" }"\
" "\
" ObjObj_Class obj = ObjObj_Class.Cast(GetGame().GetWorld().FindEntityByName(\"ObjObj\"));"\
" "\
" GetGame().GetCallqueue().CallLater(obj.respawnOpfor, 15000, false);"\
" GetGame().GetCallqueue().CallLater(obj.unlockZone2, 120000, false);"\
" "
{
SCR_VehicleSpawn ZU {
coords 3.864 0 -3.18
angleY -50.586
m_rnPrefab "{FD109F3702AAB392}Prefabs/Vehicles/Wheeled/Ural4320/Ural4320_ZU23.et"
respawnDelay 10000
firstSpawn 1
{
$grp GenericEntity : "{BE16EE8FAA315FE2}Prefabs/Props/Military/Sandbags/Sandbag_01_long_high_burlap.et" {
{
coords -3.121 0 0.707
angleY 89.026
}
{
coords -3.065 0 -2.57
angleY 89.026
}
{
coords 1.538 -0.211 -4.904
angleY -179.924
}
{
coords -1.739 -0.067 -4.897
angleY -179.924
}
{
coords 2.933 -0.077 -2.469
angleY 89.026
}
{
coords 2.878 0 0.809
angleY 89.026
}
{
coords 3.079 0 4.5
angleY 178.76
}
{
coords -2.946 0 4.417
angleY 178.76
}
}
}
}
CRF_ManualMarker : "{7B677FB61E410D0D}PrefabsEditable/Markers/ObjectiveMarker.et" {
coords 0.673 0 -1.511
m_MarkerColor 0.502 0 0 1
m_sQuadName "fortification"
m_sDescription "ZU-23"
m_bVisibleForEmptyFaction 1
m_bShowForAnyFaction 1
}
}
}
ObjB {
components {
SCR_DestructionMultiPhaseComponent "{5624A88D86EFE8BA}" {
Enabled 1
}
}
coords 2400.111 183.924 7517.198
destructor ""\
" SCR_PopUpNotification.GetInstance().PopupMsg(\"OBJ 2 destroyed. Opfor respawns in 10 sec. Zone 3 unlocks in 2 min.\", duration: 10);"\
" "\
" if (RplSession.Mode() == RplMode.Dedicated)"\
" {"\
" int playerCount = GetGame().GetPlayerManager().GetPlayerCount();"\
" int bluforCount = Math.Ceil(playerCount / 5 * 3);"\
" CRF_Gamemode gm = CRF_Gamemode.GetInstance();"\
" gm.m_iBLUFORTickets = gm.m_iBLUFORTickets + Math.Ceil(bluforCount * 0.5);"\
" }"\
" "\
" ObjObj_Class obj = ObjObj_Class.Cast(GetGame().GetWorld().FindEntityByName(\"ObjObj\"));"\
" "\
" GetGame().GetCallqueue().CallLater(obj.respawnOpfor, 15000, false);"\
" GetGame().GetCallqueue().CallLater(obj.unlockZone3, 120000, false);"\
" "
{
$grp SCR_VehicleSpawn {
fuel {
coords 3.23 0.168 5.296
angleY -50.586
m_rnPrefab "{4A59DAEFE645E8A0}Prefabs/Vehicles/Wheeled/Ural4320/Ural4320_tanker_CIV_orange.et"
respawnDelay 10000
firstSpawn 1
{
$grp StaticModelEntity : "{5608B9078BF2AC5A}Prefabs/Structures/Military/Fortifications/Dragontooth_01/Dragonsteeth_01_old_V1.et" {
{
coords 3.788 0.439 4.516
angleY 50.586
}
{
coords -3.316 0.375 5.534
angleY 50.586
}
{
coords 2.417 -0.38 -5.411
angleY 50.586
}
{
coords -2.48 -0.456 -5.125
angleY 50.586
}
{
coords 0.072 -0.556 -7.113
angleY 50.586
}
{
coords 0.005 0.6 7.486
angleY 50.586
}
}
}
}
fuel2 {
coords -5.544 0.068 -3.936
angleY -50.586
m_rnPrefab "{4A59DAEFE645E8A0}Prefabs/Vehicles/Wheeled/Ural4320/Ural4320_tanker_CIV_orange.et"
respawnDelay 10000
firstSpawn 1
{
$grp StaticModelEntity : "{5608B9078BF2AC5A}Prefabs/Structures/Military/Fortifications/Dragontooth_01/Dragonsteeth_01_old_V1.et" {
{
coords 3.788 0.323 4.516
angleY 50.586
}
{
coords -3.316 0.202 5.534
angleY 50.586
}
{
coords 2.417 -0.369 -5.411
angleY 50.586
}
{
coords -2.478 -0.467 -5.125
angleY 50.586
}
{
coords 0.073 -0.56 -7.113
angleY 50.586
}
{
coords 0.005 0.39 7.486
angleY 50.586
}
}
}
}
}
CRF_ManualMarker : "{7B677FB61E410D0D}PrefabsEditable/Markers/ObjectiveMarker.et" {
coords 0.673 -0.113 -1.511
angleY 90
m_MarkerColor 0.502 0 0 1
m_sQuadName "fortification"
m_sDescription "Fuel Depot"
m_aVisibleForFactions {
"OPFOR"
}
}
}
}
ObjC {
components {
SCR_DestructionMultiPhaseComponent "{5624A88D86EFE8BA}" {
Enabled 1
}
}
coords 1100.115 191.805 7214.212
angleY -83.063
destructor ""\
" SCR_PopUpNotification.GetInstance().PopupMsg(\"OBJ 3 destroyed.\", duration: 10);"\
" "
{
GenericEntity {
components {
MeshObject "{651D0D975731B23E}" {
Object "{01E5327CE6F3006E}Assets/Structures/Military/CamoNets/CamoNet_Tent_Soviet.xob"
}
}
coords -2.073 0.115 1.098
}
StaticModelEntity : "{07C8783AD399E669}Prefabs/Compositions/Misc/SubCompositions/Furniture/Chair_NightStand_USSR_03.et" {
coords -2.538 0.135 0.989
angleY 0
}
GenericEntity : "{757FCCE8E756175C}Prefabs/Props/Furniture/MeetingTable_01.et" {
coords -2.335 0.135 1.593
}
CRF_ManualMarker : "{7B677FB61E410D0D}PrefabsEditable/Markers/ObjectiveMarker.et" {
coords 0.673 0 -1.511
m_MarkerColor 0.502 0 0 1
m_sQuadName "fortification"
m_sDescription "HQ"
m_aVisibleForFactions {
"OPFOR"
}
}
GenericEntity : "{B17411929589C43C}Prefabs/MP/Campaign/Assets/CampaignHQRadioEast.et" {
coords -1.613 1.041 1.544
angleY -129.893
}
GenericEntity : "{D60220233693B077}Prefabs/Items/Equipment/Maps/Map_Paper_01/Map_Paper_01_unfolded_table.et" {
coords -3.18 1.038 1.597
}
}
}
} | 412 | 0.785354 | 1 | 0.785354 | game-dev | MEDIA | 0.961977 | game-dev | 0.593194 | 1 | 0.593194 |
KettleFoundation/Kettle | 1,114 | patches/net/minecraft/world/chunk/storage/ExtendedBlockStorage.java.patch | --- ../src-base/minecraft/net/minecraft/world/chunk/storage/ExtendedBlockStorage.java
+++ ../src-work/minecraft/net/minecraft/world/chunk/storage/ExtendedBlockStorage.java
@@ -27,6 +27,22 @@
}
}
+ public ExtendedBlockStorage(int y, boolean flag, char[] blockIds) {
+ this.yBase = y;
+ this.data = new BlockStateContainer();
+ for (int i = 0; i < blockIds.length; i++) {
+ int xx = i & 15;
+ int yy = (i >> 8) & 15;
+ int zz = (i >> 4) & 15;
+ this.data.set(xx, yy, zz, Block.BLOCK_STATE_IDS.getByValue(blockIds[i]));
+ }
+ this.blockLight = new NibbleArray();
+ if (flag) {
+ this.skyLight = new NibbleArray();
+ }
+ recalculateRefCounts();
+ }
+
public IBlockState get(int x, int y, int z)
{
return this.data.get(x, y, z);
@@ -65,7 +81,8 @@
public boolean isEmpty()
{
- return this.blockRefCount == 0;
+ // return this.blockRefCount == 0;
+ return false; // CraftBukkit - MC-80966
}
public boolean needsRandomTick()
| 412 | 0.798132 | 1 | 0.798132 | game-dev | MEDIA | 0.957965 | game-dev | 0.900839 | 1 | 0.900839 |
paulevsGitch/BetterEnd | 1,155 | src/main/java/ru/betterend/mixin/client/PlayerRendererMixin.java | package ru.betterend.mixin.client;
import net.minecraft.client.model.PlayerModel;
import net.minecraft.client.player.AbstractClientPlayer;
import net.minecraft.client.renderer.entity.EntityRendererProvider;
import net.minecraft.client.renderer.entity.LivingEntityRenderer;
import net.minecraft.client.renderer.entity.player.PlayerRenderer;
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 ru.betterend.client.render.ArmoredElytraLayer;
@Mixin(PlayerRenderer.class)
public abstract class PlayerRendererMixin extends LivingEntityRenderer<AbstractClientPlayer, PlayerModel<AbstractClientPlayer>> {
public PlayerRendererMixin(EntityRendererProvider.Context context, PlayerModel<AbstractClientPlayer> entityModel, float f) {
super(context, entityModel, f);
}
@Inject(method = "<init>*", at = @At("TAIL"))
public void be_addCustomLayer(EntityRendererProvider.Context context, boolean bl, CallbackInfo ci) {
addLayer(new ArmoredElytraLayer<>(this, context.getModelSet()));
}
}
| 412 | 0.708668 | 1 | 0.708668 | game-dev | MEDIA | 0.935056 | game-dev | 0.896446 | 1 | 0.896446 |
Fluorohydride/ygopro-scripts | 2,701 | c85277313.lua | --ティスティナの胎動
local s,id,o=GetID()
function s.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetTarget(s.target)
e1:SetOperation(s.activate)
c:RegisterEffect(e1)
--self destroy
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EVENT_LEAVE_FIELD)
e2:SetRange(LOCATION_MZONE)
e2:SetCondition(s.condition)
e2:SetOperation(s.sdestroy)
c:RegisterEffect(e2)
--target destroy
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e3:SetCode(EVENT_LEAVE_FIELD_P)
e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e3:SetOperation(s.check)
c:RegisterEffect(e3)
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e4:SetCode(EVENT_LEAVE_FIELD)
e4:SetLabelObject(e3)
e4:SetCondition(s.condition)
e4:SetOperation(s.tdestroy)
c:RegisterEffect(e4)
end
function s.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsFaceup() end
if chk==0 then return Duel.IsExistingTarget(Card.IsFaceup,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil)
and Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsPlayerCanSpecialSummonMonster(tp,id,0x1a4,TYPES_EFFECT_TRAP_MONSTER,0,0,10,RACE_AQUA,ATTRIBUTE_LIGHT) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,Card.IsFaceup,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function s.activate(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0
or not Duel.IsPlayerCanSpecialSummonMonster(tp,id,0x1a4,TYPES_EFFECT_TRAP_MONSTER,0,0,10,RACE_AQUA,ATTRIBUTE_LIGHT) then return end
local c=e:GetHandler()
c:AddMonsterAttribute(TYPE_EFFECT+TYPE_TRAP)
Duel.SpecialSummon(c,0,tp,tp,true,false,POS_FACEUP)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then c:SetCardTarget(tc) end
end
function s.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()==1-tp
end
function s.sdestroy(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetHandler():GetFirstCardTarget()
if tc and eg:IsContains(tc) then Duel.Destroy(e:GetHandler(),REASON_EFFECT) end
end
function s.check(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsDisabled() then e:SetLabel(1) else e:SetLabel(0) end
end
function s.tdestroy(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetHandler():GetFirstCardTarget()
if e:GetLabelObject():GetLabel()==0 and tc and tc:IsLocation(LOCATION_MZONE) then
Duel.Destroy(tc,REASON_EFFECT)
end
end
| 412 | 0.892064 | 1 | 0.892064 | game-dev | MEDIA | 0.993735 | game-dev | 0.951874 | 1 | 0.951874 |
apache/james-project | 6,842 | protocols/imap/src/main/java/org/apache/james/imap/api/message/FetchData.java | /****************************************************************
* Licensed to the Apache Software Foundation (ASF) under one *
* or more contributor license agreements. See the NOTICE file *
* distributed with this work for additional information *
* regarding copyright ownership. The ASF licenses this file *
* to you under the Apache License, Version 2.0 (the *
* "License"); you may not use this file except in compliance *
* with the License. You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, *
* software distributed under the License is distributed on an *
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
* KIND, either express or implied. See the License for the *
* specific language governing permissions and limitations *
* under the License. *
****************************************************************/
package org.apache.james.imap.api.message;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.Objects;
import java.util.Optional;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableSet;
public class FetchData {
public static class Builder {
public static Builder from(FetchData fetchData) {
return builder()
.fetch(fetchData.itemToFetch)
.vanished(fetchData.vanished)
.changedSince(fetchData.changedSince)
.addBodyElements(fetchData.bodyElements)
.seen(fetchData.setSeen);
}
private final EnumSet<Item> itemToFetch = EnumSet.noneOf(Item.class);
private final ImmutableSet.Builder<BodyFetchElement> bodyElements = ImmutableSet.builder();
private boolean setSeen = false;
private long changedSince = -1;
private boolean vanished;
private Optional<PartialRange> partialRange = Optional.empty();
public Builder fetch(Item item) {
itemToFetch.add(item);
return this;
}
public Builder fetch(Item... item) {
return fetch(Arrays.asList(item));
}
public Builder fetch(Collection<Item> items) {
itemToFetch.addAll(items);
return this;
}
public Builder changedSince(long changedSince) {
this.changedSince = changedSince;
return fetch(Item.MODSEQ);
}
public Builder partial(PartialRange partialRange) {
this.partialRange = Optional.of(partialRange);
return this;
}
/**
* Set to true if the VANISHED FETCH modifier was used as stated in <code>QRESYNC</code> extension
*/
public Builder vanished(boolean vanished) {
this.vanished = vanished;
return this;
}
public Builder add(BodyFetchElement element, boolean peek) {
if (!peek) {
setSeen = true;
}
bodyElements.add(element);
return this;
}
private Builder addBodyElements(Collection<BodyFetchElement> elements) {
bodyElements.addAll(elements);
return this;
}
private Builder seen(boolean setSeen) {
this.setSeen = setSeen;
return this;
}
public FetchData build() {
return new FetchData(itemToFetch, bodyElements.build(), partialRange, setSeen, changedSince, vanished);
}
}
public enum Item {
FLAGS,
UID,
INTERNAL_DATE,
SIZE,
ENVELOPE,
BODY,
BODY_STRUCTURE,
MODSEQ,
// https://www.rfc-editor.org/rfc/rfc8474.html#section-5.3
EMAILID,
THREADID,
// https://www.rfc-editor.org/rfc/rfc8514.html#section-4.2
SAVEDATE
}
public static Builder builder() {
return new Builder();
}
private final EnumSet<Item> itemToFetch;
private final ImmutableSet<BodyFetchElement> bodyElements;
private final Optional<PartialRange> partialRange;
private final boolean setSeen;
private final long changedSince;
private final boolean vanished;
private FetchData(EnumSet<Item> itemToFetch, ImmutableSet<BodyFetchElement> bodyElements, Optional<PartialRange> partialRange, boolean setSeen, long changedSince, boolean vanished) {
this.itemToFetch = itemToFetch;
this.bodyElements = bodyElements;
this.partialRange = partialRange;
this.setSeen = setSeen;
this.changedSince = changedSince;
this.vanished = vanished;
}
public Collection<BodyFetchElement> getBodyElements() {
return bodyElements;
}
public boolean contains(Item item) {
return itemToFetch.contains(item);
}
public boolean isSetSeen() {
return setSeen;
}
public long getChangedSince() {
return changedSince;
}
public Optional<PartialRange> getPartialRange() {
return partialRange;
}
/**
* Return true if the VANISHED FETCH modifier was used as stated in <code>QRESYNC<code> extension
*/
public boolean getVanished() {
return vanished;
}
public boolean isOnlyFlags() {
return bodyElements.isEmpty()
&& itemToFetch.stream()
.filter(item -> item != Item.FLAGS)
.filter(item -> item != Item.UID)
.filter(item -> item != Item.MODSEQ)
.findAny()
.isEmpty();
}
@Override
public final int hashCode() {
return Objects.hash(itemToFetch, bodyElements, setSeen, changedSince);
}
@Override
public final boolean equals(Object o) {
if (o instanceof FetchData) {
FetchData fetchData = (FetchData) o;
return Objects.equals(this.setSeen, fetchData.setSeen)
&& Objects.equals(this.changedSince, fetchData.changedSince)
&& Objects.equals(this.itemToFetch, fetchData.itemToFetch)
&& Objects.equals(this.bodyElements, fetchData.bodyElements);
}
return false;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(FetchData.class.getSimpleName())
.omitNullValues()
.add("items", itemToFetch)
.add("setSeen", setSeen)
.add("bodyElements", bodyElements)
.add("changedSince", changedSince)
.add("vanished", vanished)
.toString();
}
}
| 412 | 0.767125 | 1 | 0.767125 | game-dev | MEDIA | 0.144552 | game-dev | 0.7704 | 1 | 0.7704 |
Rosewood-Development/RoseLoot | 2,818 | NMS/v1_20_R3/src/main/java/dev/rosewood/roseloot/nms/v1_20_R3/NMSHandlerImpl.java | package dev.rosewood.roseloot.nms.v1_20_R3;
import dev.rosewood.rosegarden.utils.NMSUtil;
import dev.rosewood.roseloot.nms.NMSHandler;
import net.minecraft.core.BlockPos;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.util.RandomSource;
import net.minecraft.world.item.enchantment.EnchantmentHelper;
import net.minecraft.world.level.StructureManager;
import net.minecraft.world.level.levelgen.structure.Structure;
import net.minecraft.world.level.levelgen.structure.StructureStart;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.World;
import org.bukkit.craftbukkit.v1_20_R3.CraftWorld;
import org.bukkit.craftbukkit.v1_20_R3.inventory.CraftItemStack;
import org.bukkit.inventory.ItemStack;
public class NMSHandlerImpl implements NMSHandler {
@Override
public ItemStack enchantWithLevels(ItemStack itemStack, int levels, boolean treasure, World world) {
if (itemStack.getType() == Material.ENCHANTED_BOOK) {
if (NMSUtil.isPaper()) {
itemStack = itemStack.withType(Material.BOOK);
} else {
itemStack.setType(Material.BOOK);
}
}
net.minecraft.world.item.ItemStack nmsStack = CraftItemStack.asNMSCopy(itemStack);
RandomSource randomSource = world != null ? ((CraftWorld) world).getHandle().getRandom() : RandomSource.create();
net.minecraft.world.item.ItemStack enchantedStack = EnchantmentHelper.enchantItem(randomSource, nmsStack, levels, treasure);
return CraftItemStack.asCraftMirror(enchantedStack);
}
@Override
public boolean isWithinStructure(Location location, NamespacedKey structureKey) {
ServerLevel serverLevel = ((CraftWorld) location.getWorld()).getHandle();
HolderLookup.RegistryLookup<Structure> registry = MinecraftServer.getServer().registryAccess().lookupOrThrow(Registries.STRUCTURE);
ResourceLocation resourceLocation = new ResourceLocation(structureKey.toString());
ResourceKey<Structure> structureResourceKey = ResourceKey.create(Registries.STRUCTURE, resourceLocation);
Structure structure = registry.getOrThrow(structureResourceKey).value();
StructureManager structureManager = serverLevel.structureManager();
BlockPos blockPos = new BlockPos(location.getBlockX(), location.getBlockY(), location.getBlockZ());
StructureStart structureStart = structureManager.getStructureWithPieceAt(blockPos, structure);
return !structureStart.equals(StructureStart.INVALID_START);
}
}
| 412 | 0.828334 | 1 | 0.828334 | game-dev | MEDIA | 0.999249 | game-dev | 0.756981 | 1 | 0.756981 |
space-wizards/space-station-14 | 9,188 | Content.Client/Tips/TippyUIController.cs | using System.Numerics;
using Content.Client.Message;
using Content.Client.Paper.UI;
using Content.Shared.CCVar;
using Content.Shared.Movement.Components;
using Content.Shared.Tips;
using Robust.Client.GameObjects;
using Robust.Client.ResourceManagement;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.Controllers;
using Robust.Client.UserInterface.Controls;
using Robust.Client.Audio;
using Robust.Shared.Configuration;
using Robust.Shared.Map;
using Robust.Shared.Timing;
using static Content.Client.Tips.TippyUI;
namespace Content.Client.Tips;
public sealed class TippyUIController : UIController
{
[Dependency] private readonly IConfigurationManager _cfg = default!;
[Dependency] private readonly IResourceCache _resCache = default!;
[UISystemDependency] private readonly AudioSystem _audio = default!;
[UISystemDependency] private readonly SpriteSystem _sprite = default!;
public const float Padding = 50;
public static Angle WaddleRotation = Angle.FromDegrees(10);
private EntityUid _entity;
private float _secondsUntilNextState;
private int _previousStep = 0;
private TippyEvent? _currentMessage;
private readonly Queue<TippyEvent> _queuedMessages = new();
public override void Initialize()
{
base.Initialize();
UIManager.OnScreenChanged += OnScreenChanged;
SubscribeNetworkEvent<TippyEvent>(OnTippyEvent);
}
private void OnTippyEvent(TippyEvent msg, EntitySessionEventArgs args)
{
_queuedMessages.Enqueue(msg);
}
public override void FrameUpdate(FrameEventArgs args)
{
base.FrameUpdate(args);
var screen = UIManager.ActiveScreen;
if (screen == null)
{
_queuedMessages.Clear();
return;
}
var tippy = screen.GetOrAddWidget<TippyUI>();
_secondsUntilNextState -= args.DeltaSeconds;
if (_secondsUntilNextState <= 0)
NextState(tippy);
else
{
var pos = UpdatePosition(tippy, screen.Size, args); ;
LayoutContainer.SetPosition(tippy, pos);
}
}
private Vector2 UpdatePosition(TippyUI tippy, Vector2 screenSize, FrameEventArgs args)
{
if (_currentMessage == null)
return default;
var slideTime = _currentMessage.SlideTime;
var offset = tippy.State switch
{
TippyState.Hidden => 0,
TippyState.Revealing => Math.Clamp(1 - _secondsUntilNextState / slideTime, 0, 1),
TippyState.Hiding => Math.Clamp(_secondsUntilNextState / slideTime, 0, 1),
_ => 1,
};
var waddle = _currentMessage.WaddleInterval;
if (_currentMessage == null
|| waddle <= 0
|| tippy.State == TippyState.Hidden
|| tippy.State == TippyState.Speaking
|| !EntityManager.TryGetComponent(_entity, out SpriteComponent? sprite))
{
return new Vector2(screenSize.X - offset * (tippy.DesiredSize.X + Padding), (screenSize.Y - tippy.DesiredSize.Y) / 2);
}
var numSteps = (int)Math.Ceiling(slideTime / waddle);
var curStep = (int)Math.Floor(numSteps * offset);
var stepSize = (tippy.DesiredSize.X + Padding) / numSteps;
if (curStep != _previousStep)
{
_previousStep = curStep;
_sprite.SetRotation((_entity, sprite),
sprite.Rotation > 0
? -WaddleRotation
: WaddleRotation);
if (EntityManager.TryGetComponent(_entity, out FootstepModifierComponent? step) && step.FootstepSoundCollection != null)
{
var audioParams = step.FootstepSoundCollection.Params
.AddVolume(-7f)
.WithVariation(0.1f);
_audio.PlayGlobal(step.FootstepSoundCollection, EntityUid.Invalid, audioParams);
}
}
return new Vector2(screenSize.X - stepSize * curStep, (screenSize.Y - tippy.DesiredSize.Y) / 2);
}
private void NextState(TippyUI tippy)
{
SpriteComponent? sprite;
switch (tippy.State)
{
case TippyState.Hidden:
if (!_queuedMessages.TryDequeue(out var next))
return;
if (next.Proto != null)
{
_entity = EntityManager.SpawnEntity(next.Proto, MapCoordinates.Nullspace);
tippy.ModifyLayers = false;
}
else
{
_entity = EntityManager.SpawnEntity(_cfg.GetCVar(CCVars.TippyEntity), MapCoordinates.Nullspace);
tippy.ModifyLayers = true;
}
if (!EntityManager.TryGetComponent(_entity, out sprite))
return;
if (!EntityManager.HasComponent<PaperVisualsComponent>(_entity))
{
var paper = EntityManager.AddComponent<PaperVisualsComponent>(_entity);
paper.BackgroundImagePath = "/Textures/Interface/Paper/paper_background_default.svg.96dpi.png";
paper.BackgroundPatchMargin = new(16f, 16f, 16f, 16f);
paper.BackgroundModulate = new(255, 255, 204);
paper.FontAccentColor = new(0, 0, 0);
}
tippy.InitLabel(EntityManager.GetComponentOrNull<PaperVisualsComponent>(_entity), _resCache);
var scale = sprite.Scale;
if (tippy.ModifyLayers)
{
_sprite.SetScale((_entity, sprite), Vector2.One);
}
else
{
_sprite.SetScale((_entity, sprite), new Vector2(3, 3));
}
tippy.Entity.SetEntity(_entity);
tippy.Entity.Scale = scale;
_currentMessage = next;
_secondsUntilNextState = next.SlideTime;
tippy.State = TippyState.Revealing;
_previousStep = 0;
if (tippy.ModifyLayers)
{
_sprite.LayerSetAnimationTime((_entity, sprite), "revealing", 0);
_sprite.LayerSetVisible((_entity, sprite), "revealing", true);
_sprite.LayerSetVisible((_entity, sprite), "speaking", false);
_sprite.LayerSetVisible((_entity, sprite), "hiding", false);
}
_sprite.SetRotation((_entity, sprite), 0);
tippy.Label.SetMarkupPermissive(_currentMessage.Msg);
tippy.Label.Visible = false;
tippy.LabelPanel.Visible = false;
tippy.Visible = true;
_sprite.SetVisible((_entity, sprite), true);
break;
case TippyState.Revealing:
tippy.State = TippyState.Speaking;
if (!EntityManager.TryGetComponent(_entity, out sprite))
return;
_sprite.SetRotation((_entity, sprite), 0);
_previousStep = 0;
if (tippy.ModifyLayers)
{
_sprite.LayerSetAnimationTime((_entity, sprite), "speaking", 0);
_sprite.LayerSetVisible((_entity, sprite), "revealing", false);
_sprite.LayerSetVisible((_entity, sprite), "speaking", true);
_sprite.LayerSetVisible((_entity, sprite), "hiding", false);
}
tippy.Label.Visible = true;
tippy.LabelPanel.Visible = true;
tippy.InvalidateArrange();
tippy.InvalidateMeasure();
if (_currentMessage != null)
_secondsUntilNextState = _currentMessage.SpeakTime;
break;
case TippyState.Speaking:
tippy.State = TippyState.Hiding;
if (!EntityManager.TryGetComponent(_entity, out sprite))
return;
if (tippy.ModifyLayers)
{
_sprite.LayerSetAnimationTime((_entity, sprite), "hiding", 0);
_sprite.LayerSetVisible((_entity, sprite), "revealing", false);
_sprite.LayerSetVisible((_entity, sprite), "speaking", false);
_sprite.LayerSetVisible((_entity, sprite), "hiding", true);
}
tippy.LabelPanel.Visible = false;
if (_currentMessage != null)
_secondsUntilNextState = _currentMessage.SlideTime;
break;
default: // finished hiding
EntityManager.DeleteEntity(_entity);
_entity = default;
tippy.Visible = false;
_currentMessage = null;
_secondsUntilNextState = 0;
tippy.State = TippyState.Hidden;
break;
}
}
private void OnScreenChanged((UIScreen? Old, UIScreen? New) ev)
{
ev.Old?.RemoveWidget<TippyUI>();
_currentMessage = null;
EntityManager.DeleteEntity(_entity);
}
}
| 412 | 0.858713 | 1 | 0.858713 | game-dev | MEDIA | 0.93059 | game-dev | 0.965962 | 1 | 0.965962 |
mehah/otclient | 1,688 | mods/game_bot/default_configs/vBot_4.8/cavebot/pos_check.lua | CaveBot.Extensions.PosCheck = {}
local posCheckRetries = 0
CaveBot.Extensions.PosCheck.setup = function()
CaveBot.registerAction("PosCheck", "#00FFFF", function(value, retries)
local tilePos
local data = string.split(value, ",")
if #data ~= 5 then
warn("wrong travel format, should be: label, distance, x, y, z")
return false
end
local tilePos = player:getPosition()
tilePos.x = tonumber(data[3])
tilePos.y = tonumber(data[4])
tilePos.z = tonumber(data[5])
if posCheckRetries > 10 then
posCheckRetries = 0
print("CaveBot[CheckPos]: waypoints locked, too many tries, unclogging cavebot and proceeding")
return false
elseif (tilePos.z == player:getPosition().z) and (getDistanceBetween(player:getPosition(), tilePos) <= tonumber(data[2])) then
posCheckRetries = 0
print("CaveBot[CheckPos]: position reached, proceeding")
return true
else
posCheckRetries = posCheckRetries + 1
if data[1] == "last" then
CaveBot.gotoFirstPreviousReachableWaypoint()
print("CaveBot[CheckPos]: position not-reached, going back to first reachable waypoint.")
return false
else
CaveBot.gotoLabel(data[1])
print("CaveBot[CheckPos]: position not-reached, going back to label: " .. data[1])
return false
end
end
end)
CaveBot.Editor.registerAction("poscheck", "pos check", {
value=function() return "last" .. "," .. "10" .. "," .. posx() .. "," .. posy() .. "," .. posz() end,
title="Location Check",
description="label name, accepted dist from coordinates, x, y, z",
multiline=false,
})
end
| 412 | 0.667726 | 1 | 0.667726 | game-dev | MEDIA | 0.314037 | game-dev | 0.892705 | 1 | 0.892705 |
hogwarts-mp/mod | 6,518 | code/client/src/sdk/Runtime/CoreUObject/Private/UObject/PropertyClass.cpp | // Copyright Epic Games, Inc. All Rights Reserved.
#include "CoreMinimal.h"
#include "UObject/ObjectMacros.h"
#include "Templates/Casts.h"
#include "UObject/UnrealType.h"
#include "UObject/UnrealTypePrivate.h"
#include "UObject/LinkerPlaceholderClass.h"
#include "Misc/ConfigCacheIni.h"
#include "UObject/PropertyHelper.h"
// WARNING: This should always be the last include in any file that needs it (except .generated.h)
#include "UObject/UndefineUPropertyMacros.h"
/*-----------------------------------------------------------------------------
FClassProperty.
-----------------------------------------------------------------------------*/
IMPLEMENT_FIELD(FClassProperty)
#if WITH_EDITORONLY_DATA
FClassProperty::FClassProperty(UField* InField)
: FObjectProperty(InField)
{
UClassProperty* SourceProperty = CastChecked<UClassProperty>(InField);
MetaClass = SourceProperty->MetaClass;
}
#endif // WITH_EDITORONLY_DATA
void FClassProperty::BeginDestroy()
{
#if USE_CIRCULAR_DEPENDENCY_LOAD_DEFERRING
if (ULinkerPlaceholderClass* PlaceholderClass = Cast<ULinkerPlaceholderClass>(MetaClass))
{
PlaceholderClass->RemoveReferencingProperty(this);
}
#endif // USE_CIRCULAR_DEPENDENCY_LOAD_DEFERRING
Super::BeginDestroy();
}
void FClassProperty::PostDuplicate(const FField& InField)
{
const FClassProperty& Source = static_cast<const FClassProperty&>(InField);
MetaClass = Source.MetaClass;
Super::PostDuplicate(InField);
}
void FClassProperty::Serialize( FArchive& Ar )
{
Super::Serialize( Ar );
Ar << MetaClass;
#if USE_CIRCULAR_DEPENDENCY_LOAD_DEFERRING
if (Ar.IsLoading() || Ar.IsObjectReferenceCollector())
{
if (ULinkerPlaceholderClass* PlaceholderClass = Cast<ULinkerPlaceholderClass>(MetaClass))
{
PlaceholderClass->AddReferencingProperty(this);
}
}
#endif // USE_CIRCULAR_DEPENDENCY_LOAD_DEFERRING
if( !MetaClass )
{
// If we failed to load the MetaClass and we're not a CDO, that means we relied on a class that has been removed or doesn't exist.
// The most likely cause for this is either an incomplete recompile, or if content was migrated between games that had native class dependencies
// that do not exist in this game. We allow blueprint classes to continue, because compile on load will error out, and stub the class that was using it
UClass* TestClass = dynamic_cast<UClass*>(GetOwnerStruct());
if( TestClass && TestClass->HasAllClassFlags(CLASS_Native) && !TestClass->HasAllClassFlags(CLASS_NewerVersionExists) && (TestClass->GetOutermost() != GetTransientPackage()) )
{
checkf(false, TEXT("Class property tried to serialize a missing class. Did you remove a native class and not fully recompile?"));
}
}
}
#if USE_CIRCULAR_DEPENDENCY_LOAD_DEFERRING
void FClassProperty::SetMetaClass(UClass* NewMetaClass)
{
if (ULinkerPlaceholderClass* NewPlaceholderClass = Cast<ULinkerPlaceholderClass>(NewMetaClass))
{
NewPlaceholderClass->AddReferencingProperty(this);
}
if (ULinkerPlaceholderClass* OldPlaceholderClass = Cast<ULinkerPlaceholderClass>(MetaClass))
{
OldPlaceholderClass->RemoveReferencingProperty(this);
}
MetaClass = NewMetaClass;
}
#endif // USE_CIRCULAR_DEPENDENCY_LOAD_DEFERRING
void FClassProperty::AddReferencedObjects(FReferenceCollector& Collector)
{
Collector.AddReferencedObject( MetaClass );
Super::AddReferencedObjects( Collector );
}
const TCHAR* FClassProperty::ImportText_Internal( const TCHAR* Buffer, void* Data, int32 PortFlags, UObject* Parent, FOutputDevice* ErrorText ) const
{
const TCHAR* Result = FObjectProperty::ImportText_Internal( Buffer, Data, PortFlags, Parent, ErrorText );
if( Result )
{
if (UClass* AssignedPropertyClass = dynamic_cast<UClass*>(GetObjectPropertyValue(Data)))
{
#if USE_CIRCULAR_DEPENDENCY_LOAD_DEFERRING
FLinkerLoad* ObjectLinker = (Parent != nullptr) ? Parent->GetClass()->GetLinker() : GetLinker();
auto IsDeferringValueLoad = [](const UClass* Class)->bool
{
const ULinkerPlaceholderClass* Placeholder = Cast<ULinkerPlaceholderClass>(Class);
return Placeholder && !Placeholder->IsMarkedResolved();
};
const bool bIsDeferringValueLoad = IsDeferringValueLoad(MetaClass) || ((!ObjectLinker || (ObjectLinker->LoadFlags & LOAD_DeferDependencyLoads) != 0) && IsDeferringValueLoad(AssignedPropertyClass));
#if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
check( bIsDeferringValueLoad || !(Cast<ULinkerPlaceholderClass>(MetaClass) || Cast<ULinkerPlaceholderClass>(AssignedPropertyClass)) );
#endif // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
#else // USE_CIRCULAR_DEPENDENCY_LOAD_DEFERRING
bool const bIsDeferringValueLoad = false;
#endif // USE_CIRCULAR_DEPENDENCY_LOAD_DEFERRING
// Validate metaclass.
if ((!AssignedPropertyClass->IsChildOf(MetaClass)) && !bIsDeferringValueLoad)
{
// the object we imported doesn't implement our interface class
ErrorText->Logf(TEXT("Invalid object '%s' specified for property '%s'"), *AssignedPropertyClass->GetFullName(), *GetName());
SetObjectPropertyValue(Data, NULL);
Result = NULL;
}
}
}
return Result;
}
FString FClassProperty::GetCPPType(FString* ExtendedTypeText, uint32 CPPExportFlags) const
{
check(MetaClass);
return GetCPPTypeCustom(ExtendedTypeText, CPPExportFlags,
FString::Printf(TEXT("%s%s"), MetaClass->GetPrefixCPP(), *MetaClass->GetName()));
}
FString FClassProperty::GetCPPTypeCustom(FString* ExtendedTypeText, uint32 CPPExportFlags, const FString& InnerNativeTypeName) const
{
if (PropertyFlags & CPF_UObjectWrapper)
{
ensure(!InnerNativeTypeName.IsEmpty());
return FString::Printf(TEXT("TSubclassOf<%s> "), *InnerNativeTypeName);
}
else
{
return TEXT("UClass*");
}
}
FString FClassProperty::GetCPPTypeForwardDeclaration() const
{
return FString::Printf(TEXT("class %s%s;"), MetaClass->GetPrefixCPP(), *MetaClass->GetName());
}
FString FClassProperty::GetCPPMacroType( FString& ExtendedTypeText ) const
{
ExtendedTypeText = TEXT("UClass");
return TEXT("OBJECT");
}
bool FClassProperty::SameType(const FProperty* Other) const
{
return Super::SameType(Other) && (MetaClass == ((FClassProperty*)Other)->MetaClass);
}
bool FClassProperty::Identical( const void* A, const void* B, uint32 PortFlags ) const
{
UObject* ObjectA = A ? GetObjectPropertyValue(A) : nullptr;
UObject* ObjectB = B ? GetObjectPropertyValue(B) : nullptr;
check(ObjectA == nullptr || ObjectA->IsA<UClass>());
check(ObjectB == nullptr || ObjectB->IsA<UClass>());
return (ObjectA == ObjectB);
}
#include "UObject/DefineUPropertyMacros.h" | 412 | 0.916456 | 1 | 0.916456 | game-dev | MEDIA | 0.359224 | game-dev | 0.97434 | 1 | 0.97434 |
gaucho-matrero/altoclef | 15,434 | src/main/java/adris/altoclef/tasks/construction/compound/ConstructNetherPortalBucketTask.java | package adris.altoclef.tasks.construction.compound;
import adris.altoclef.AltoClef;
import adris.altoclef.Debug;
import adris.altoclef.TaskCatalogue;
import adris.altoclef.tasks.InteractWithBlockTask;
import adris.altoclef.tasks.construction.ClearLiquidTask;
import adris.altoclef.tasks.construction.DestroyBlockTask;
import adris.altoclef.tasks.construction.PlaceObsidianBucketTask;
import adris.altoclef.tasks.movement.PickupDroppedItemTask;
import adris.altoclef.tasks.movement.TimeoutWanderTask;
import adris.altoclef.tasksystem.Task;
import adris.altoclef.util.ItemTarget;
import adris.altoclef.util.time.TimerGame;
import adris.altoclef.util.helpers.WorldHelper;
import adris.altoclef.util.progresscheck.MovementProgressChecker;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.client.MinecraftClient;
import net.minecraft.item.Item;
import net.minecraft.item.Items;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.util.math.Vec3i;
import java.util.HashSet;
/**
* Build a nether portal by casting each piece with water + lava.
*
* Currently the most reliable portal building method.
*/
public class ConstructNetherPortalBucketTask extends Task {
// Order here matters
private static final Vec3i[] PORTAL_FRAME = new Vec3i[]{
// Left side
new Vec3i(0, 0, -1),
new Vec3i(0, 1, -1),
new Vec3i(0, 2, -1),
// Right side
new Vec3i(0, 0, 2),
new Vec3i(0, 1, 2),
new Vec3i(0, 2, 2),
// Bottom
new Vec3i(0, -1, 0),
new Vec3i(0, -1, 1),
// Top
new Vec3i(0, 3, 0),
new Vec3i(0, 3, 1)
};
private static final Vec3i[] PORTAL_INTERIOR = new Vec3i[]{
new Vec3i(0, 0, 0),
new Vec3i(0, 1, 0),
new Vec3i(0, 2, 0),
new Vec3i(0, 0, 1),
new Vec3i(0, 1, 1),
new Vec3i(0, 2, 1)
};
// The "portalable" region includes the portal (1 x 6 x 4 structure) and an outer buffer for its construction and water bullshit.
// The "portal origin relative to region" corresponds to the portal origin with respect to the "portalable" region (see _portalOrigin).
// This can only really be explained visually, sorry!
private static final Vec3i PORTALABLE_REGION_SIZE = new Vec3i(4, 6, 6);
private static final Vec3i PORTAL_ORIGIN_RELATIVE_TO_REGION = new Vec3i(1, 0, 2);
private final TimerGame _lavaSearchTimer = new TimerGame(5);
private final MovementProgressChecker _progressChecker = new MovementProgressChecker(5);
private final TimeoutWanderTask _wanderTask = new TimeoutWanderTask(25);
// Stored here to cache lava blacklist
private final Task _collectLavaTask = TaskCatalogue.getItemTask(Items.LAVA_BUCKET, 1);
private final TimerGame _refreshTimer = new TimerGame(11);
private BlockPos _portalOrigin = null;
//private BlockPos _currentLavaTarget = null;
private BlockPos _currentDestroyTarget = null;
private boolean _firstSearch = false;
@Override
protected void onStart(AltoClef mod) {
_currentDestroyTarget = null;
mod.getBlockTracker().trackBlock(Blocks.LAVA);
mod.getBehaviour().push();
// Avoid breaking portal frame if we're obsidian.
// Also avoid placing on the lava + water
// Also avoid breaking the cast frame
mod.getBehaviour().avoidBlockBreaking(block -> {
if (_portalOrigin != null) {
// Don't break frame
for (Vec3i framePosRelative : PORTAL_FRAME) {
BlockPos framePos = _portalOrigin.add(framePosRelative);
if (block.equals(framePos)) {
return mod.getWorld().getBlockState(framePos).getBlock() == Blocks.OBSIDIAN;
}
}
}
return false;
});
// Protect some used items
mod.getBehaviour().addProtectedItems(Items.WATER_BUCKET, Items.LAVA_BUCKET, Items.FLINT_AND_STEEL, Items.FIRE_CHARGE);
_progressChecker.reset();
}
@Override
protected Task onTick(AltoClef mod) {
if (_refreshTimer.elapsed()) {
Debug.logMessage("Duct tape: Refreshing inventory again just in case");
_refreshTimer.reset();
mod.getSlotHandler().refreshInventory();
}
//If too far, reset.
if (_portalOrigin != null && !_portalOrigin.isWithinDistance(mod.getPlayer().getPos(), 2000)) {
_portalOrigin = null;
_currentDestroyTarget = null;
}
if (_currentDestroyTarget != null) {
if (!WorldHelper.isSolid(mod, _currentDestroyTarget)) {
_currentDestroyTarget = null;
} else {
return new DestroyBlockTask(_currentDestroyTarget);
}
}
if (_wanderTask.isActive() && !_wanderTask.isFinished(mod)) {
setDebugState("Wandering before retrying...");
_progressChecker.reset();
return _wanderTask;
}
// Get bucket if we don't have one.
int bucketCount = mod.getItemStorage().getItemCount(Items.BUCKET, Items.LAVA_BUCKET, Items.WATER_BUCKET);
if (bucketCount < 2) {
setDebugState("Getting buckets");
_progressChecker.reset();
// If we have lava/water, get the inverse. Otherwise we dropped a bucket, just get a bucket.
if (mod.getItemStorage().hasItem(Items.LAVA_BUCKET)) {
return TaskCatalogue.getItemTask(Items.WATER_BUCKET, 1);
} else if (mod.getItemStorage().hasItem(Items.WATER_BUCKET)) {
return TaskCatalogue.getItemTask(Items.LAVA_BUCKET, 1);
}
if (mod.getEntityTracker().itemDropped(Items.WATER_BUCKET, Items.LAVA_BUCKET)) {
return new PickupDroppedItemTask(new ItemTarget(new Item[]{Items.WATER_BUCKET, Items.LAVA_BUCKET}, 1), true);
}
return TaskCatalogue.getItemTask(Items.BUCKET, 2);
}
// Get flint & steel if we don't have one
if (!mod.getItemStorage().hasItem(Items.FLINT_AND_STEEL) && !mod.getItemStorage().hasItem(Items.FIRE_CHARGE)) {
setDebugState("Getting flint & steel");
_progressChecker.reset();
return TaskCatalogue.getItemTask(Items.FLINT_AND_STEEL, 1);
}
boolean needsToLookForPortal = _portalOrigin == null;
if (needsToLookForPortal) {
_progressChecker.reset();
// Get water before searching, just for convenience.
if (!mod.getItemStorage().hasItem(Items.WATER_BUCKET)) {
setDebugState("Getting water");
_progressChecker.reset();
return TaskCatalogue.getItemTask(Items.WATER_BUCKET, 1);
}
boolean foundSpot = false;
if (_firstSearch || _lavaSearchTimer.elapsed()) {
_firstSearch = false;
_lavaSearchTimer.reset();
Debug.logMessage("(Searching for lava lake with portalable spot nearby...)");
BlockPos lavaPos = findLavaLake(mod, mod.getPlayer().getBlockPos());
if (lavaPos != null) {
// We have a lava lake, set our portal origin!
BlockPos foundPortalRegion = getPortalableRegion(mod, lavaPos, mod.getPlayer().getBlockPos(), new Vec3i(-1, 0, 0), PORTALABLE_REGION_SIZE, 20);
if (foundPortalRegion == null) {
Debug.logWarning("Failed to find portalable region nearby. Consider increasing the search timeout range");
} else {
_portalOrigin = foundPortalRegion.add(PORTAL_ORIGIN_RELATIVE_TO_REGION);
foundSpot = true;
}
} else {
Debug.logMessage("(lava lake not found)");
}
}
if (!foundSpot) {
setDebugState("(timeout: Looking for lava lake)");
return new TimeoutWanderTask(100);
}
}
// We have a portal, now build it.
for (Vec3i framePosRelative : PORTAL_FRAME) {
BlockPos framePos = _portalOrigin.add(framePosRelative);
Block frameBlock = mod.getWorld().getBlockState(framePos).getBlock();
if (frameBlock == Blocks.OBSIDIAN) {
// Already satisfied, clear water above if need be.
BlockPos waterCheck = framePos.up();
if (mod.getWorld().getBlockState(waterCheck).getBlock() == Blocks.WATER && WorldHelper.isSourceBlock(mod, waterCheck, true)) {
setDebugState("Clearing water from cast");
return new ClearLiquidTask(waterCheck);
}
continue;
}
// Get lava early so placing it is faster
if (!mod.getItemStorage().hasItem(Items.LAVA_BUCKET) && frameBlock != Blocks.LAVA) {
setDebugState("Collecting lava");
_progressChecker.reset();
return _collectLavaTask;
}
// We need to place obsidian here.
return new PlaceObsidianBucketTask(framePos);
}
// Now, clear the inside.
for (Vec3i offs : PORTAL_INTERIOR) {
BlockPos p = _portalOrigin.add(offs);
assert MinecraftClient.getInstance().world != null;
if (!MinecraftClient.getInstance().world.getBlockState(p).isAir()) {
setDebugState("Clearing inside of portal");
_currentDestroyTarget = p;
return null;
//return new DestroyBlockTask(p);
}
}
setDebugState("Flinting and Steeling");
// Flint and steel it baby
return new InteractWithBlockTask(new ItemTarget(new Item[]{Items.FLINT_AND_STEEL, Items.FIRE_CHARGE}, 1), Direction.UP, _portalOrigin.down(), true);
}
@Override
protected void onStop(AltoClef mod, Task interruptTask) {
mod.getBlockTracker().stopTracking(Blocks.LAVA);
mod.getBehaviour().pop();
}
@Override
protected boolean isEqual(Task other) {
return other instanceof ConstructNetherPortalBucketTask;
}
@Override
protected String toDebugString() {
return "Construct Nether Portal";
}
private BlockPos findLavaLake(AltoClef mod, BlockPos playerPos) {
HashSet<BlockPos> alreadyExplored = new HashSet<>();
double nearestSqDistance = Double.POSITIVE_INFINITY;
BlockPos nearestLake = null;
for (BlockPos pos : mod.getBlockTracker().getKnownLocations(Blocks.LAVA)) {
if (alreadyExplored.contains(pos)) continue;
double sqDist = playerPos.getSquaredDistance(pos);
if (sqDist < nearestSqDistance) {
int depth = getNumberOfBlocksAdjacent(alreadyExplored, pos);
if (depth != 0) {
Debug.logMessage("Found with depth " + depth);
if (depth >= 12) {
nearestSqDistance = sqDist;
nearestLake = pos;
}
}
}
}
return nearestLake;
}
// Used to flood-scan for blocks of lava.
private int getNumberOfBlocksAdjacent(HashSet<BlockPos> alreadyExplored, BlockPos origin) {
// Base case: We already explored this one
if (alreadyExplored.contains(origin)) return 0;
alreadyExplored.add(origin);
// Base case: We hit a non-full lava block.
assert MinecraftClient.getInstance().world != null;
BlockState s = MinecraftClient.getInstance().world.getBlockState(origin);
if (s.getBlock() != Blocks.LAVA) {
return 0;
} else {
// We may not be a full lava block
if (!s.getFluidState().isStill()) return 0;
int level = s.getFluidState().getLevel();
//Debug.logMessage("TEST LEVEL: " + level + ", " + height);
// Only accept FULL SOURCE BLOCKS
if (level != 8) return 0;
}
BlockPos[] toCheck = new BlockPos[]{origin.north(), origin.south(), origin.east(), origin.west(), origin.up(), origin.down()};
int bonus = 0;
for (BlockPos check : toCheck) {
// This block is new! Explore out from it.
bonus += getNumberOfBlocksAdjacent(alreadyExplored, check);
}
return bonus + 1;
}
// Get a region that a portal can fit into
private BlockPos getPortalableRegion(AltoClef mod, BlockPos lava, BlockPos playerPos, Vec3i sizeOffset, Vec3i sizeAllocation, int timeoutRange) {
Vec3i[] directions = new Vec3i[]{new Vec3i(1, 0, 0), new Vec3i(-1, 0, 0), new Vec3i(0, 0, 1), new Vec3i(0, 0, -1)};
double minDistanceToPlayer = Double.POSITIVE_INFINITY;
BlockPos bestPos = null;
for (Vec3i direction : directions) {
// Inch along
for (int offs = 1; offs < timeoutRange; ++offs) {
Vec3i offset = new Vec3i(direction.getX() * offs, direction.getY() * offs, direction.getZ() * offs);
boolean found = true;
boolean solidFound = false;
// check for collision with lava in box
// We have an extra buffer to make sure we never break a block NEXT to lava.
moveAlongLine:
for (int dx = -1; dx < sizeAllocation.getX() + 1; ++dx) {
for (int dz = -1; dz < sizeAllocation.getZ() + 1; ++dz) {
for (int dy = -1; dy < sizeAllocation.getY(); ++dy) {
BlockPos toCheck = lava.add(offset).add(sizeOffset).add(dx, dy, dz);
assert MinecraftClient.getInstance().world != null;
BlockState state = MinecraftClient.getInstance().world.getBlockState(toCheck);
if (state.getBlock() == Blocks.LAVA || state.getBlock() == Blocks.WATER || state.getBlock() == Blocks.BEDROCK) {
found = false;
break moveAlongLine;
}
// Also check for at least 1 solid block for us to place on...
if (dy <= 1 && !solidFound && WorldHelper.isSolid(mod, toCheck)) {
solidFound = true;
}
}
}
}
// Check for solid ground at least somewhere
if (!solidFound) {
break;
}
if (found) {
BlockPos foundBoxCorner = lava.add(offset).add(sizeOffset);
double sqDistance = foundBoxCorner.getSquaredDistance(playerPos);
if (sqDistance < minDistanceToPlayer) {
minDistanceToPlayer = sqDistance;
bestPos = foundBoxCorner;
}
break;
}
}
}
return bestPos;
}
}
| 412 | 0.966458 | 1 | 0.966458 | game-dev | MEDIA | 0.991913 | game-dev | 0.992179 | 1 | 0.992179 |
chromealex/ME.BECS | 5,663 | Runtime/Core/Systems/Systems.Graph.Add.cs | namespace ME.BECS {
public struct StaticSystemTypes {
public static readonly Unity.Burst.SharedStatic<uint> counterBurst = Unity.Burst.SharedStatic<uint>.GetOrCreate<StaticSystemTypes>();
public static ref uint counter => ref counterBurst.Data;
}
public struct StaticSystemTypesId<T> where T : unmanaged {
public static readonly Unity.Burst.SharedStatic<uint> value = Unity.Burst.SharedStatic<uint>.GetOrCreate<StaticSystemTypesId<T>>();
}
public struct StaticSystemTypesNull<T> where T : unmanaged {
public static readonly Unity.Burst.SharedStatic<T> value = Unity.Burst.SharedStatic<T>.GetOrCreate<StaticSystemTypesNull<T>>();
}
public struct StaticSystemTypes<T> where T : unmanaged {
public static ref T nullValue {
get {
StaticSystemTypesNull<T>.value.Data = default;
return ref StaticSystemTypesNull<T>.value.Data;
}
}
public static ref uint typeId => ref StaticSystemTypesId<T>.value.Data;
public static void Validate() {
if (typeId == 0u) {
StaticSystemTypes<T>.typeId = ++StaticSystemTypes.counter;
}
}
}
public static unsafe class SystemsGraphExtensions {
public static ref T GetSystem<T>(this ref SystemGroup graph, out bool found) where T : unmanaged, ISystem {
found = false;
var typeId = StaticSystemTypes<T>.typeId;
for (int i = 0; i < graph.index; ++i) {
var node = graph.nodes[i];
if (node.data.ptr->graph.ptr != null) {
ref var sys = ref (*node.data.ptr->graph.ptr).GetSystem<T>(out found);
if (found == true) return ref sys;
} else if (node.data.ptr->systemData.ptr != null) {
if (node.data.ptr->systemTypeId == typeId) {
found = true;
return ref *(T*)node.data.ptr->systemData.ptr;
}
}
}
return ref StaticSystemTypes<T>.nullValue;
}
private static readonly object[] addDirectParametersCache = new object[3];
private static readonly System.Reflection.MethodInfo addDirectMethodCache = typeof(SystemsGraphExtensions).GetMethod(nameof(AddDirect));
public static SystemHandle Add(this ref SystemGroup graph, ISystem system, in SystemHandle dependsOn = default) {
var type = system.GetType();
var gMethod = addDirectMethodCache.MakeGenericMethod(type);
addDirectParametersCache[0] = graph;
addDirectParametersCache[1] = system;
addDirectParametersCache[2] = dependsOn;
return (SystemHandle)gMethod.Invoke(null, addDirectParametersCache);
}
public static SystemHandle Add(this ref SystemGroup graph, in SystemGroup innerGraph, in SystemHandle dependsOn = default) {
var node = Node.Create(innerGraph);
graph.RegisterNode(node);
if (dependsOn.IsValid() == false) {
// No dependencies
graph.rootNode.ptr->AddChild(node, graph.rootNode);
} else {
// Has dependencies
var depNode = graph.GetNode(dependsOn);
if (depNode.ptr->deps.ptr != null) {
// Combined dependencies
for (int i = 0; i < depNode.ptr->depsIndex; ++i) {
var dep = depNode.ptr->deps[i];
dep.data.ptr->AddChild(node, dep.data);
}
} else {
// Single dependency
depNode.ptr->AddChild(node, depNode);
}
}
Journal.AddSystem(Context.world.id, node.ptr->name);
return SystemHandle.Create(node.ptr->id);
}
public static SystemHandle AddDirect<T>(SystemGroup graph, T system, SystemHandle dependsOn) where T : unmanaged, ISystem {
return Add<T>(ref graph, system, dependsOn);
}
public static SystemHandle Add<T>(this ref SystemGroup graph, in SystemHandle dependsOn = default) where T : unmanaged, ISystem {
return Add<T>(ref graph, default, dependsOn);
}
public static SystemHandle Add<T>(this ref SystemGroup graph, in T system, in SystemHandle dependsOn = default) where T : unmanaged, ISystem {
var node = Node.CreateMethods(system);
graph.RegisterNode(node);
node.ptr->name = typeof(T).Name;
if (dependsOn.IsValid() == false) {
// No dependencies
graph.rootNode.ptr->AddChild(node, graph.rootNode);
} else {
// Has dependencies
var depNode = graph.GetNode(dependsOn);
if (depNode.ptr->deps.ptr != null) {
// Combined dependencies
for (int i = 0; i < depNode.ptr->depsIndex; ++i) {
var dep = depNode.ptr->deps[i];
dep.data.ptr->AddChild(node, dep.data);
}
} else {
// Single dependency
depNode.ptr->AddChild(node, depNode);
}
}
Journal.AddSystem(Context.world.id, node.ptr->name);
return SystemHandle.Create(node.ptr->id);
}
}
} | 412 | 0.9182 | 1 | 0.9182 | game-dev | MEDIA | 0.227824 | game-dev | 0.861894 | 1 | 0.861894 |
rexrainbow/phaser3-rex-notes | 3,191 | plugins/math/raycaster/Raycaster.js | import Obstacles from './Obstacles.js';
import GetLineToPolygon from './GetLineToPolygon.js';
const GetValue = Phaser.Utils.Objects.GetValue;
const Line = Phaser.Geom.Line;
const SetToAngle = Phaser.Geom.Line.SetToAngle;
const ReflectAngle = Phaser.Geom.Line.ReflectAngle;
class Reflection {
constructor(config) {
this.obstacles = new Obstacles();
this.ray = new Line();
this.setMaxRayLength(GetValue(config, 'maxRayLength', 10000));
this.result = {
hit: false,
x: 0, y: 0,
segment: new Line(),
polygon: null,
gameObject: null,
reflectAngle: 0
};
}
destroy() {
this.obstacles.clear();
this.obstacles = null;
this.ray = null;
this.result = null;
}
setMaxRayLength(length) {
this.maxRayLength = length;
return this;
}
addObstacle(gameObject, polygon) {
if (Array.isArray(gameObject)) {
var gameObjects = gameObject;
for (var i = 0, cnt = gameObjects.length; i < cnt; i++) {
this.obstacles.add(gameObjects[i]);
}
} else {
this.obstacles.add(gameObject, polygon);
}
return this;
}
clearObstacle() {
this.obstacles.clear();
return this;
}
removeObstacle(gameObject) {
if (Array.isArray(gameObject)) {
var gameObjects = gameObject;
for (var i = 0, cnt = gameObjects.length; i < cnt; i++) {
this.obstacles.remove(gameObjects[i]);
}
} else {
this.obstacles.remove(gameObject);
}
return this;
}
updateObstacle(gameObject, polygon) {
if (Array.isArray(gameObject)) {
var gameObjects = gameObject;
for (var i = 0, cnt = gameObjects.length; i < cnt; i++) {
this.obstacles.update(gameObjects[i]);
}
} else {
this.obstacles.update(gameObject, polygon);
}
return this;
}
hitTest() {
var result = GetLineToPolygon(this.ray, this.obstacles.polygons, true);
if (result) {
this.ray.x2 = result.x;
this.ray.y2 = result.y;
this.result.hit = true;
this.result.x = result.x;
this.result.y = result.y;
var obstacle = this.obstacles.get(result.shapeIndex);
this.result.polygon = obstacle.polygon;
this.result.gameObject = obstacle.gameObject;
var points = this.result.polygon.points,
segIndex = result.segIndex,
p0 = points[segIndex],
p1 = points[segIndex + 1];
var segment = this.result.segment;
segment.setTo(p0.x, p0.y, p1.x, p1.y);
this.result.reflectAngle = ReflectAngle(this.ray, segment);
} else {
this.result.hit = false;
}
return (result) ? this.result : false;
}
rayToward(x, y, angle) {
SetToAngle(this.ray, x, y, angle, this.maxRayLength);
return this.hitTest();
}
}
export default Reflection; | 412 | 0.792609 | 1 | 0.792609 | game-dev | MEDIA | 0.718402 | game-dev,web-frontend | 0.950804 | 1 | 0.950804 |
webbukkit/dynmap | 72,612 | spigot/src/main/java/org/dynmap/bukkit/DynmapPlugin.java | package org.dynmap.bukkit;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import org.bstats.bukkit.Metrics;
import org.bstats.charts.CustomChart;
import org.bstats.json.JsonObjectBuilder;
import org.bstats.json.JsonObjectBuilder.JsonObject;
import org.bukkit.*;
import org.bukkit.attribute.Attribute;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.block.Sign;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockFadeEvent;
import org.bukkit.event.block.BlockFormEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockGrowEvent;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.block.BlockPistonExtendEvent;
import org.bukkit.event.block.BlockPistonRetractEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.BlockRedstoneEvent;
import org.bukkit.event.block.BlockSpreadEvent;
import org.bukkit.event.block.LeavesDecayEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerBedLeaveEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.event.world.ChunkPopulateEvent;
import org.bukkit.event.world.SpawnChangeEvent;
import org.bukkit.event.world.StructureGrowEvent;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.event.world.WorldUnloadEvent;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionDefault;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffectType;
import org.dynmap.DynmapAPI;
import org.dynmap.DynmapChunk;
import org.dynmap.DynmapCommonAPIListener;
import org.dynmap.DynmapCore;
import org.dynmap.DynmapLocation;
import org.dynmap.DynmapWebChatEvent;
import org.dynmap.DynmapWorld;
import org.dynmap.Log;
import org.dynmap.MapManager;
import org.dynmap.MapType;
import org.dynmap.PlayerList;
import org.dynmap.bukkit.helper.BukkitVersionHelper;
import org.dynmap.bukkit.helper.BukkitWorld;
import org.dynmap.bukkit.helper.SnapshotCache;
import org.dynmap.bukkit.permissions.BukkitPermissions;
import org.dynmap.bukkit.permissions.NijikokunPermissions;
import org.dynmap.bukkit.permissions.OpPermissions;
import org.dynmap.bukkit.permissions.PEXPermissions;
import org.dynmap.bukkit.permissions.PermBukkitPermissions;
import org.dynmap.bukkit.permissions.GroupManagerPermissions;
import org.dynmap.bukkit.permissions.PermissionProvider;
import org.dynmap.bukkit.permissions.VaultPermissions;
import org.dynmap.bukkit.permissions.bPermPermissions;
import org.dynmap.bukkit.permissions.LuckPermsPermissions;
import org.dynmap.bukkit.permissions.LuckPerms5Permissions;
import org.dynmap.common.BiomeMap;
import org.dynmap.common.DynmapCommandSender;
import org.dynmap.common.DynmapPlayer;
import org.dynmap.common.DynmapServerInterface;
import org.dynmap.common.chunk.GenericChunkCache;
import org.dynmap.common.DynmapListenerManager.EventType;
import org.dynmap.common.chunk.GenericMapChunkCache;
import org.dynmap.hdmap.HDMap;
import org.dynmap.markers.MarkerAPI;
import org.dynmap.modsupport.ModSupportImpl;
import org.dynmap.utils.MapChunkCache;
import org.dynmap.utils.Polygon;
import org.dynmap.utils.VisibilityLimit;
public class DynmapPlugin extends JavaPlugin implements DynmapAPI {
private DynmapCore core;
private PermissionProvider permissions;
private String version;
public PlayerList playerList;
private MapManager mapManager;
public static DynmapPlugin plugin;
public PluginManager pm;
private Metrics metrics;
private BukkitEnableCoreCallback enabCoreCB = new BukkitEnableCoreCallback();
private Method ismodloaded;
private Method instance;
private Method getindexedmodlist;
private Method getversion;
private HashMap<String, BukkitWorld> world_by_name = new HashMap<String, BukkitWorld>();
private HashSet<String> modsused = new HashSet<String>();
// TPS calculator
private double tps;
private long lasttick;
private long perTickLimit;
private long cur_tick_starttime;
private long avgticklen = 50000000;
private int chunks_in_cur_tick = 0;
private long cur_tick;
private long prev_tick;
private HashMap<String, Integer> sortWeights = new HashMap<String, Integer>();
/* Lookup cache */
private World last_world;
private BukkitWorld last_bworld;
private BukkitVersionHelper helper;
private final BukkitWorld getWorldByName(String name) {
if((last_world != null) && (last_world.getName().equals(name))) {
return last_bworld;
}
return world_by_name.get(name);
}
private final BukkitWorld getWorld(World w) {
if(last_world == w) {
return last_bworld;
}
BukkitWorld bw = world_by_name.get(w.getName());
if(bw == null) {
bw = new BukkitWorld(w);
world_by_name.put(w.getName(), bw);
}
else if(bw.isLoaded() == false) {
bw.setWorldLoaded(w);
}
last_world = w;
last_bworld = bw;
return bw;
}
final void removeWorld(World w) {
world_by_name.remove(w.getName());
if(w == last_world) {
last_world = null;
last_bworld = null;
}
}
// Nonblocking thread safety
private static final AtomicBoolean tryNativeId = new AtomicBoolean(true);
@SuppressWarnings("deprecation")
private static final int getBlockIdFromMaterial(Material material) {
if (tryNativeId.get()) {
try {
return material.getId();
} catch (NoSuchMethodError e) {
// We failed once, no need to retry
tryNativeId.set(false);
} catch (java.lang.IllegalArgumentException e) {
// Ignore this entirely, as modern materials throw
// java.lang.IllegalArgumentException: Cannot get ID of Modern Material
}
}
// We're living in a world where numerical IDs have been phased out completely.
// Let's return *some* number, because we need one.
// Also in that case we are adding a constant to ensure we're not conflicting with the
// actual IDs
return material.ordinal() + (1 << 20);
}
private static final int getBlockIdFromBlock(Block block) {
return getBlockIdFromMaterial(block.getType());
}
private class BukkitEnableCoreCallback extends DynmapCore.EnableCoreCallbacks {
@Override
public void configurationLoaded() {
File st = new File(core.getDataFolder(), "renderdata/spout-texture.txt");
if(st.exists()) {
st.delete();
}
}
}
private static class BlockToCheck {
Location loc;
int typeid;
byte data;
String trigger;
};
private LinkedList<BlockToCheck> blocks_to_check = null;
private LinkedList<BlockToCheck> blocks_to_check_accum = new LinkedList<BlockToCheck>();
public DynmapPlugin() {
plugin = this;
try {
Class<?> c = Class.forName("cpw.mods.fml.common.Loader");
ismodloaded = c.getMethod("isModLoaded", String.class);
instance = c.getMethod("instance");
getindexedmodlist = c.getMethod("getIndexedModList");
c = Class.forName("cpw.mods.fml.common.ModContainer");
getversion = c.getMethod("getVersion");
} catch (NoSuchMethodException nsmx) {
} catch (ClassNotFoundException e) {
}
}
private boolean banBrokenMsg = false;
/**
* Server access abstraction class
*/
public class BukkitServer extends DynmapServerInterface {
@Override
public int getBlockIDAt(String wname, int x, int y, int z) {
World w = getServer().getWorld(wname);
if((w != null) && w.isChunkLoaded(x >> 4, z >> 4)) {
return getBlockIdFromBlock(w.getBlockAt(x, y, z));
}
return -1;
}
@Override
public int isSignAt(String wname, int x, int y, int z) {
World w = getServer().getWorld(wname);
if((w != null) && w.isChunkLoaded(x >> 4, z >> 4)) {
Block b = w.getBlockAt(x, y, z);
BlockState s = b.getState();
if (s instanceof Sign) {
return 1;
} else {
return 0;
}
}
return -1;
}
@Override
public void scheduleServerTask(Runnable run, long delay) {
getServer().getScheduler().scheduleSyncDelayedTask(DynmapPlugin.this, run, delay);
}
@Override
public DynmapPlayer[] getOnlinePlayers() {
Player[] players = helper.getOnlinePlayers();
DynmapPlayer[] dplay = new DynmapPlayer[players.length];
for(int i = 0; i < players.length; i++)
dplay[i] = new BukkitPlayer(players[i]);
return dplay;
}
@Override
public void reload() {
PluginManager pluginManager = getServer().getPluginManager();
pluginManager.disablePlugin(DynmapPlugin.this);
pluginManager.enablePlugin(DynmapPlugin.this);
}
@Override
public DynmapPlayer getPlayer(String name) {
Player p = getServer().getPlayerExact(name);
if(p != null) {
return new BukkitPlayer(p);
}
return null;
}
@Override
public Set<String> getIPBans() {
return getServer().getIPBans();
}
@Override
public <T> Future<T> callSyncMethod(Callable<T> task) {
if(DynmapPlugin.this.isEnabled())
return getServer().getScheduler().callSyncMethod(DynmapPlugin.this, task);
else
return null;
}
private boolean noservername = false;
@Override
public String getServerName() {
try {
if (!noservername)
return getServer().getServerName();
} catch (NoSuchMethodError x) { // Missing in 1.14 spigot - no idea why removed...
noservername = true;
}
return getServer().getMotd();
}
private boolean isBanned(OfflinePlayer p) {
try {
if ((!banBrokenMsg) && (p != null) && p.isBanned()) {
return true;
}
} catch (Exception x) {
Log.severe("Server error - broken Ban API - ban check disabled - this may allow banned players to log in!!!", x);
Log.severe("REPORT ERROR TO "+ Bukkit.getServer().getVersion() + " DEVELOPERS - THIS IS NOT DYNMAP ISSUE");
banBrokenMsg = true;
}
return false;
}
@Override
public boolean isPlayerBanned(String pid) {
OfflinePlayer p = getServer().getOfflinePlayer(pid);
return isBanned(p);
}
@Override
public boolean isServerThread() {
return Bukkit.getServer().isPrimaryThread();
}
@Override
public String stripChatColor(String s) {
return ChatColor.stripColor(s);
}
private Set<EventType> registered = new HashSet<EventType>();
@Override
public boolean requestEventNotification(EventType type) {
if(registered.contains(type))
return true;
switch(type) {
case WORLD_LOAD:
case WORLD_UNLOAD:
/* Already called for normal world activation/deactivation */
break;
case WORLD_SPAWN_CHANGE:
pm.registerEvents(new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onSpawnChange(SpawnChangeEvent evt) {
BukkitWorld w = getWorld(evt.getWorld());
core.listenerManager.processWorldEvent(EventType.WORLD_SPAWN_CHANGE, w);
}
}, DynmapPlugin.this);
break;
case PLAYER_JOIN:
case PLAYER_QUIT:
/* Already handled */
break;
case PLAYER_BED_LEAVE:
pm.registerEvents(new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onPlayerBedLeave(PlayerBedLeaveEvent evt) {
DynmapPlayer p = new BukkitPlayer(evt.getPlayer());
core.listenerManager.processPlayerEvent(EventType.PLAYER_BED_LEAVE, p);
}
}, DynmapPlugin.this);
break;
case PLAYER_CHAT:
pm.registerEvents(new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onPlayerChat(AsyncPlayerChatEvent evt) {
final Player p = evt.getPlayer();
final String msg = evt.getMessage();
getServer().getScheduler().scheduleSyncDelayedTask(DynmapPlugin.this, new Runnable() {
public void run() {
DynmapPlayer dp = null;
if(p != null)
dp = new BukkitPlayer(p);
core.listenerManager.processChatEvent(EventType.PLAYER_CHAT, dp, msg);
}
});
}
}, DynmapPlugin.this);
break;
case BLOCK_BREAK:
pm.registerEvents(new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onBlockBreak(BlockBreakEvent evt) {
Block b = evt.getBlock();
if(b == null) return; /* Work around for stupid mods.... */
Location l = b.getLocation();
core.listenerManager.processBlockEvent(EventType.BLOCK_BREAK, b.getType().name(),
getWorld(l.getWorld()).getName(), l.getBlockX(), l.getBlockY(), l.getBlockZ());
}
}, DynmapPlugin.this);
break;
case SIGN_CHANGE:
pm.registerEvents(new Listener() {
@EventHandler(priority=EventPriority.HIGHEST, ignoreCancelled=true)
public void onSignChange(SignChangeEvent evt) {
Block b = evt.getBlock();
Location l = b.getLocation();
String[] lines = evt.getLines(); /* Note: changes to this change event - intentional */
DynmapPlayer dp = null;
Player p = evt.getPlayer();
if(p != null) dp = new BukkitPlayer(p);
core.listenerManager.processSignChangeEvent(EventType.SIGN_CHANGE, b.getType().name(),
getWorld(l.getWorld()).getName(), l.getBlockX(), l.getBlockY(), l.getBlockZ(), lines, dp);
for (int i = 0; i < 4; i++) {
evt.setLine(i, lines[i]);
}
}
}, DynmapPlugin.this);
break;
default:
Log.severe("Unhandled event type: " + type);
return false;
}
registered.add(type);
return true;
}
@Override
public boolean sendWebChatEvent(String source, String name, String msg) {
DynmapWebChatEvent evt = new DynmapWebChatEvent(source, name, msg);
getServer().getPluginManager().callEvent(evt);
return ((evt.isCancelled() == false) && (evt.isProcessed() == false));
}
@Override
public void broadcastMessage(String msg) {
getServer().broadcastMessage(msg);
}
@Override
public String[] getBiomeIDs() {
BiomeMap[] b = BiomeMap.values();
String[] bname = new String[b.length];
for(int i = 0; i < bname.length; i++)
bname[i] = b[i].toString();
return bname;
}
@Override
public double getCacheHitRate() {
return helper.useGenericCache() ? BukkitVersionHelper.gencache.getHitRate() : SnapshotCache.sscache.getHitRate();
}
@Override
public void resetCacheStats() {
if (helper.useGenericCache()) {
BukkitVersionHelper.gencache.resetStats();
}
else {
SnapshotCache.sscache.resetStats();
}
}
@Override
public DynmapWorld getWorldByName(String wname) {
return DynmapPlugin.this.getWorldByName(wname);
}
@Override
public DynmapPlayer getOfflinePlayer(String name) {
OfflinePlayer op = getServer().getOfflinePlayer(name);
if(op != null) {
return new BukkitPlayer(op);
}
return null;
}
@Override
public Set<String> checkPlayerPermissions(String player, Set<String> perms) {
OfflinePlayer p = getServer().getOfflinePlayer(player);
if (isBanned(p))
return new HashSet<String>();
Set<String> rslt = permissions.hasOfflinePermissions(player, perms);
if (rslt == null) {
rslt = new HashSet<String>();
if(p.isOp()) {
rslt.addAll(perms);
}
}
return rslt;
}
@Override
public boolean checkPlayerPermission(String player, String perm) {
OfflinePlayer p = getServer().getOfflinePlayer(player);
if (isBanned(p))
return false;
boolean rslt = permissions.hasOfflinePermission(player, perm);
return rslt;
}
/**
* Render processor helper - used by code running on render threads to request chunk snapshot cache from server/sync thread
*/
@Override
public MapChunkCache createMapChunkCache(DynmapWorld w, List<DynmapChunk> chunks,
boolean blockdata, boolean highesty, boolean biome, boolean rawbiome) {
MapChunkCache c = w.getChunkCache(chunks);
if(c == null) { /* Can fail if not currently loaded */
return null;
}
if(w.visibility_limits != null) {
for(VisibilityLimit limit: w.visibility_limits) {
c.setVisibleRange(limit);
}
c.setHiddenFillStyle(w.hiddenchunkstyle);
}
if(w.hidden_limits != null) {
for(VisibilityLimit limit: w.hidden_limits) {
c.setHiddenRange(limit);
}
c.setHiddenFillStyle(w.hiddenchunkstyle);
}
if(c.setChunkDataTypes(blockdata, biome, highesty, rawbiome) == false) {
Log.severe("CraftBukkit build does not support biome APIs");
}
if(chunks.size() == 0) { /* No chunks to get? */
c.loadChunks(0);
return c;
}
final MapChunkCache cc = c;
while(!cc.isDoneLoading()) {
if (BukkitVersionHelper.helper.isUnsafeAsync()) {
Future<Boolean> f = core.getServer().callSyncMethod(new Callable<Boolean>() {
public Boolean call() throws Exception {
boolean exhausted = true;
if (prev_tick != cur_tick) {
prev_tick = cur_tick;
cur_tick_starttime = System.nanoTime();
}
if (chunks_in_cur_tick > 0) {
boolean done = false;
while (!done) {
int cnt = chunks_in_cur_tick;
if (cnt > 5) cnt = 5;
chunks_in_cur_tick -= cc.loadChunks(cnt);
exhausted = (chunks_in_cur_tick == 0) || ((System.nanoTime() - cur_tick_starttime) > perTickLimit);
done = exhausted || cc.isDoneLoading();
}
}
return exhausted;
}
});
if (f == null) {
return null;
}
Boolean delay;
try {
delay = f.get();
} catch (CancellationException cx) {
return null;
} catch (InterruptedException cx) {
return null;
} catch (ExecutionException ex) {
Log.severe("Exception while fetching chunks: ", ex.getCause());
return null;
} catch (Exception ix) {
Log.severe(ix);
return null;
}
if ((delay != null) && delay.booleanValue()) {
try {
Thread.sleep(25);
} catch (InterruptedException ix) {
}
}
} else {
if (prev_tick != cur_tick) {
prev_tick = cur_tick;
cur_tick_starttime = System.nanoTime();
}
if (cc instanceof GenericMapChunkCache) {
((GenericMapChunkCache) cc).loadChunksAsync();
} else {
cc.loadChunks(Integer.MAX_VALUE);
}
}
}
/* If cancelled due to world unload return nothing */
if(w.isLoaded() == false)
return null;
return c;
}
@Override
public int getMaxPlayers() {
return getServer().getMaxPlayers();
}
@Override
public int getCurrentPlayers() {
return helper.getOnlinePlayers().length;
}
@Override
public boolean isModLoaded(String name) {
if(ismodloaded != null) {
try {
Object rslt =ismodloaded.invoke(null, name);
if(rslt instanceof Boolean) {
if(((Boolean)rslt).booleanValue()) {
modsused.add(name);
return true;
}
}
} catch (IllegalArgumentException iax) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
return false;
}
@Override
public String getModVersion(String name) {
if((instance != null) && (getindexedmodlist != null) && (getversion != null)) {
try {
Object inst = instance.invoke(null);
Map<?,?> modmap = (Map<?,?>) getindexedmodlist.invoke(inst);
Object mod = modmap.get(name);
if (mod != null) {
return (String) getversion.invoke(mod);
}
} catch (IllegalArgumentException iax) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
return null;
}
@Override
public double getServerTPS() {
return tps;
}
@Override
public String getServerIP() {
return Bukkit.getServer().getIp();
}
@Override
public Map<Integer, String> getBlockIDMap() {
String[] bsn = helper.getBlockNames();
HashMap<Integer, String> map = new HashMap<Integer, String>();
for (int i = 0; i < bsn.length; i++) {
if (bsn[i] != null) {
if (bsn[i].indexOf(':') < 0)
map.put(i, "minecraft:" + bsn[i]);
else
map.put(i, bsn[i]);
}
}
return map;
}
}
/**
* Player access abstraction class
*/
public class BukkitPlayer extends BukkitCommandSender implements DynmapPlayer {
private Player player;
private OfflinePlayer offplayer;
private String skinurl;
private UUID uuid;
public BukkitPlayer(Player p) {
super(p);
player = p;
offplayer = p.getPlayer();
uuid = p.getUniqueId();
skinurl = helper.getSkinURL(p);
}
public BukkitPlayer(OfflinePlayer p) {
super(null);
offplayer = p;
}
@Override
public boolean isConnected() {
return offplayer.isOnline();
}
@Override
public String getName() {
return offplayer.getName();
}
@Override
public String getDisplayName() {
if(player != null)
return player.getDisplayName();
else
return offplayer.getName();
}
@Override
public boolean isOnline() {
return offplayer.isOnline();
}
@Override
public DynmapLocation getLocation() {
if(player == null) {
return null;
}
Location loc = player.getEyeLocation(); // Use eye location, since we show head
return toLoc(loc);
}
@Override
public String getWorld() {
if(player == null) {
return null;
}
World w = player.getWorld();
if(w != null)
return DynmapPlugin.this.getWorld(w).getName();
return null;
}
@Override
public InetSocketAddress getAddress() {
if(player != null)
return player.getAddress();
return null;
}
@Override
public boolean isSneaking() {
if(player != null)
return player.isSneaking();
return false;
}
@Override
public double getHealth() {
if(player != null) {
return Math.ceil(2.0 * player.getHealth() / player.getMaxHealth() * player.getHealthScale()) / 2.0;
}
else
return 0;
}
@Override
public int getArmorPoints() {
if(player != null)
return (int) player.getAttribute(Attribute.GENERIC_ARMOR).getValue();
else
return 0;
}
@Override
public DynmapLocation getBedSpawnLocation() {
Location loc = offplayer.getBedSpawnLocation();
if(loc != null) {
return toLoc(loc);
}
return null;
}
@Override
public long getLastLoginTime() {
return offplayer.getLastPlayed();
}
@Override
public long getFirstLoginTime() {
return offplayer.getFirstPlayed();
}
@Override
public boolean isInvisible() {
if(player != null) {
return player.hasPotionEffect(PotionEffectType.INVISIBILITY);
}
return false;
}
@Override
public boolean isSpectator() {
if(player != null) {
return player.getGameMode() == GameMode.SPECTATOR;
}
return false;
}
@Override
public int getSortWeight() {
Integer wt = sortWeights.get(getName());
if (wt != null)
return wt;
return 0;
}
@Override
public void setSortWeight(int wt) {
if (wt == 0) {
sortWeights.remove(getName());
}
else {
sortWeights.put(getName(), wt);
}
}
@Override
public String getSkinURL() {
return skinurl;
}
@Override
public UUID getUUID() {
return uuid;
}
/**
* Send title and subtitle text (called from server thread)
*/
@Override
public void sendTitleText(String title, String subtitle, int fadeInTicks, int stayTicks, int fadeOutTIcks) {
if (player != null) {
helper.sendTitleText(player, title, subtitle, fadeInTicks, stayTicks, fadeOutTIcks);
}
}
}
/* Handler for generic console command sender */
public class BukkitCommandSender implements DynmapCommandSender {
private CommandSender sender;
public BukkitCommandSender(CommandSender send) {
sender = send;
}
@Override
public boolean hasPrivilege(String privid) {
if(sender != null)
return permissions.has(sender, privid);
return false;
}
@Override
public void sendMessage(String msg) {
if(sender != null)
sender.sendMessage(msg);
}
@Override
public boolean isConnected() {
if(sender != null)
return true;
return false;
}
@Override
public boolean isOp() {
if(sender != null)
return sender.isOp();
else
return false;
}
@Override
public boolean hasPermissionNode(String node) {
if (sender != null) {
return sender.hasPermission(node);
}
return false;
}
}
public void loadExtraBiomes(String mcver) {
int cnt = 0;
BiomeMap.loadWellKnownByVersion(mcver);
/* Find array of biomes in biomebase */
Object[] biomelist = helper.getBiomeBaseList();
//Log.info("biomelist length = " + biomelist.length);
/* Loop through list, skipping well known biomes */
for(int i = 0; i < biomelist.length; i++) {
Object bb = biomelist[i];
if(bb != null) {
String rl = helper.getBiomeBaseResourceLocsation(bb);
float tmp = helper.getBiomeBaseTemperature(bb);
float hum = helper.getBiomeBaseHumidity(bb);
int watermult = helper.getBiomeBaseWaterMult(bb);
Log.verboseinfo("biome[" + i + "]: hum=" + hum + ", tmp=" + tmp + ", mult=" + Integer.toHexString(watermult));
BiomeMap bmap = BiomeMap.NULL;
if (rl != null) { // If resource location, lookup by this
bmap = BiomeMap.byBiomeResourceLocation(rl);
}
else {
bmap = BiomeMap.byBiomeID(i);
}
if (bmap.isDefault() || (bmap == BiomeMap.NULL)) {
String id = helper.getBiomeBaseIDString(bb);
if (id == null) {
id = "BIOME_" + i;
}
bmap = new BiomeMap((rl != null) ? BiomeMap.NO_INDEX : i, id, tmp, hum, rl);
Log.verboseinfo("Add custom biome [" + bmap.toString() + "] (" + i + ") rl=" + rl);
//Log.info(String.format("rl=%s, bmap=%s", rl, bmap));
cnt++;
}
else {
bmap.setTemperature(tmp);
bmap.setRainfall(hum);
}
if (watermult != -1) {
bmap.setWaterColorMultiplier(watermult);
Log.verboseinfo("Set watercolormult for " + bmap.toString() + " (" + i + ") to " + Integer.toHexString(watermult));
}
bmap.setBiomeObject(bb);
}
}
if(cnt > 0) {
Log.info("Added " + cnt + " custom biome mappings");
}
}
@Override
public void onLoad() {
Log.setLogger(this.getLogger(), "");
helper = Helper.getHelper();
pm = this.getServer().getPluginManager();
ModSupportImpl.init();
}
@Override
public void onEnable() {
if(core != null){
if(core.getMarkerAPI() != null){
getLogger().info("Starting Scheduled Write Job (markerAPI).");
core.restartMarkerSaveJob();
}
}
if (helper == null) {
Log.info("Dynmap is disabled (unsupported platform)");
this.setEnabled(false);
return;
}
PluginDescriptionFile pdfFile = this.getDescription();
version = pdfFile.getVersion();
/* Get MC version */
String bukkitver = getServer().getVersion();
String mcver = "1.0.0";
int idx = bukkitver.indexOf("(MC: ");
if(idx > 0) {
mcver = bukkitver.substring(idx+5);
idx = mcver.indexOf(")");
if(idx > 0) mcver = mcver.substring(0, idx);
}
// Initialize block states
helper.initializeBlockStates();
/* Load extra biomes, if any */
loadExtraBiomes(mcver);
/* Set up player login/quit event handler */
registerPlayerLoginListener();
/* Build default permissions from our plugin */
Map<String, Boolean> perdefs = new HashMap<String, Boolean>();
List<Permission> pd = plugin.getDescription().getPermissions();
for(Permission p : pd) {
perdefs.put(p.getName(), p.getDefault() == PermissionDefault.TRUE);
}
permissions = PEXPermissions.create(getServer(), "dynmap");
if (permissions == null)
permissions = bPermPermissions.create(getServer(), "dynmap", perdefs);
if (permissions == null)
permissions = PermBukkitPermissions.create(getServer(), "dynmap", perdefs);
if (permissions == null)
permissions = NijikokunPermissions.create(getServer(), "dynmap");
if (permissions == null)
permissions = GroupManagerPermissions.create(getServer(), "dynmap");
if (permissions == null)
permissions = LuckPermsPermissions.create(getServer(), "dynmap");
if (permissions == null)
permissions = LuckPerms5Permissions.create(getServer(), "dynmap");
if (permissions == null)
permissions = VaultPermissions.create(this, "dynmap");
if (permissions == null)
permissions = BukkitPermissions.create("dynmap", perdefs);
if (permissions == null)
permissions = new OpPermissions(new String[] { "fullrender", "cancelrender", "radiusrender", "resetstats", "reload", "purgequeue", "pause", "ips-for-id", "ids-for-ip", "add-id-for-ip", "del-id-for-ip" });
/* Get and initialize data folder */
File dataDirectory = this.getDataFolder();
if(dataDirectory.exists() == false)
dataDirectory.mkdirs();
/* Instantiate core */
if(core == null)
core = new DynmapCore();
/* Inject dependencies */
core.setPluginJarFile(this.getFile());
core.setPluginVersion(version, "CraftBukkit");
core.setMinecraftVersion(mcver);
core.setDataFolder(dataDirectory);
core.setServer(new BukkitServer());
core.setBiomeNames(helper.getBiomeNames());
/* Load configuration */
if(!core.initConfiguration(enabCoreCB)) {
this.setEnabled(false);
return;
}
/* Skins support via SkinsRestorer */
SkinsRestorerSkinUrlProvider skinUrlProvider = null;
if (core.configuration.getBoolean("skinsrestorer-integration", false)) {
Plugin skinsRestorer = getServer().getPluginManager().getPlugin("SkinsRestorer");
if (skinsRestorer == null) {
Log.warning("SkinsRestorer integration can't be enabled because SkinsRestorer is not installed");
} else {
try {
skinUrlProvider = new SkinsRestorerSkinUrlProvider();
Log.info("SkinsRestorer API integration enabled");
} catch (NoClassDefFoundError e) {
skinUrlProvider = null;
Log.warning("You are using unsupported version of SkinsRestorer. Use v14.1 or newer.");
Log.warning("Disabled SkinsRestorer integration for this session");
} catch (Throwable e) {
// SkinsRestorer probably updated its API
skinUrlProvider = null;
Log.warning("Error while enabling SkinsRestorer integration", e);
}
}
}
core.setSkinUrlProvider(skinUrlProvider);
/* See if we need to wait before enabling core */
if(!readyToEnable()) {
Listener pl = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onPluginEnabled(PluginEnableEvent evt) {
if (!readyToEnable()) {
if (readyToEnable()) { /* If we;re ready now, finish enable */
doEnable(); /* Finish enable */
}
}
}
};
pm.registerEvents(pl, this);
}
else {
doEnable();
}
// Start tps calculation
lasttick = System.nanoTime();
tps = 20.0;
perTickLimit = core.getMaxTickUseMS() * 1000000;
getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
public void run() {
processTick();
}
}, 1, 1);
}
private boolean readyToEnable() {
return true;
}
private void doEnable() {
/* Enable core */
if(!core.enableCore(enabCoreCB)) {
this.setEnabled(false);
return;
}
playerList = core.playerList;
if (helper.useGenericCache()) {
BukkitVersionHelper.gencache = new GenericChunkCache(core.getSnapShotCacheSize(), core.useSoftRefInSnapShotCache());
}
else {
SnapshotCache.sscache = new SnapshotCache(core.getSnapShotCacheSize(), core.useSoftRefInSnapShotCache());
}
/* Get map manager from core */
mapManager = core.getMapManager();
/* Initialized the currently loaded worlds */
for (World world : getServer().getWorlds()) {
BukkitWorld w = getWorld(world);
if(core.processWorldLoad(w)) /* Have core process load first - fire event listeners if good load after */
core.listenerManager.processWorldEvent(EventType.WORLD_LOAD, w);
}
/* Register our update trigger events */
registerEvents();
/* Submit metrics to mcstats.org */
initMetrics();
/* Core is ready - notify API availability */
DynmapCommonAPIListener.apiInitialized(this);
Log.info("Enabled");
}
@Override
public void onDisable() {
/* Core is being disabled - notify API disable */
DynmapCommonAPIListener.apiTerminated();
if (metrics != null) {
metrics = null;
}
/* Disable core */
core.disableCore();
if(SnapshotCache.sscache != null) {
SnapshotCache.sscache.cleanup();
SnapshotCache.sscache = null;
}
if (BukkitVersionHelper.gencache != null) {
BukkitVersionHelper.gencache.cleanup();
BukkitVersionHelper.gencache = null;
}
Log.info("Disabled");
}
private void processTick() {
long now = System.nanoTime();
long elapsed = now - lasttick;
lasttick = now;
avgticklen = ((avgticklen * 99) / 100) + (elapsed / 100);
tps = (double)1E9 / (double)avgticklen;
if (mapManager != null) {
chunks_in_cur_tick = mapManager.getMaxChunkLoadsPerTick();
}
cur_tick++;
// Tick core
if (core != null) {
core.serverTick(tps);
}
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
DynmapCommandSender dsender;
if(sender instanceof Player) {
dsender = new BukkitPlayer((Player)sender);
}
else {
dsender = new BukkitCommandSender(sender);
}
if (core != null)
return core.processCommand(dsender, cmd.getName(), commandLabel, args);
else
return false;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String alias, String[] args) {
DynmapCommandSender dsender;
if(sender instanceof Player) {
dsender = new BukkitPlayer((Player)sender);
}
else {
dsender = new BukkitCommandSender(sender);
}
if (core != null)
return core.getTabCompletions(dsender, cmd.getName(), args);
else
return Collections.emptyList();
}
@Override
public final MarkerAPI getMarkerAPI() {
return core.getMarkerAPI();
}
@Override
public final boolean markerAPIInitialized() {
return core.markerAPIInitialized();
}
@Override
public final boolean sendBroadcastToWeb(String sender, String msg) {
return core.sendBroadcastToWeb(sender, msg);
}
@Override
public final int triggerRenderOfVolume(String wid, int minx, int miny, int minz,
int maxx, int maxy, int maxz) {
invalidateSnapshot(wid, minx, miny, minz, maxx, maxy, maxz);
return core.triggerRenderOfVolume(wid, minx, miny, minz, maxx, maxy, maxz);
}
@Override
public final int triggerRenderOfBlock(String wid, int x, int y, int z) {
invalidateSnapshot(wid, x, y, z);
return core.triggerRenderOfBlock(wid, x, y, z);
}
@Override
public final void setPauseFullRadiusRenders(boolean dopause) {
core.setPauseFullRadiusRenders(dopause);
}
@Override
public final boolean getPauseFullRadiusRenders() {
return core.getPauseFullRadiusRenders();
}
@Override
public final void setPauseUpdateRenders(boolean dopause) {
core.setPauseUpdateRenders(dopause);
}
@Override
public final boolean getPauseUpdateRenders() {
return core.getPauseUpdateRenders();
}
@Override
public final void setPlayerVisiblity(String player, boolean is_visible) {
core.setPlayerVisiblity(player, is_visible);
}
@Override
public final boolean getPlayerVisbility(String player) {
return core.getPlayerVisbility(player);
}
@Override
public final void postPlayerMessageToWeb(String playerid, String playerdisplay,
String message) {
core.postPlayerMessageToWeb(playerid, playerdisplay, message);
}
@Override
public final void postPlayerJoinQuitToWeb(String playerid, String playerdisplay,
boolean isjoin) {
core.postPlayerJoinQuitToWeb(playerid, playerdisplay, isjoin);
}
@Override
public final String getDynmapCoreVersion() {
return core.getDynmapCoreVersion();
}
@Override
public final int triggerRenderOfVolume(Location l0, Location l1) {
int x0 = l0.getBlockX(), y0 = l0.getBlockY(), z0 = l0.getBlockZ();
int x1 = l1.getBlockX(), y1 = l1.getBlockY(), z1 = l1.getBlockZ();
return core.triggerRenderOfVolume(getWorld(l0.getWorld()).getName(), Math.min(x0, x1), Math.min(y0, y1),
Math.min(z0, z1), Math.max(x0, x1), Math.max(y0, y1), Math.max(z0, z1));
}
@Override
public final void setPlayerVisiblity(Player player, boolean is_visible) {
core.setPlayerVisiblity(player.getName(), is_visible);
}
@Override
public final boolean getPlayerVisbility(Player player) {
return core.getPlayerVisbility(player.getName());
}
@Override
public final void postPlayerMessageToWeb(Player player, String message) {
core.postPlayerMessageToWeb(player.getName(), player.getDisplayName(), message);
}
@Override
public void postPlayerJoinQuitToWeb(Player player, boolean isjoin) {
core.postPlayerJoinQuitToWeb(player.getName(), player.getDisplayName(), isjoin);
}
@Override
public String getDynmapVersion() {
return version;
}
private static DynmapLocation toLoc(Location l) {
return new DynmapLocation(DynmapWorld.normalizeWorldName(l.getWorld().getName()), l.getBlockX(), l.getBlockY(), l.getBlockZ());
}
private void registerPlayerLoginListener() {
Listener pl = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onPlayerJoin(PlayerJoinEvent evt) {
final DynmapPlayer dp = new BukkitPlayer(evt.getPlayer());
// Give other handlers a change to prep player (nicknames and such from Essentials)
getServer().getScheduler().scheduleSyncDelayedTask(DynmapPlugin.this, new Runnable() {
@Override
public void run() {
core.listenerManager.processPlayerEvent(EventType.PLAYER_JOIN, dp);
}
}, 2);
}
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onPlayerQuit(PlayerQuitEvent evt) {
DynmapPlayer dp = new BukkitPlayer(evt.getPlayer());
core.listenerManager.processPlayerEvent(EventType.PLAYER_QUIT, dp);
}
};
pm.registerEvents(pl, this);
}
private class BlockCheckHandler implements Runnable {
public void run() {
BlockToCheck btt;
while(blocks_to_check.isEmpty() != true) {
btt = blocks_to_check.pop();
Location loc = btt.loc;
World w = loc.getWorld();
if(!w.isChunkLoaded(loc.getBlockX()>>4, loc.getBlockZ()>>4))
continue;
int bt = getBlockIdFromBlock(w.getBlockAt(loc));
/* Avoid stationary and moving water churn */
if(bt == 9) bt = 8;
if(btt.typeid == 9) btt.typeid = 8;
if((bt != btt.typeid) || (btt.data != w.getBlockAt(loc).getData())) {
String wn = getWorld(w).getName();
invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), btt.trigger);
}
}
blocks_to_check = null;
/* Kick next run, if one is needed */
startIfNeeded();
}
public void startIfNeeded() {
if((blocks_to_check == null) && (blocks_to_check_accum.isEmpty() == false)) { /* More pending? */
blocks_to_check = blocks_to_check_accum;
blocks_to_check_accum = new LinkedList<BlockToCheck>();
getServer().getScheduler().scheduleSyncDelayedTask(DynmapPlugin.this, this, 10);
}
}
}
private BlockCheckHandler btth = new BlockCheckHandler();
private void checkBlock(Block b, String trigger) {
BlockToCheck btt = new BlockToCheck();
btt.loc = b.getLocation();
btt.typeid = getBlockIdFromBlock(b);
btt.data = b.getData();
btt.trigger = trigger;
blocks_to_check_accum.add(btt); /* Add to accumulator */
btth.startIfNeeded();
}
private boolean onplace;
private boolean onbreak;
private boolean onblockform;
private boolean onblockfade;
private boolean onblockspread;
private boolean onblockfromto;
private boolean onblockphysics;
private boolean onleaves;
private boolean onburn;
private boolean onpiston;
private boolean onplayerjoin;
private boolean onplayermove;
private boolean ongeneratechunk;
private boolean onexplosion;
private boolean onstructuregrow;
private boolean onblockgrow;
private boolean onblockredstone;
private void invalidateSnapshot(String wn, int x, int y, int z) {
if (helper.useGenericCache()) {
BukkitVersionHelper.gencache.invalidateSnapshot(wn, x, y, z);
}
else {
SnapshotCache.sscache.invalidateSnapshot(wn, x, y, z);
}
}
private void invalidateSnapshot(String wname, int minx, int miny, int minz, int maxx, int maxy, int maxz) {
if (helper.useGenericCache()) {
BukkitVersionHelper.gencache.invalidateSnapshot(wname, minx, miny, minz, maxx, maxy, maxz);
}
else {
SnapshotCache.sscache.invalidateSnapshot(wname, minx, miny, minz, maxx, maxy, maxz);
}
}
private void registerEvents() {
// To trigger rendering.
onplace = core.isTrigger("blockplaced");
onbreak = core.isTrigger("blockbreak");
onleaves = core.isTrigger("leavesdecay");
onburn = core.isTrigger("blockburn");
onblockform = core.isTrigger("blockformed");
onblockfade = core.isTrigger("blockfaded");
onblockspread = core.isTrigger("blockspread");
onblockfromto = core.isTrigger("blockfromto");
onblockphysics = core.isTrigger("blockphysics");
onpiston = core.isTrigger("pistonmoved");
onblockredstone = core.isTrigger("blockredstone");
if(onplace) {
Listener placelistener = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onBlockPlace(BlockPlaceEvent event) {
Location loc = event.getBlock().getLocation();
String wn = getWorld(loc.getWorld()).getName();
invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockplace");
}
};
pm.registerEvents(placelistener, this);
}
if(onbreak) {
Listener breaklistener = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onBlockBreak(BlockBreakEvent event) {
Block b = event.getBlock();
if(b == null) return; /* Stupid mod workaround */
Location loc = b.getLocation();
String wn = getWorld(loc.getWorld()).getName();
invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockbreak");
}
};
pm.registerEvents(breaklistener, this);
}
if(onleaves) {
Listener leaveslistener = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onLeavesDecay(LeavesDecayEvent event) {
Location loc = event.getBlock().getLocation();
String wn = getWorld(loc.getWorld()).getName();
invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
if(onleaves) {
mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "leavesdecay");
}
}
};
pm.registerEvents(leaveslistener, this);
}
if(onburn) {
Listener burnlistener = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onBlockBurn(BlockBurnEvent event) {
Location loc = event.getBlock().getLocation();
String wn = getWorld(loc.getWorld()).getName();
invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
if(onburn) {
mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockburn");
}
}
};
pm.registerEvents(burnlistener, this);
}
if(onblockphysics) {
Listener physlistener = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onBlockPhysics(BlockPhysicsEvent event) {
Block b = event.getBlock();
Material m = b.getType();
if(m == null) return;
switch(m) {
case STATIONARY_WATER:
case WATER:
case STATIONARY_LAVA:
case LAVA:
case GRAVEL:
case SAND:
checkBlock(b, "blockphysics");
break;
default:
break;
}
}
};
pm.registerEvents(physlistener, this);
}
if(onblockfromto) {
Listener fromtolistener = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onBlockFromTo(BlockFromToEvent event) {
Block b = event.getBlock();
Material m = b.getType();
String m_id = (m != null) ? m.toString() : "";
boolean not_pressure_plate = (m_id != "WOOD_PLATE") && (m_id != "STONE_PLATE") && (!m_id.contains("PRESSURE_PLATE")) && (m_id != "");
if (not_pressure_plate)
checkBlock(b, "blockfromto");
b = event.getToBlock();
m = b.getType();
if (not_pressure_plate)
checkBlock(b, "blockfromto");
}
};
pm.registerEvents(fromtolistener, this);
}
if(onpiston) {
Listener pistonlistener = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onBlockPistonRetract(BlockPistonRetractEvent event) {
Block b = event.getBlock();
Location loc = b.getLocation();
BlockFace dir;
try { /* Workaround Bukkit bug = http://leaky.bukkit.org/issues/1227 */
dir = event.getDirection();
} catch (ClassCastException ccx) {
dir = BlockFace.NORTH;
}
String wn = getWorld(loc.getWorld()).getName();
int x = loc.getBlockX(), y = loc.getBlockY(), z = loc.getBlockZ();
invalidateSnapshot(wn, x, y, z);
if(onpiston)
mapManager.touch(wn, x, y, z, "pistonretract");
for(int i = 0; i < 2; i++) {
x += dir.getModX();
y += dir.getModY();
z += dir.getModZ();
invalidateSnapshot(wn, x, y, z);
mapManager.touch(wn, x, y, z, "pistonretract");
}
}
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onBlockPistonExtend(BlockPistonExtendEvent event) {
Block b = event.getBlock();
Location loc = b.getLocation();
BlockFace dir;
try { /* Workaround Bukkit bug = http://leaky.bukkit.org/issues/1227 */
dir = event.getDirection();
} catch (ClassCastException ccx) {
dir = BlockFace.NORTH;
}
String wn = getWorld(loc.getWorld()).getName();
int x = loc.getBlockX(), y = loc.getBlockY(), z = loc.getBlockZ();
invalidateSnapshot(wn, x, y, z);
if(onpiston)
mapManager.touch(wn, x, y, z, "pistonretract");
for(int i = 0; i < 1+event.getLength(); i++) {
x += dir.getModX();
y += dir.getModY();
z += dir.getModZ();
invalidateSnapshot(wn, x, y, z);
mapManager.touch(wn, x, y, z, "pistonretract");
}
}
};
pm.registerEvents(pistonlistener, this);
}
if(onblockspread) {
Listener spreadlistener = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onBlockSpread(BlockSpreadEvent event) {
Location loc = event.getBlock().getLocation();
String wn = getWorld(loc.getWorld()).getName();
invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockspread");
}
};
pm.registerEvents(spreadlistener, this);
}
if(onblockform) {
Listener formlistener = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onBlockForm(BlockFormEvent event) {
Location loc = event.getBlock().getLocation();
String wn = getWorld(loc.getWorld()).getName();
invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockform");
}
};
pm.registerEvents(formlistener, this);
}
if(onblockfade) {
Listener fadelistener = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onBlockFade(BlockFadeEvent event) {
Location loc = event.getBlock().getLocation();
String wn = getWorld(loc.getWorld()).getName();
invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockfade");
}
};
pm.registerEvents(fadelistener, this);
}
onblockgrow = core.isTrigger("blockgrow");
if(onblockgrow) {
Listener growTrigger = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onBlockGrow(BlockGrowEvent event) {
Location loc = event.getBlock().getLocation();
String wn = getWorld(loc.getWorld()).getName();
invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockgrow");
}
};
pm.registerEvents(growTrigger, this);
}
if(onblockredstone) {
Listener redstoneTrigger = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onBlockRedstone(BlockRedstoneEvent event) {
Location loc = event.getBlock().getLocation();
String wn = getWorld(loc.getWorld()).getName();
invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockredstone");
}
};
pm.registerEvents(redstoneTrigger, this);
}
/* Register player event trigger handlers */
Listener playerTrigger = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onPlayerJoin(PlayerJoinEvent event) {
if(onplayerjoin) {
Location loc = event.getPlayer().getLocation();
mapManager.touch(getWorld(loc.getWorld()).getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "playerjoin");
}
}
};
onplayerjoin = core.isTrigger("playerjoin");
onplayermove = core.isTrigger("playermove");
pm.registerEvents(playerTrigger, this);
if(onplayermove) {
Listener playermove = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onPlayerMove(PlayerMoveEvent event) {
Location loc = event.getPlayer().getLocation();
mapManager.touch(getWorld(loc.getWorld()).getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "playermove");
}
};
pm.registerEvents(playermove, this);
Log.warning("playermove trigger enabled - this trigger can cause excessive tile updating: use with caution");
}
/* Register entity event triggers */
Listener entityTrigger = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onEntityExplode(EntityExplodeEvent event) {
Location loc = event.getLocation();
String wname = getWorld(loc.getWorld()).getName();
int minx, maxx, miny, maxy, minz, maxz;
minx = maxx = loc.getBlockX();
miny = maxy = loc.getBlockY();
minz = maxz = loc.getBlockZ();
/* Calculate volume impacted by explosion */
List<Block> blocks = event.blockList();
for(Block b: blocks) {
Location l = b.getLocation();
int x = l.getBlockX();
if(x < minx) minx = x;
if(x > maxx) maxx = x;
int y = l.getBlockY();
if(y < miny) miny = y;
if(y > maxy) maxy = y;
int z = l.getBlockZ();
if(z < minz) minz = z;
if(z > maxz) maxz = z;
}
invalidateSnapshot(wname, minx, miny, minz, maxx, maxy, maxz);
if(onexplosion) {
mapManager.touchVolume(wname, minx, miny, minz, maxx, maxy, maxz, "entityexplode");
}
}
};
onexplosion = core.isTrigger("explosion");
pm.registerEvents(entityTrigger, this);
/* Register world event triggers */
Listener worldTrigger = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onWorldLoad(WorldLoadEvent event) {
BukkitWorld w = getWorld(event.getWorld());
if(core.processWorldLoad(w)) /* Have core process load first - fire event listeners if good load after */
core.listenerManager.processWorldEvent(EventType.WORLD_LOAD, w);
}
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onWorldUnload(WorldUnloadEvent event) {
BukkitWorld w = getWorld(event.getWorld());
if(w != null) {
core.listenerManager.processWorldEvent(EventType.WORLD_UNLOAD, w);
w.setWorldUnloaded();
core.processWorldUnload(w);
}
}
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onStructureGrow(StructureGrowEvent event) {
Location loc = event.getLocation();
String wname = getWorld(loc.getWorld()).getName();
int minx, maxx, miny, maxy, minz, maxz;
minx = maxx = loc.getBlockX();
miny = maxy = loc.getBlockY();
minz = maxz = loc.getBlockZ();
/* Calculate volume impacted by explosion */
List<BlockState> blocks = event.getBlocks();
for(BlockState b: blocks) {
int x = b.getX();
if(x < minx) minx = x;
if(x > maxx) maxx = x;
int y = b.getY();
if(y < miny) miny = y;
if(y > maxy) maxy = y;
int z = b.getZ();
if(z < minz) minz = z;
if(z > maxz) maxz = z;
}
invalidateSnapshot(wname, minx, miny, minz, maxx, maxy, maxz);
if(onstructuregrow) {
mapManager.touchVolume(wname, minx, miny, minz, maxx, maxy, maxz, "structuregrow");
}
}
};
onstructuregrow = core.isTrigger("structuregrow");
// To link configuration to real loaded worlds.
pm.registerEvents(worldTrigger, this);
ongeneratechunk = core.isTrigger("chunkgenerated");
if(ongeneratechunk) {
Listener chunkTrigger = new Listener() {
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onChunkPopulate(ChunkPopulateEvent event) {
DynmapWorld dw = getWorld(event.getWorld());
Chunk c = event.getChunk();
/* Touch extreme corners */
int x = c.getX() << 4;
int z = c.getZ() << 4;
int ymin = dw.minY;
int ymax = dw.worldheight;
mapManager.touchVolume(getWorld(event.getWorld()).getName(), x, ymin, z, x+15, ymax, z+16, "chunkpopulate");
}
};
pm.registerEvents(chunkTrigger, this);
}
}
@Override
public void assertPlayerInvisibility(String player, boolean is_invisible,
String plugin_id) {
core.assertPlayerInvisibility(player, is_invisible, plugin_id);
}
@Override
public void assertPlayerInvisibility(Player player, boolean is_invisible,
Plugin plugin) {
core.assertPlayerInvisibility(player.getName(), is_invisible, plugin.getDescription().getName());
}
@Override
public void assertPlayerVisibility(String player, boolean is_visible,
String plugin_id) {
core.assertPlayerVisibility(player, is_visible, plugin_id);
}
@Override
public void assertPlayerVisibility(Player player, boolean is_visible,
Plugin plugin) {
core.assertPlayerVisibility(player.getName(), is_visible, plugin.getDescription().getName());
}
@Override
public boolean setDisableChatToWebProcessing(boolean disable) {
return core.setDisableChatToWebProcessing(disable);
}
@Override
public boolean testIfPlayerVisibleToPlayer(String player, String player_to_see) {
return core.testIfPlayerVisibleToPlayer(player, player_to_see);
}
@Override
public boolean testIfPlayerInfoProtected() {
return core.testIfPlayerInfoProtected();
}
private class FeatureChart extends CustomChart {
public FeatureChart() { super("features_used"); }
@Override
protected JsonObject getChartData() throws Exception {
JsonObjectBuilder obj = new JsonObjectBuilder();
obj = obj.appendField("internal_web_server", core.configuration.getBoolean("disable-webserver", false) ? 0 : 1);
obj = obj.appendField("login_security", core.configuration.getBoolean("login-enabled", false) ? 1 : 0);
obj = obj.appendField("player_info_protected", core.player_info_protected ? 1 : 0);
for (String mod : modsused)
obj = obj.appendField(mod + "_blocks", 1);
return obj.build();
}
}
private class MapChart extends CustomChart {
public MapChart() { super("map_data"); }
@Override
protected JsonObject getChartData() throws Exception {
JsonObjectBuilder obj = new JsonObjectBuilder();
obj = obj.appendField("worlds", core.mapManager != null ? core.mapManager.getWorlds().size() : 0);
int maps = 0, hdmaps = 0;
if (core.mapManager != null) {
for (DynmapWorld w : core.mapManager.getWorlds()) {
for (MapType mt : w.maps)
if (mt instanceof HDMap)
++hdmaps;
maps += w.maps.size();
}
obj = obj.appendField("maps", maps);
obj = obj.appendField("hd_maps", hdmaps);
}
return obj.build();
}
}
private void initMetrics() {
metrics = new Metrics(this, 619);
metrics.addCustomChart(new FeatureChart());
metrics.addCustomChart(new MapChart());
}
@Override
public void processSignChange(String material, String world, int x, int y, int z,
String[] lines, String playerid) {
core.processSignChange(material, world, x, y, z, lines, playerid);
}
Polygon getWorldBorder(World w) {
return helper.getWorldBorder(w);
}
public static boolean migrateChunks() {
if ((plugin != null) && (plugin.core != null)) {
return plugin.core.migrateChunks();
}
return false;
}
}
| 412 | 0.957473 | 1 | 0.957473 | game-dev | MEDIA | 0.963286 | game-dev | 0.745392 | 1 | 0.745392 |
itsdax/Runescape-Web-Walker-Engine | 5,842 | src/main/java/dax/shared/helpers/WorldHelper.java | package dax.shared.helpers;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class WorldHelper {
private static WorldHelper instance = null;
private Map<Integer, World> worldList;
private WorldHelper() {
updateWorldList();
}
private void updateWorldList(){
try {
worldList = loadWorldList();
} catch (IOException e){
e.printStackTrace();
}
}
private static WorldHelper getInstance() {
return instance != null ? instance : (instance = new WorldHelper());
}
public static Map<Integer, World> getWorldList(){
try {
return Collections.unmodifiableMap(getInstance().worldList);
} catch(Exception e){
e.printStackTrace();
getInstance().updateWorldList();
}
return new HashMap<>();
}
public static boolean isSkillTotal(int worldNumber) {
World world = getWorld(worldNumber);
return world != null && world.isSkillTotal();
}
public static boolean isMember(int worldNumber) {
World world = getWorld(worldNumber);
return world != null && world.isMember();
}
public static String getActivity(int worldNumber) {
World world = getWorld(worldNumber);
return world != null ? world.getActivity() : null;
}
public static boolean hasActivity(int worldNumber) {
World world = getWorld(worldNumber);
return world != null && world.getActivity() != null && world.getActivity().length() > 2;
}
public static boolean isDeadMan(int worldNumber) {
World world = getWorld(worldNumber);
return world != null && world.isDeadman();
}
public static boolean isPvp(int worldNumber) {
World world = getWorld(worldNumber);
return world != null && world.isPvp();
}
private static World getWorld(int worldNumber){
worldNumber = worldNumber % 300;
return getWorldList().get(worldNumber);
}
/**
* Credit to AlphaDog
* @return
* @throws IOException
*/
private static Map<Integer, World> loadWorldList() throws IOException {
Map<Integer, World> worldList = new HashMap<>();
URLConnection urlConnection = new URL("http://oldschool.runescape.com/slr").openConnection();
try (DataInputStream dataInputStream = new DataInputStream(urlConnection.getInputStream())) {
int size = dataInputStream.readInt() & 0xFF;
int worldCount = dataInputStream.readShort();
for (int i = 0; i < worldCount; i++) {
int world = (dataInputStream.readShort() & 0xFFFF) % 300, flag = dataInputStream.readInt();
boolean member = (flag & 0x1) != 0, pvp = (flag & 0x4) != 0, highRisk = (flag & 0x400) != 0;
StringBuilder sb = new StringBuilder();
String host = null, activity;
byte b;
while (true) {
if ((b = dataInputStream.readByte()) == 0) {
if (host == null) {
host = sb.toString();
sb = new StringBuilder();
} else {
activity = sb.toString();
break;
}
} else {
sb.append((char) b);
}
}
worldList.put(world, new World(world, flag, member, pvp, highRisk, host, activity, dataInputStream.readByte() & 0xFF, dataInputStream.readShort()));
}
}
return worldList;
}
public static class World {
private final int id;
private final boolean member;
private final boolean pvp;
private final boolean highRisk;
private final boolean deadman, skillTotal;
private final String host;
private final String activity;
private final int serverLoc;
private final int playerCount;
private final int flag;
public World(int id, int flag, boolean member, boolean pvp, boolean highRisk, String host, String activity, int serverLoc, int playerCount) {
this.id = id;
this.flag = flag;
this.member = member;
this.pvp = pvp;
this.highRisk = highRisk;
this.host = host;
this.activity = activity;
this.serverLoc = serverLoc;
this.playerCount = playerCount;
deadman = activity.toLowerCase().contains("deadman");
skillTotal = activity.toLowerCase().contains("skill");
}
public int getId() {
return id;
}
public int getFlag() {
return flag;
}
public boolean isMember() {
return member;
}
public boolean isPvp() {
return pvp;
}
public boolean isHighRisk() {
return highRisk;
}
public boolean isDeadman() {
return deadman;
}
public String getHost() {
return host;
}
public String getActivity() {
return activity;
}
public int getServerLoc() {
return serverLoc;
}
public int getPlayerCount() {
return playerCount;
}
public boolean isSkillTotal() {
return skillTotal;
}
@Override
public String toString() {
return "[World " + id + " | " + playerCount + " players | " + (member ? "Members" : "F2P") + " | " + activity + "]";
}
}
}
| 412 | 0.625818 | 1 | 0.625818 | game-dev | MEDIA | 0.857887 | game-dev | 0.851455 | 1 | 0.851455 |
FiveM-Scripts/Cops_FiveM | 6,211 | police/client/cloackroom.lua | --[[
Cops_FiveM - A cops script for FiveM RP servers.
Copyright (C) 2018 FiveM-Scripts
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Cops_FiveM in the file "LICENSE". If not, see <http://www.gnu.org/licenses/>.
]]
local buttons = {}
function load_cloackroom()
for k in ipairs (buttons) do
buttons [k] = nil
end
for k, data in pairs(skins) do
if config.useCopWhitelist then
if dept == k then
for k, v in pairs(data) do
buttons[#buttons+1] = {name = tostring(v.name), func = "clockIn", params = tostring(v.model)}
end
end
else
for k, v in pairs(data) do
buttons[#buttons+1] = {name = tostring(v.name), func = "clockIn", params = tostring(v.model)}
end
end
end
buttons[#buttons+1] = {name = i18n.translate("cloackroom_break_service_title"), func = "clockOut", params = ""}
if(config.enableOutfits == true) then
if(rank <= 0) then
buttons[#buttons+1] = {name = i18n.translate("cloackroom_add_yellow_vest_title"), func = "cloackroom_add_yellow_vest", params = ""}
buttons[#buttons+1] = {name = i18n.translate("cloackroom_remove_yellow_vest_title"), func = "cloackroom_rem_yellow_vest", params = ""}
end
end
end
function clockIn(model)
if model then
if IsModelValid(model) and IsModelInCdimage(model) then
ServiceOn()
SetCopModel(model)
drawNotification(i18n.translate("now_in_service_notification"))
drawNotification(i18n.translate("help_open_menu_notification"))
else
drawNotification("This model is ~r~invalid~w~.")
end
end
end
function clockOut()
ServiceOff()
removeUniforme()
drawNotification(i18n.translate("break_service_notification"))
end
function cloackroom_add_yellow_vest()
Citizen.CreateThread(function()
if(GetEntityModel(PlayerPedId()) == hashSkin) then
SetPedComponentVariation(PlayerPedId(), 8, 59, 0, 2)
else
SetPedComponentVariation(PlayerPedId(), 8, 36, 0, 2)
end
end)
end
function cloackroom_rem_yellow_vest()
Citizen.CreateThread(function()
if(GetEntityModel(PlayerPedId()) == hashSkin) then
SetPedComponentVariation(PlayerPedId(), 8, 58, 0, 2)
else
SetPedComponentVariation(PlayerPedId(), 8, 35, 0, 2)
end
end)
end
function SetCopModel(model)
SetMaxWantedLevel(0)
SetWantedLevelMultiplier(0.0)
SetRelationshipBetweenGroups(0, GetHashKey("police"), GetHashKey("PLAYER"))
SetRelationshipBetweenGroups(0, GetHashKey("PLAYER"), GetHashKey("police"))
modelHash = GetHashKey(model)
RequestModel(modelHash)
while not HasModelLoaded(modelHash) do
Citizen.Wait(0)
end
if model == "s_m_y_cop_01" then
if (config.enableOutfits == true) then
if(GetEntityModel(PlayerPedId()) == GetHashKey("mp_m_freemode_01")) then
SetPedPropIndex(PlayerPedId(), 1, 5, 0, 2) --Sunglasses
SetPedPropIndex(PlayerPedId(), 2, 0, 0, 2) --Bluetoothn earphone
SetPedComponentVariation(PlayerPedId(), 11, 55, 0, 2) --Shirt
SetPedComponentVariation(PlayerPedId(), 8, 58, 0, 2) --Nightstick decoration
SetPedComponentVariation(PlayerPedId(), 4, 35, 0, 2) --Pants
SetPedComponentVariation(PlayerPedId(), 6, 24, 0, 2) --Shooes
SetPedComponentVariation(PlayerPedId(), 10, 8, config.rank.outfit_badge[rank], 2) --rank
else
SetPedPropIndex(PlayerPedId(), 1, 11, 3, 2) --Sunglasses
SetPedPropIndex(PlayerPedId(), 2, 0, 0, 2) --Bluetoothn earphone
SetPedComponentVariation(PlayerPedId(), 3, 14, 0, 2) --Non buggy tshirt
SetPedComponentVariation(PlayerPedId(), 11, 48, 0, 2) --Shirt
SetPedComponentVariation(PlayerPedId(), 8, 35, 0, 2) --Nightstick decoration
SetPedComponentVariation(PlayerPedId(), 4, 34, 0, 2) --Pants
SetPedComponentVariation(PlayerPedId(), 6, 29, 0, 2) --Shooes
SetPedComponentVariation(PlayerPedId(), 10, 7, config.rank.outfit_badge[rank], 2) --rank
end
else
SetPlayerModel(PlayerId(), modelHash)
end
elseif model == "s_m_y_hwaycop_01" then
SetPlayerModel(PlayerId(), modelHash)
SetPedComponentVariation(PlayerPedId(), 10, 7, config.rank.outfit_badge[rank], 2)
elseif model == "s_m_y_sheriff_01" then
SetPlayerModel(PlayerId(), modelHash)
SetPedComponentVariation(PlayerPedId(), 10, 7, config.rank.outfit_badge[rank], 2)
elseif model == "s_m_y_ranger_01" then
SetPlayerModel(PlayerId(), modelHash)
SetPedComponentVariation(PlayerPedId(), 10, 7, config.rank.outfit_badge[rank], 2)
elseif model == "a_m_y_genstreet_01" then
else
SetPlayerModel(PlayerId(), modelHash)
end
giveBasicKit()
SetModelAsNoLongerNeeded(modelHash)
end
function removeUniforme()
if(config.enableOutfits == true) then
RemoveAllPedWeapons(PlayerPedId())
TriggerServerEvent("skin_customization:SpawnPlayer")
else
local model = GetHashKey("a_m_y_mexthug_01")
RequestModel(model)
while not HasModelLoaded(model) do
Citizen.Wait(0)
end
SetPlayerModel(PlayerId(), model)
SetModelAsNoLongerNeeded(model)
SetMaxWantedLevel(5)
SetWantedLevelMultiplier(1.0)
SetRelationshipBetweenGroups(3, GetHashKey("police"), GetHashKey("PLAYER"))
SetRelationshipBetweenGroups(3, GetHashKey("PLAYER"), GetHashKey("police"))
end
end
function OpenCloackroom()
if anyMenuOpen.menuName ~= "cloackroom" and not anyMenuOpen.isActive then
SendNUIMessage({
title = GetLabelText("collision_8vlv02g"),
subtitle = GetLabelText("INPUT_CHARACTER_WHEEL"),
buttons = buttons,
action = "setAndOpen"
})
anyMenuOpen.menuName = "cloackroom"
anyMenuOpen.isActive = true
if config.enableVersionNotifier then
TriggerServerEvent('police:UpdateNotifier')
end
end
end
| 412 | 0.824778 | 1 | 0.824778 | game-dev | MEDIA | 0.882403 | game-dev | 0.937797 | 1 | 0.937797 |
amatukaze/ing | 3,065 | src/Game/Sakuno.ING.Game.Models/Models/MasterDataRoot.cs | using Sakuno.ING.Game.Models.MasterData;
using System;
using System.Reactive.Linq;
namespace Sakuno.ING.Game.Models
{
public sealed class MasterDataRoot
{
private readonly IdTable<ShipInfoId, ShipInfo, RawShipInfo, MasterDataRoot> _shipInfos;
public ITable<ShipInfoId, ShipInfo> ShipInfos => _shipInfos;
private readonly IdTable<ShipTypeId, ShipTypeInfo, RawShipTypeInfo, MasterDataRoot> _shipTypes;
public ITable<ShipTypeId, ShipTypeInfo> ShipTypes => _shipTypes;
private readonly IdTable<SlotItemInfoId, SlotItemInfo, RawSlotItemInfo, MasterDataRoot> _slotItemInfos;
public ITable<SlotItemInfoId, SlotItemInfo> SlotItemInfos => _slotItemInfos;
private readonly IdTable<SlotItemTypeId, SlotItemTypeInfo, RawSlotItemTypeInfo, MasterDataRoot> _slotItemTypes;
public ITable<SlotItemTypeId, SlotItemTypeInfo> SlotItemTypes => _slotItemTypes;
private readonly IdTable<UseItemId, UseItemInfo, RawUseItem, MasterDataRoot> _useItems;
public ITable<UseItemId, UseItemInfo> UseItems => _useItems;
private readonly IdTable<MapAreaId, MapAreaInfo, RawMapArea, MasterDataRoot> _mapAreas;
public ITable<MapAreaId, MapAreaInfo> MapAreas => _mapAreas;
private readonly IdTable<MapId, MapInfo, RawMapInfo, MasterDataRoot> _mapInfos;
public ITable<MapId, MapInfo> MapInfos => _mapInfos;
private readonly IdTable<ExpeditionId, ExpeditionInfo, RawExpeditionInfo, MasterDataRoot> _expeditions;
public ITable<ExpeditionId, ExpeditionInfo> Expeditions => _expeditions;
internal MasterDataRoot(GameProvider provider)
{
_shipInfos = new IdTable<ShipInfoId, ShipInfo, RawShipInfo, MasterDataRoot>(this);
_shipTypes = new IdTable<ShipTypeId, ShipTypeInfo, RawShipTypeInfo, MasterDataRoot>(this);
_slotItemInfos = new IdTable<SlotItemInfoId, SlotItemInfo, RawSlotItemInfo, MasterDataRoot>(this);
_slotItemTypes = new IdTable<SlotItemTypeId, SlotItemTypeInfo, RawSlotItemTypeInfo, MasterDataRoot>(this);
_useItems = new IdTable<UseItemId, UseItemInfo, RawUseItem, MasterDataRoot>(this);
_mapAreas = new IdTable<MapAreaId, MapAreaInfo, RawMapArea, MasterDataRoot>(this);
_mapInfos = new IdTable<MapId, MapInfo, RawMapInfo, MasterDataRoot>(this);
_expeditions = new IdTable<ExpeditionId, ExpeditionInfo, RawExpeditionInfo, MasterDataRoot>(this);
provider.MasterDataUpdated.Subscribe(message =>
{
_shipTypes.BatchUpdate(message.ShipTypes);
_shipInfos.BatchUpdate(message.ShipInfos);
_slotItemTypes.BatchUpdate(message.SlotItemTypes);
_slotItemInfos.BatchUpdate(message.SlotItemInfos);
_useItems.BatchUpdate(message.UseItems);
_mapAreas.BatchUpdate(message.MapAreas);
_mapInfos.BatchUpdate(message.Maps);
_expeditions.BatchUpdate(message.Expeditions);
});
}
}
}
| 412 | 0.700865 | 1 | 0.700865 | game-dev | MEDIA | 0.811425 | game-dev | 0.623355 | 1 | 0.623355 |
AmiBlitz/AmiBlitz3 | 13,749 | Sourcecodes/Amiblitz3/Debugger/defaultdebugger.ab3 | ; XTRA
; Embedded .xtra Header
;
; General Info
; -------------------------------------------------------
; ExePath = ""
; ExeFile = ""
; CreateIcon = 1
; Residents = ""
;
; Compiler
; -------------------------------------------------------
; StringBuffer = 10240
; MakeSmallest = 0
; FuncOptimize = 1
; Version = 0.0.0
; NumberOfBuilds = 0
;
; Debugger
; -------------------------------------------------------
; CliArgs = ""
; StackSize = 80000
; RuntimeDebug = 1
; DebugInfo = 0
; CreateDbgFile = 0
; OverflowCheck = 0
; AssemblerCheck = 0
; InterruptCheck = 1
; AutoRun = 1
;
; Editor
; -------------------------------------------------------
; CursorLine = 1
; CursorColumn = 1
; LabelSearch = ""
; LabelRemark = 0
; LabelAll = 0
; LabelPosition = 0
;
; Blitz Objects
; -------------------------------------------------------
; Max File = 5
; Max GadgetList = 5
; Max Queue = 10
; Max Screen = 5
; Max Shape = 100
; Max CopList = 10
; Max Sprite = 20
; Max Stencil = 5
; Max Module = 5
; Max Window = 20
; Max Anim = 10
; Max Sound = 10
; Max Bank = 5
; Max Buffer = 10
; Max Slice = 10
; Max Page = 4
; Max Tape = 5
; Max IntuiFont = 5
; Max MedModule = 8
; Max Palette = 4
; Max MenuList = 5
; Max BlitzFont = 4
; Max GTList = 20
; Max BitMap = 10
; Max IconInfo = 1
; Max NChunky = 50
; Max MUIObject = 50
; Max PTModule = 5
; Max AsyncReq = 4
; Max Req-Lib = 5
; Max GTMenuList = 5
; Max Console = 5
; Max TCPSock = 5
; Max XBSound = 10
; Max Chunky = 20
; /XTRA
;OK, here's the source code to the Blitz2 default debugger.
;
;The debugger system works like this...
;
;When Blitz2 is first run, the program 'Blitz2:dbug/defaultdbug'
;is LoadSeg 'ed into memory. When a program is run from within
;Blitz2, the debug prog get's started up via 'CreateProc'. The
;new compiler menu option 'Load Debug Module' allows a different
;debugger to be used instead of 'defaultdbug'.
;
;Note that the debug prog (eg: this prog) and the main prog (the
;program actually being debugged) run as separate tasks.
;***************************************************************;
;The debug program is supplied the following routines by the main
;prog. The debug prog is supplied a look up table of the functions
;via the task control block USERDATA pointer. Have a look at the
;!d_call{} macro and d_sethandler{}, d_detoke{} procedures in the
;code to see how I call them. Note that most of these will NOT have
;any effect until the next program statement is executed.
;SETHANDLER - call this when the debugger has done all it's setup
;stuff (eg: opening windows etc), and is ready to be used and
;abused. SETHANDLER requires A0 to be pointing to a table of
;debug routines (see below) - checkout the 'htable' table in
;the program code...
;DETOKE - this allows you to detokenise a line of program source.
;On input, A0 = tokenised text and A1 = buffer to place detokenised
;text into.
;FINDOFFSET - given A0 = tokenised source line and D0=statement
;offset, this function will return D0 = detokenised statement
;offset.
;EVAL - Evaluates the null terminated string in A0. The answer
;eventually gets returned via 'EVALHANDLER' (see below).
;EXEC - Executes the null terminated string in A0. Any errors in
;execution get reported through 'EVALHANDLER' (see below).
;QUIT - call this to end program execution - but don't actually do
;anything (eg: 'END'!) until the main prog calls your 'CLEANUP'
;routine (see below).
;SKIP - call this to cause the next program statement to be
;'skipped' or ignored
;****************************************************************;
;The debug program needs to supply the following routines to
;the main prog. Note that these routines will be called by another
;task (not the debug task), and therefore should only perform
;very simple operations (eg: setting flags, or 'Signal' ing the
;debug task).
;STATEHANDLER - called before the execution of every line of
;program code, except for stuff in supervisor mode (ie: interupts).
;This routine is only allowed to play with A0 and A1 (to keep things
;fast). On entry, A0 contains a pointer to an 'info' block:
;
; NEWTYPE.statehandlerinfo
; DREGS[8] ;contents of data registers D0...D7
; AREGS[8] ;contents of address registers A0...A7
; *PC.pcinfo ;program counter
; CC.w ;condition codes
; END NEWTYPE
;
;The *PC entry points to another 'info' block:
;
; NEWTYPE.pcinfo
; *SRC.src ;pointer to start of source code line
; OFFSET.w ;pointer to offset in source line of current statement.
; SKIP.w ;offset to next statement (so we can skip this one
; ;if we want!)
; END NEWTYPE
;
; NEWTYPE.src
; *NEXT.src ;pointer to next line
; *PREV.src ;pointer to previous line
; CHARS.b ;how many characters in line
; CHRS[0] ;actual tokenised source code
; END NEWTYPE
;
;The actual program code starts 8 bytes after PC...
;On exit, your statehandler return should return with the Z flag
;set if it's OK to run the statement. If the Z flag is clear, then
;the statement will not be executed, and your 'WAITHANDLER' routine
;will eventually be called (see below).
;SUPERHANDLER - called when a runtime error occurs in supervisor
;mode. A0 points to a null terminated string describing the error.
;USERHANDLER - called when a runtime error occurs in user
;mode. A0 points to a null terminated string describing the error.
;WAITHANDLER - called whenever a program statement is NOT executed.
;The main purpose of this function is to allow for a 'Step' function.
;EVALHANDLER - called with either the result of an EVAL call (see
;above), or when errors occur during either an EVAL or an EXEC.
;CLEANUP - called when the debug program is required to finish.
;This may be triggered by an 'End' statement in the main prog,
;or a call to 'QUIT' (see above). As this is called by the main prog
;task, and not the debug task, this routine should really only
;inform the debug task to end.
;******************************************************************;
;Note that in this version, I've used a 'checkflag/VWait' type
;approach to intertask communication. This is due purely to laziness
;on my part (been too busy writing a game...) and would be much more
;elegant if replaced by an exec 'Signal' or (gasp!) 'PutMsg' type
;system...
;******************************************************************;
#test=0
DEFTYPE.l
#bufflen=4096:#buffand=#bufflen-1
Macro d_call
MOVE.l d_table(pc),a2:MOVE.l `1 LSL 2(a2),a2:JSR (a2)
End Macro
Statement d_sethandler{}
LEA htable(pc),a0:!d_call{2}
End Statement
Function$ d_detoke{sa}
SHARED d_d$
GetReg a0,sa:GetReg a1,&d_d$
!d_call{3}
Function Return d_d$
End Function
Statement d_eval{t$}
SHARED d_ev$
d_ev$=t$:GetReg a0,&d_ev$:!d_call{4}
End Statement
Statement d_exec{t$}
SHARED d_ex$
d_ex$=t$:GetReg a0,&d_ex$:!d_call{5}
End Statement
Statement d_quit{}
!d_call{6}
End Statement
Statement d_skip{}
!d_call{8}
End Statement
Macro d_basic
MOVE.l d_a5(pc),a5
End Macro
NEWTYPE.d_event ;a debug event!
;
t.w ;type...0=supervisor error
; 1=user error
; 2=eval result
; 3=trace this line...
; 4=end
;
i.w ;buffer put val!
s$ ;string
;
End NEWTYPE
Dim List d_e.d_event(10)
.add_event
Statement add_event{t,s$}
SHARED d_e()
Forbid_
If AddLast(d_e())
d_e()\t=t
MOVE bufferput(pc),d0:SUBQ #4,d0:AND #buffand,d0:PutReg d0,d_e()\i
d_e()\s=s$
EndIf
Permit_
End Statement
.BEGIN:
MOVE.l 4,a0 : MOVE.l 276(a0),a0
MOVE.l 88(a0),d_table
MOVE.l a5,d_a5
MaxLen d_d$ = 256
MaxLen d_ev$ = 256
MaxLen d_ex$ = 256
Poke.l ?d_dadd,&d_d$
statego.w=0 : dstatus.w=0 : prtcode.w=0 : Poke.l ?statego_,&statego
buffmem = AllocMem_(#bufflen,$10001) : Poke.l ?buffmem_,buffmem:CLR bufferput
Goto mainstart
d_dadd: Dc.l 0
d_table: Dc.l 0 ; function table to call functions in debuglib
d_a5: Dc.l 0
statego_: Dc.l 0
buffmem_: Dc.l 0
bufferput:Dc 0
htable ;handler table
Dc.l d_statehandler,d_superhandler,d_userhandler
Dc.l d_waithandler,d_evalhandler,d_cleanup
d_statehandler
MOVE.l buffmem_(pc),a1:ADD bufferput(pc),a1:MOVE.l 64(a0),(a1)
ADDQ #4,bufferput:ANDI #buffand,bufferput
MOVE.l statego_(pc),a1:TST (a1)
RTS
d_superhandler
!d_basic:PutReg a0,sa
Gosub stopit:add_event{0,Peek$(sa)}
RTS
d_userhandler
!d_basic:PutReg a0,sa
Gosub stopit:add_event{1,Peek$(sa)}
RTS
d_waithandler
!d_basic
If prtcode ;print code out?
prtbusy=-1
add_event{3,""} ;print me out!
While prtbusy:VWait:Wend ;wait till printed!
EndIf
If dstatus=2 ;stopped?
While stepcnt=0 AND dstatus=2:VWait:Wend:stepcnt-1
EndIf
RTS
d_evalhandler
!d_basic : PutReg a0,sa
add_event{2,Peek$(sa)}
RTS
d_cleanup
!d_basic:add_event{4,""}
RTS
;*****************************************************************
.mainstart
Gosub initgads
ww = 258 : wh = 25:SizeLimits ww,wh,-1,-1
Gosub findsc:wx=sw LSR 1-(ww LSR 1):wy=16:Gosub openwindow
CNIF #test=0
d_sethandler{}
CEND
Repeat
Gosub getevent
Select ev
Case 2 ;newsize
Gosub newsize:Gosub refwindow
Case 4 ;refresh
Gosub refwindow
Case 64 ;gadget up
Select GadgetHit
Case 1 ;stop
If dstatus<>2 Then !d_call{1}
Case 2 ;step
stepcnt+1
Case 3 ;skip
If dstatus=2 Then !d_call{8}:stepcnt+1
Case 4 ;trace
Forbid_:dstatus=1:statego=-1:Permit_
Case 5 ;run
If dstatus
cil=0:pb=0:Gosub refwindow:li=0:lt$=""
Forbid_
prtcode=0:dstatus=0:statego=0
Permit_
EndIf
Case 6 ;<<
If dstatus=2 Then Gosub backward
Case 7 ;>>
If dstatus=2 AND pb<>0 Then Gosub forward
Case 8 ;execute
SetString 1,1,ex$
t$="Execute...":Gosub getascii:ex$=t$
d_exec{ex$}:stepcnt+1
Case 9 ;evaluate
SetString 1,1,ev$
t$="Evaluate...":Gosub getascii:ev$=t$
d_eval{ev$}:stepcnt+1
End Select
Case 512
CNIF #test=1
End
CELSE
d_quit{}:stepcnt+1
CEND
Case 1024
i$=Inkey$
Select Asc(i$)
Case 27
CNIF #test=1
End
CELSE
d_quit{}:stepcnt+1
CEND
Case 28
Gosub checkw
If li
If Peek.l(il+4)
il=Peek.l(il+4):Gosub prtcode2
EndIf
EndIf
Case 29
Gosub checkw
If li
If Peek.l(il)
il=Peek.l(il):Gosub prtcode2
EndIf
EndIf
End Select
End Select
Forever
.backoff
If pb
pb=0:i=Peek.l(buffmem+cb):mc=-1:Gosub prtcode
EndIf
Return
.backward
If pb=0 Then bb=cb
bb-4 AND #buffand:i=Peek.l(buffmem+bb)
If i=0
If pb=0 Then Return
bb+4 AND #buffand:t$="At end of buffer":DisplayBeep_ 0:Goto wprint
EndIf
pb=-1:mc=-1:Goto prtcode
.forward
bb+4 AND #buffand
If (bb+4 AND #buffand)=Peek.w(?bufferput) Then pb=0
i=Peek.l(buffmem+bb):mc=-1:Goto prtcode
.checkw
If ih<8 Then wh=25+16:Goto openwindow
Return
.prtcode
;
;i=info
;
;mc=-1 to make current
;cil=current ins. line, cio=current offset
;
Gosub checkw:il=Peek.l(i):io=Peek.w(i+4)-9
If mc Then cil=il:cio=io:mc=0
;
Gosub prtcode2
;
li=i:Return
prtcode2
;
y=ym:i2=il
While y<=ih-8 AND i2<>0
Gosub prti2:y+8:i2=Peek.l(i2)
Wend
While y<=ih-8:WLocate 0,12+y:Print spc$:y+8:Wend
;
y=ym-8:i2=Peek.l(il+4)
While y>=0 AND i2<>0
Gosub prti2:y-8:i2=Peek.l(i2+4)
Wend
While y>=0:WLocate 0,12+y:Print spc$:y-8:Wend
;
Return
.prti2 ;i2 at y
;
GetReg a0,i2+9
MOVE.l d_dadd(pc),a1:!d_call{3}:SUB.l d_dadd(pc),a1:SUBQ #1,a1
MOVE.l d_dadd(pc),a0:MOVE.l a1,-(a0)
;
If i2=cil
GetReg a0,i2+9:GetReg d0,cio:!d_call{7}:PutReg d0,cio2
d_d$=Left$(d_d$,cio2)+" "+Mid$(d_d$,cio2+1)
EndIf
;
WLocate 0,12+y:WColour 1,0:Print LSet$(d_d$,cw)
;
If i2=cil
WLocate cio2 LSL 3,12+y:WColour 3,0
If pb
Print ">"
Else
WJam 3:Print " ":WJam 1
EndIf
EndIf
;
Return
.wprint
Gosub checkw
WLocate ix-WLeftOff,iy+ih-WTopOff:WColour 3,0:Print LSet$(t$,cw)
lt$=t$
Return
.initgads
Borders 2,2:BorderPens 2,1
gx=4:gn=1
Repeat
Read t$
If t$<>""
gf=0:If gn=10 Then gf=1
TextGadget 0,gx,11,gf,gn,t$:gx+Len(t$)LSL 3+4
gn+1
EndIf
Until t$=""
Borders Off
StringGadget 1,8,12,8,1,256,-16
Return
Data$ "BRK","STP","SKP","TRC","RUN","<<",">>","EXC","EVL"
Data$ ""
findsc
FindScreen 0:s0=Peek.l(Addr Screen(0))
sw=Peek.w(s0+12):sh=Peek.w(s0+14)
Return
.refwindow
If li<>0 OR lt$<>""
WBox ix,iy,ix+iw-1,iy+ih-1,0
If li Then i=li:Gosub prtcode
t$=lt$:Gosub wprint
EndIf
Return
.getascii
x=WindowX:y=WindowY+WindowHeight LSR 1-12:w=WindowWidth:h=23
ResetString 1,1
Window 1,x,y,w,h,$1000,t$,1,0,1
ActivateString 1,1
;
Repeat
ev2.l=WaitEvent
Until ev2=64 AND EventWindow=1
;
Free Window 1:Use Window 0:t$=StringText$(1,1):Return
.openwindow
Window 0,wx,wy,ww,wh,$f,"Blitz 2 DBUG",1,0,0:w0=Peek.l(Addr Window(0))
.newsize
ix=WLeftOff:iy=WTopOff+12:iw=InnerWidth:ih=InnerHeight-20
cw=iw LSR 3:ch=ih LSR 3
ym=ch LSR 1:If ch&1=0 Then ym-1
ym LSL 3:spc$=String$(" ",cw)
Return
.stopit
prtcode=-1:stepcnt=0:dstatus=2:statego=-1
Return
.getevent
Repeat
While FirstItem(d_e())
Select d_e()\t
Case 0 ;supervisor mode error!
t$="(*) "+d_e()\s:Gosub wprint:Gosub goterr ;DisplayBeep_ 0
Case 1 ;user mode error!
t$=d_e()\s:Gosub wprint:Gosub goterr ;DisplayBeep_ 0
Case 2 ;eval/exec result!
t$=d_e()\s:Gosub wprint
Case 3 ;dump code baby!
cb=d_e()\i:i=Peek.l(buffmem+cb)
pb=0:mc=-1:Gosub prtcode:prtbusy=0
Case 4 ;outa-here
FreeMem_ buffmem,#bufflen:End
End Select
MaxLen d_e()\s=0:KillItem d_e()
Wend
ev=Event:If ev=0 Then WaitTOF_
Until ev
Return
.goterr:
DisplayBeep_ 0:ScreenToFront_ s0:Activate 0:Return
| 412 | 0.957695 | 1 | 0.957695 | game-dev | MEDIA | 0.348461 | game-dev | 0.983492 | 1 | 0.983492 |
Fluorohydride/ygopro-scripts | 2,501 | c28677304.lua | --E・HERO ブラック・ネオス
function c28677304.initial_effect(c)
--fusion material
c:EnableReviveLimit()
aux.AddFusionProcCode2(c,89943723,43237273,false,false)
aux.AddContactFusionProcedure(c,Card.IsAbleToDeckOrExtraAsCost,LOCATION_ONFIELD,0,aux.ContactFusionSendToDeck(c))
--spsummon condition
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetCode(EFFECT_SPSUMMON_CONDITION)
e1:SetValue(c28677304.splimit)
c:RegisterEffect(e1)
--return
aux.EnableNeosReturn(c,c28677304.retop)
--disable
local e5=Effect.CreateEffect(c)
e5:SetDescription(aux.Stringid(28677304,1))
e5:SetCategory(CATEGORY_DISABLE)
e5:SetType(EFFECT_TYPE_IGNITION)
e5:SetRange(LOCATION_MZONE)
e5:SetProperty(EFFECT_FLAG_CARD_TARGET)
e5:SetCondition(c28677304.discon)
e5:SetTarget(c28677304.distg)
e5:SetOperation(c28677304.disop)
c:RegisterEffect(e5)
end
c28677304.material_setcode=0x8
function c28677304.splimit(e,se,sp,st)
return not e:GetHandler():IsLocation(LOCATION_EXTRA)
end
function c28677304.retop(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) or e:GetHandler():IsFacedown() then return end
Duel.SendtoDeck(e:GetHandler(),nil,SEQ_DECKSHUFFLE,REASON_EFFECT)
end
function c28677304.discon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetCardTargetCount()==0
end
function c28677304.filter(c)
return c:IsFaceup() and c:IsType(TYPE_EFFECT)
end
function c28677304.distg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and c28677304.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c28677304.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
local g=Duel.SelectTarget(tp,c28677304.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_DISABLE,g,1,0,0)
end
function c28677304.disop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if c:IsRelateToEffect(e) and tc:IsFaceup() and tc:IsRelateToEffect(e) and not tc:IsImmuneToEffect(e) then
c:SetCardTarget(tc)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE+EFFECT_FLAG_CANNOT_DISABLE)
e1:SetRange(LOCATION_MZONE)
e1:SetCode(EFFECT_DISABLE)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
e1:SetCondition(c28677304.rcon)
tc:RegisterEffect(e1,true)
end
end
function c28677304.rcon(e)
return e:GetOwner():IsHasCardTarget(e:GetHandler())
end
| 412 | 0.803841 | 1 | 0.803841 | game-dev | MEDIA | 0.952866 | game-dev | 0.821914 | 1 | 0.821914 |
tenox7/micropolis | 26,602 | src/sim/w_sim.c | #include "sim.h"
Tcl_HashTable SimCmds;
#define SIMCMD_CALL(proc) \
int SimCmd##proc(ARGS) { proc(); return (TCL_OK); }
#define SIMCMD_CALL_KICK(proc) \
int SimCmd##proc(ARGS) { proc(); Kick(); return (TCL_OK); }
#define SIMCMD_CALL_INT(proc) \
int SimCmd##proc(ARGS) { \
int val; \
if (argc != 3) return (TCL_ERROR); \
if ((Tcl_GetInt(interp, argv[2], &val) != TCL_OK)) return (TCL_ERROR); \
proc(val); \
return (TCL_OK); \
}
#define SIMCMD_CALL_STR(proc) \
int SimCmd##proc(ARGS) { \
if (argc != 3) return (TCL_ERROR); \
proc(argv[2]); \
return (TCL_OK); \
}
#define SIMCMD_CALL_TILEXY(proc) \
int SimCmd##proc(ARGS) { \
int x, y; \
if (argc != 4) return (TCL_ERROR); \
if ((Tcl_GetInt(interp, argv[2], &x) != TCL_OK) || \
(x < 0) || (x >= WORLD_X)) return (TCL_ERROR); \
if ((Tcl_GetInt(interp, argv[3], &y) != TCL_OK) || \
(y < 0) || (y >= WORLD_Y)) return (TCL_ERROR); \
proc(x, y); \
return (TCL_OK); \
}
#define SIMCMD_ACCESS_INT(var) \
int SimCmd##var(ARGS) { \
int val; \
if ((argc != 2) && (argc != 3)) return (TCL_ERROR); \
if (argc == 3) { \
if (Tcl_GetInt(interp, argv[2], &val) != TCL_OK) return (TCL_ERROR); \
var = val; \
} \
sprintf(interp->result, "%d", var); \
return (TCL_OK); \
}
#define SIMCMD_GET_INT(var) \
int SimCmd##var(ARGS) { \
sprintf(interp->result, "%d", var); \
return (TCL_OK); \
}
#define SIMCMD_GET_STR(var) \
int SimCmd##var(ARGS) { \
sprintf(interp->result, "%s", var); \
return (TCL_OK); \
}
SIMCMD_CALL_KICK(GameStarted)
SIMCMD_CALL_KICK(InitGame)
SIMCMD_CALL(SaveCity)
SIMCMD_CALL(ReallyQuit)
SIMCMD_CALL_KICK(UpdateHeads)
SIMCMD_CALL_KICK(UpdateMaps)
SIMCMD_CALL_KICK(UpdateEditors)
SIMCMD_CALL_KICK(RedrawMaps)
SIMCMD_CALL_KICK(RedrawEditors)
SIMCMD_CALL_KICK(UpdateGraphs)
SIMCMD_CALL_KICK(UpdateEvaluation)
SIMCMD_CALL_KICK(UpdateBudget)
SIMCMD_CALL_KICK(UpdateBudgetWindow)
SIMCMD_CALL_KICK(DoBudget)
SIMCMD_CALL_KICK(DoBudgetFromMenu)
SIMCMD_CALL_KICK(Pause)
SIMCMD_CALL_KICK(Resume)
SIMCMD_CALL(StartBulldozer)
SIMCMD_CALL(StopBulldozer)
SIMCMD_CALL(MakeFire)
SIMCMD_CALL(MakeFlood)
SIMCMD_CALL(MakeTornado)
SIMCMD_CALL(MakeEarthquake)
SIMCMD_CALL(MakeMonster)
SIMCMD_CALL(MakeMeltdown)
SIMCMD_CALL(FireBomb)
SIMCMD_CALL(SoundOff)
SIMCMD_CALL(GenerateNewCity)
SIMCMD_CALL_INT(GenerateSomeCity)
SIMCMD_ACCESS_INT(LakeLevel)
SIMCMD_ACCESS_INT(TreeLevel)
SIMCMD_ACCESS_INT(CurveLevel)
SIMCMD_ACCESS_INT(CreateIsland)
SIMCMD_CALL_KICK(SmoothTrees)
SIMCMD_CALL_KICK(SmoothWater)
SIMCMD_CALL_KICK(SmoothRiver)
SIMCMD_CALL_KICK(ClearMap)
SIMCMD_CALL_KICK(ClearUnnatural)
SIMCMD_CALL_INT(LoadScenario)
SIMCMD_CALL_STR(LoadCity)
SIMCMD_CALL_STR(SaveCityAs)
SIMCMD_CALL_TILEXY(MakeExplosion)
SIMCMD_CALL(EraseOverlay)
SIMCMD_ACCESS_INT(OverRide)
SIMCMD_ACCESS_INT(Expensive)
SIMCMD_ACCESS_INT(Players)
SIMCMD_ACCESS_INT(Votes)
SIMCMD_ACCESS_INT(BobHeight)
SIMCMD_ACCESS_INT(PendingTool)
SIMCMD_ACCESS_INT(PendingX)
SIMCMD_ACCESS_INT(PendingY)
SIMCMD_GET_STR(Displays)
int SimCmdCityName(ARGS)
{
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
setCityName(argv[2]);
}
sprintf(interp->result, "%s", CityName);
return (TCL_OK);
}
int SimCmdCityFileName(ARGS)
{
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
if (CityFileName != NULL) {
ckfree(CityFileName);
CityFileName = NULL;
}
if (argv[2][0] != '\0') {
CityFileName = (char *)ckalloc(strlen(argv[0]) + 1);
strcpy(CityFileName, argv[2]);
}
}
sprintf(interp->result, "%s", CityFileName ? CityFileName : "");
return (TCL_OK);
}
int SimCmdGameLevel(ARGS)
{
int level;
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
if ((Tcl_GetInt(interp, argv[2], &level) != TCL_OK) ||
(level < 0) || (level > 2)) {
return (TCL_ERROR);
}
SetGameLevelFunds(level);
}
sprintf(interp->result, "%d", GameLevel);
return (TCL_OK);
}
int SimCmdSpeed(ARGS)
{
int speed;
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
if ((Tcl_GetInt(interp, argv[2], &speed) != TCL_OK) ||
(speed < 0) || (speed > 7)) {
return (TCL_ERROR);
}
setSpeed(speed); Kick();
}
sprintf(interp->result, "%d", SimSpeed);
return (TCL_OK);
}
int SimCmdSkips(ARGS)
{
int skips;
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
if ((Tcl_GetInt(interp, argv[2], &skips) != TCL_OK) ||
(skips < 0)) {
return (TCL_ERROR);
}
setSkips(skips); Kick();
}
sprintf(interp->result, "%d", sim_skips);
return (TCL_OK);
}
int SimCmdSkip(ARGS)
{
int skip;
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
if ((Tcl_GetInt(interp, argv[2], &skip) != TCL_OK) ||
(skip < 0)) {
return (TCL_ERROR);
}
sim_skip = skip;
}
sprintf(interp->result, "%d", sim_skip);
return (TCL_OK);
}
int SimCmdDelay(ARGS)
{
int delay;
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
if ((Tcl_GetInt(interp, argv[2], &delay) != TCL_OK) ||
(delay < 0)) {
return (TCL_ERROR);
}
sim_delay = delay; Kick();
}
sprintf(interp->result, "%d", sim_delay);
return (TCL_OK);
}
int SimCmdWorldX(ARGS)
{
int val;
if (argc != 2) {
return (TCL_ERROR);
}
sprintf(interp->result, "%d", WORLD_X);
return (TCL_OK);
}
int SimCmdWorldY(ARGS)
{
int val;
if (argc != 2) {
return (TCL_ERROR);
}
sprintf(interp->result, "%d", WORLD_Y);
return (TCL_OK);
}
int SimCmdHeatSteps(ARGS)
{
int steps;
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
if ((Tcl_GetInt(interp, argv[2], &steps) != TCL_OK) ||
(steps < 0)) {
return (TCL_ERROR);
}
heat_steps = steps; Kick();
}
sprintf(interp->result, "%d", heat_steps);
return (TCL_OK);
}
int SimCmdHeatFlow(ARGS)
{
int flow;
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
if (Tcl_GetInt(interp, argv[2], &flow) != TCL_OK) {
return (TCL_ERROR);
}
heat_flow = flow;
}
sprintf(interp->result, "%d", heat_flow);
return (TCL_OK);
}
int SimCmdHeatRule(ARGS)
{
int rule;
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
if (Tcl_GetInt(interp, argv[2], &rule) != TCL_OK) {
return (TCL_ERROR);
}
heat_rule = rule;
}
sprintf(interp->result, "%d", heat_rule);
return (TCL_OK);
}
#ifdef CAM
int SimCmdJustCam(ARGS)
{
int cam;
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
if (Tcl_GetInt(interp, argv[2], &cam) != TCL_OK) {
return (TCL_ERROR);
}
sim_just_cam = cam;
}
sprintf(interp->result, "%d", sim_just_cam);
return (TCL_OK);
}
#endif
#ifdef NET
int SimCmdListenTo(ARGS)
{
int port, sock;
if (argc != 3) {
return (TCL_ERROR);
}
if (Tcl_GetInt(interp, argv[2], &port) != TCL_OK) {
return (TCL_ERROR);
}
#ifdef NET
sock = udp_listen(port);
#endif
sprintf(interp->result, "%d", sock);
return (TCL_OK);
}
int SimCmdHearFrom(ARGS)
{
int sock;
if (argc != 3) {
return (TCL_ERROR);
}
if ((argv[2][0] != 'f') ||
(argv[2][1] != 'i') ||
(argv[2][2] != 'l') ||
(argv[2][3] != 'e') ||
(Tcl_GetInt(interp, argv[2] + 4, &sock) != TCL_OK)) {
return (TCL_ERROR);
}
#ifdef NET
udp_hear(sock);
#endif
return (TCL_OK);
}
#endif /* NET */
int SimCmdFunds(ARGS)
{
int funds;
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
if ((Tcl_GetInt(interp, argv[2], &funds) != TCL_OK) ||
(funds < 0)) {
return (TCL_ERROR);
}
TotalFunds = funds;
MustUpdateFunds = 1;
Kick();
}
sprintf(interp->result, "%d", TotalFunds);
return (TCL_OK);
}
int SimCmdTaxRate(ARGS)
{
int tax;
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
if ((Tcl_GetInt(interp, argv[2], &tax) != TCL_OK) ||
(tax < 0) || (tax > 20)) {
return (TCL_ERROR);
}
CityTax = tax;
drawBudgetWindow(); Kick();
}
sprintf(interp->result, "%d", CityTax);
return (TCL_OK);
}
int SimCmdFireFund(ARGS)
{
int percent;
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
if ((Tcl_GetInt(interp, argv[2], &percent) != TCL_OK) ||
(percent < 0) || (percent > 100)) {
return (TCL_ERROR);
}
firePercent = percent / 100.0;
FireSpend = (fireMaxValue * percent) / 100;
UpdateFundEffects(); Kick();
}
sprintf(interp->result, "%d", (int)(firePercent * 100.0));
return (TCL_OK);
}
int SimCmdPoliceFund(ARGS)
{
int percent;
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
if ((Tcl_GetInt(interp, argv[2], &percent) != TCL_OK) ||
(percent < 0) || (percent > 100)) {
return (TCL_ERROR);
}
policePercent = percent / 100.0;
PoliceSpend = (policeMaxValue * percent) / 100;
UpdateFundEffects(); Kick();
}
sprintf(interp->result, "%d", (int)(policePercent * 100.0));
return (TCL_OK);
}
int SimCmdRoadFund(ARGS)
{
int percent;
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
if ((Tcl_GetInt(interp, argv[2], &percent) != TCL_OK) ||
(percent < 0) || (percent > 100)) {
return (TCL_ERROR);
}
roadPercent = percent / 100.0;
RoadSpend = (roadMaxValue * percent) / 100;
UpdateFundEffects(); Kick();
}
sprintf(interp->result, "%d", (int)(roadPercent * 100.0));
return (TCL_OK);
}
int SimCmdYear(ARGS)
{
int year;
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
if ((Tcl_GetInt(interp, argv[2], &year) != TCL_OK)) {
return (TCL_ERROR);
}
SetYear(year);
}
sprintf(interp->result, "%d", CurrentYear());
return (TCL_OK);
}
int SimCmdAutoBudget(ARGS)
{
int val;
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
if ((Tcl_GetInt(interp, argv[2], &val) != TCL_OK) ||
(val < 0) || (val > 1)) {
return (TCL_ERROR);
}
autoBudget = val;
MustUpdateOptions = 1; Kick();
UpdateBudget();
}
sprintf(interp->result, "%d", autoBudget);
return (TCL_OK);
}
int SimCmdAutoGoto(ARGS)
{
int val;
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
if ((Tcl_GetInt(interp, argv[2], &val) != TCL_OK) ||
(val < 0) || (val > 1)) {
return (TCL_ERROR);
}
autoGo = val;
MustUpdateOptions = 1; Kick();
}
sprintf(interp->result, "%d", autoGo);
return (TCL_OK);
}
int SimCmdAutoBulldoze(ARGS)
{
int val;
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
if ((Tcl_GetInt(interp, argv[2], &val) != TCL_OK) ||
(val < 0) || (val > 1)) {
return (TCL_ERROR);
}
autoBulldoze = val;
MustUpdateOptions = 1; Kick();
}
sprintf(interp->result, "%d", autoBulldoze);
return (TCL_OK);
}
int SimCmdDisasters(ARGS)
{
int val;
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
if ((Tcl_GetInt(interp, argv[2], &val) != TCL_OK) ||
(val < 0) || (val > 1)) {
return (TCL_ERROR);
}
NoDisasters = val ? 0 : 1;
MustUpdateOptions = 1; Kick();
}
sprintf(interp->result, "%d", NoDisasters ? 0 : 1);
return (TCL_OK);
}
int SimCmdSound(ARGS)
{
int val;
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
if ((Tcl_GetInt(interp, argv[2], &val) != TCL_OK) ||
(val < 0) || (val > 1)) {
return (TCL_ERROR);
}
UserSoundOn = val;
MustUpdateOptions = 1; Kick();
}
sprintf(interp->result, "%d", UserSoundOn);
return (TCL_OK);
}
int SimCmdFlush(ARGS)
{
int style;
if (argc != 2) {
return (TCL_ERROR);
}
return (TCL_OK);
}
int SimCmdFlushStyle(ARGS)
{
int style;
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
if ((Tcl_GetInt(interp, argv[2], &style) != TCL_OK) ||
(style < 0)) {
return (TCL_ERROR);
}
FlushStyle = style;
}
sprintf(interp->result, "%d", FlushStyle);
return (TCL_OK);
}
int SimCmdDonDither(ARGS)
{
int dd;
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
if ((Tcl_GetInt(interp, argv[2], &dd) != TCL_OK) ||
(dd < 0)) {
return (TCL_ERROR);
}
DonDither = dd;
}
sprintf(interp->result, "%d", DonDither);
return (TCL_OK);
}
int SimCmdDoOverlay(ARGS)
{
int dd;
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
if ((Tcl_GetInt(interp, argv[2], &dd) != TCL_OK) ||
(dd < 0)) {
return (TCL_ERROR);
}
DoOverlay = dd;
}
sprintf(interp->result, "%d", DoOverlay);
return (TCL_OK);
}
int SimCmdMonsterGoal(ARGS)
{
SimSprite *sprite;
int x, y;
if (argc != 4) {
return (TCL_ERROR);
}
if (Tcl_GetInt(interp, argv[2], &x) != TCL_OK) {
return (TCL_ERROR);
}
if (Tcl_GetInt(interp, argv[3], &y) != TCL_OK) {
return (TCL_ERROR);
}
if ((sprite = GetSprite(GOD)) == NULL) {
MakeMonster();
if ((sprite = GetSprite(GOD)) == NULL)
return (TCL_ERROR);
}
sprite->dest_x = x;
sprite->dest_y = y;
sprite->control = -2;
sprite->count = -1;
return (TCL_OK);
}
int SimCmdHelicopterGoal(ARGS)
{
int x, y;
SimSprite *sprite;
if (argc != 4) {
return (TCL_ERROR);
}
if (Tcl_GetInt(interp, argv[2], &x) != TCL_OK) {
return (TCL_ERROR);
}
if (Tcl_GetInt(interp, argv[3], &y) != TCL_OK) {
return (TCL_ERROR);
}
if ((sprite = GetSprite(COP)) == NULL) {
GenerateCopter(x, y);
if ((sprite = GetSprite(COP)) == NULL) {
return (TCL_ERROR);
}
}
sprite->dest_x = x;
sprite->dest_y = y;
return (TCL_OK);
}
int SimCmdMonsterDirection(ARGS)
{
int dir;
SimSprite *sprite;
if (argc != 3) {
return (TCL_ERROR);
}
if ((Tcl_GetInt(interp, argv[2], &dir) != TCL_OK) ||
(dir < -1) || (dir > 7)) {
return (TCL_ERROR);
}
if ((sprite = GetSprite(GOD)) == NULL) {
MakeMonster();
if ((sprite = GetSprite(GOD)) == NULL) {
return (TCL_ERROR);
}
}
sprite->control = dir;
return (TCL_OK);
}
int SimCmdTile(ARGS)
{
int x, y, tile;
if ((argc != 4) && (argc != 5)) {
return (TCL_ERROR);
}
if ((Tcl_GetInt(interp, argv[2], &x) != TCL_OK) ||
(x < 0) ||
(x >= WORLD_X) ||
(Tcl_GetInt(interp, argv[3], &y) != TCL_OK) ||
(y < 0) ||
(y >= WORLD_Y)) {
return (TCL_ERROR);
}
if (argc == 5) {
if (Tcl_GetInt(interp, argv[4], &tile) != TCL_OK) {
return (TCL_ERROR);
}
Map[x][y] = tile;
}
sprintf(interp->result, "%d", Map[x][y]);
return (TCL_OK);
}
int SimCmdFill(ARGS)
{
int tile, x, y;
if (argc != 3) {
return (TCL_ERROR);
}
if (Tcl_GetInt(interp, argv[2], &tile) != TCL_OK) {
return (TCL_ERROR);
}
for (x = 0; x < WORLD_X; x++) {
for (y = 0; y < WORLD_Y; y++) {
Map[x][y] = tile;
}
}
sprintf(interp->result, "%d", tile);
return (TCL_OK);
}
int SimCmdDynamicData(ARGS)
{
int index, val;
if ((argc != 3) && (argc != 4)) {
return (TCL_ERROR);
}
if ((Tcl_GetInt(interp, argv[2], &index) != TCL_OK) ||
(index < 0) ||
(index >= 32)) {
return (TCL_ERROR);
}
if (argc == 4) {
int val;
if (Tcl_GetInt(interp, argv[3], &val) != TCL_OK) {
return (TCL_ERROR);
}
DynamicData[index] = val;
NewMapFlags[DYMAP] = 1;
Kick();
}
sprintf(interp->result, "%d", DynamicData[index]);
return (TCL_OK);
}
int SimCmdResetDynamic(ARGS)
{
int i;
for (i = 0; i < 16; i++) {
DynamicData[i] = (i & 1) ? 99999 : -99999;
}
NewMapFlags[DYMAP] = 1;
Kick();
return (TCL_OK);
}
int SimCmdPerformance(ARGS)
{
SimView *view;
PerformanceTiming = 1;
FlushTime = 0.0;
for (view = sim->editor; view != NULL; view = view->next) {
view->updates = 0;
view->update_real = view->update_user = view->update_system = 0.0;
}
return (TCL_OK);
}
int SimCmdCollapseMotion(ARGS)
{
int val;
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
if ((Tcl_GetInt(interp, argv[2], &val) != TCL_OK)) {
return (TCL_ERROR);
}
tkCollapseMotion = val;
}
sprintf(interp->result, "%d", tkCollapseMotion);
return (TCL_OK);
}
int SimCmdUpdate(ARGS)
{
sim_update();
return (TCL_OK);
}
int SimCmdLandValue(ARGS)
{
int val;
if (argc != 2) {
return (TCL_ERROR);
}
sprintf(interp->result, "%d", LVAverage);
return (TCL_OK);
}
int SimCmdTraffic(ARGS)
{
int val;
if (argc != 2) {
return (TCL_ERROR);
}
sprintf(interp->result, "%d", AverageTrf());
return (TCL_OK);
}
int SimCmdCrime(ARGS)
{
int val;
if (argc != 2) {
return (TCL_ERROR);
}
sprintf(interp->result, "%d", CrimeAverage);
return (TCL_OK);
}
int SimCmdUnemployment(ARGS)
{
int val;
if (argc != 2) {
return (TCL_ERROR);
}
sprintf(interp->result, "%d", GetUnemployment());
return (TCL_OK);
}
int SimCmdFires(ARGS)
{
int val;
if (argc != 2) {
return (TCL_ERROR);
}
sprintf(interp->result, "%d", GetFire());
return (TCL_OK);
}
int SimCmdPollution(ARGS)
{
int val;
if (argc != 2) {
return (TCL_ERROR);
}
sprintf(interp->result, "%d", PolluteAverage);
return (TCL_OK);
}
int SimCmdPolMaxX(ARGS)
{
int val;
if (argc != 2) {
return (TCL_ERROR);
}
sprintf(interp->result, "%d", (PolMaxX <<4) + 8);
return (TCL_OK);
}
int SimCmdPolMaxY(ARGS)
{
int val;
if (argc != 2) {
return (TCL_ERROR);
}
sprintf(interp->result, "%d", (PolMaxY <<4) + 8);
return (TCL_OK);
}
int SimCmdTrafMaxX(ARGS)
{
int val;
if (argc != 2) {
return (TCL_ERROR);
}
sprintf(interp->result, "%d", TrafMaxX);
return (TCL_OK);
}
int SimCmdTrafMaxY(ARGS)
{
int val;
if (argc != 2) {
return (TCL_ERROR);
}
sprintf(interp->result, "%d", TrafMaxY);
return (TCL_OK);
}
int SimCmdMeltX(ARGS)
{
int val;
if (argc != 2) {
return (TCL_ERROR);
}
sprintf(interp->result, "%d", (MeltX <<4) + 8);
return (TCL_OK);
}
int SimCmdMeltY(ARGS)
{
int val;
if (argc != 2) {
return (TCL_ERROR);
}
sprintf(interp->result, "%d", (MeltY <<4) + 8);
return (TCL_OK);
}
int SimCmdCrimeMaxX(ARGS)
{
int val;
if (argc != 2) {
return (TCL_ERROR);
}
sprintf(interp->result, "%d", (CrimeMaxX <<4) + 8);
return (TCL_OK);
}
int SimCmdCrimeMaxY(ARGS)
{
int val;
if (argc != 2) {
return (TCL_ERROR);
}
sprintf(interp->result, "%d", (CrimeMaxY <<4) + 8);
return (TCL_OK);
}
int SimCmdCenterX(ARGS)
{
int val;
if (argc != 2) {
return (TCL_ERROR);
}
sprintf(interp->result, "%d", (CCx <<4) + 8);
return (TCL_OK);
}
int SimCmdCenterY(ARGS)
{
int val;
if (argc != 2) {
return (TCL_ERROR);
}
sprintf(interp->result, "%d", (CCy <<4) + 8);
return (TCL_OK);
}
int SimCmdFloodX(ARGS)
{
int val;
if (argc != 2) {
return (TCL_ERROR);
}
sprintf(interp->result, "%d", (FloodX <<4) + 8);
return (TCL_OK);
}
int SimCmdFloodY(ARGS)
{
int val;
if (argc != 2) {
return (TCL_ERROR);
}
sprintf(interp->result, "%d", (FloodY <<4) + 8);
return (TCL_OK);
}
int SimCmdCrashX(ARGS)
{
int val;
if (argc != 2) {
return (TCL_ERROR);
}
sprintf(interp->result, "%d", (CrashX <<4) + 8);
return (TCL_OK);
}
int SimCmdCrashY(ARGS)
{
int val;
if (argc != 2) {
return (TCL_ERROR);
}
sprintf(interp->result, "%d", (CrashY <<4) + 8);
return (TCL_OK);
}
int SimCmdDollars(ARGS)
{
int val;
if (argc != 2) {
return (TCL_ERROR);
}
makeDollarDecimalStr(argv[1], interp->result);
return (TCL_OK);
}
int SimCmdDoAnimation(ARGS)
{
int val;
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
if ((Tcl_GetInt(interp, argv[2], &val) != TCL_OK)) {
return (TCL_ERROR);
}
DoAnimation = val;
MustUpdateOptions = 1; Kick();
}
sprintf(interp->result, "%d", DoAnimation);
return (TCL_OK);
}
int SimCmdDoMessages(ARGS)
{
int val;
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
if ((Tcl_GetInt(interp, argv[2], &val) != TCL_OK)) {
return (TCL_ERROR);
}
DoMessages = val;
MustUpdateOptions = 1; Kick();
}
sprintf(interp->result, "%d", DoMessages);
return (TCL_OK);
}
int SimCmdDoNotices(ARGS)
{
int val;
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
if ((Tcl_GetInt(interp, argv[2], &val) != TCL_OK)) {
return (TCL_ERROR);
}
DoNotices = val;
MustUpdateOptions = 1; Kick();
}
sprintf(interp->result, "%d", DoNotices);
return (TCL_OK);
}
int SimCmdRand(ARGS)
{
int val, r;
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
if ((Tcl_GetInt(interp, argv[2], &val) != TCL_OK)) {
return (TCL_ERROR);
}
r = Rand(val);
} else {
r = Rand16();
}
sprintf(interp->result, "%d", r);
return (TCL_OK);
}
int SimCmdPlatform(ARGS)
{
#ifdef MSDOS
sprintf(interp->result, "msdos");
#else
sprintf(interp->result, "unix");
#endif
return (TCL_OK);
}
int SimCmdVersion(ARGS)
{
sprintf(interp->result, MicropolisVersion);
return (TCL_OK);
}
int SimCmdOpenWebBrowser(ARGS)
{
int result = 1;
char buf[512];
if ((argc != 3) ||
(strlen(argv[2]) > 255)) {
return (TCL_ERROR);
}
sprintf(buf,
"netscape -no-about-splash '%s' &",
argv[2]);
result = system(buf);
sprintf(interp->result, "%d", result);
return (TCL_OK);
}
int SimCmdQuoteURL(ARGS)
{
int result = 1;
char buf[2048];
char *from, *to;
int ch;
static char *hexDigits =
"0123456789ABCDEF";
if ((argc != 3) ||
(strlen(argv[2]) > 255)) {
return (TCL_ERROR);
}
from = argv[2];
to = buf;
while ((ch = *(from++)) != '\0') {
if ((ch < 32) ||
(ch >= 128) ||
(ch == '+') ||
(ch == '%') ||
(ch == '&') ||
(ch == '<') ||
(ch == '>') ||
(ch == '"') ||
(ch == '\'')) {
*to++ = '%';
*to++ = hexDigits[(ch >> 4) & 0x0f];
*to++ = hexDigits[ch & 0x0f];
} else if (ch == 32) {
*to++ = '+';
} else {
*to++ = ch;
} // if
} // while
*to = '\0';
sprintf(interp->result, "%s", buf);
return (TCL_OK);
}
int SimCmdNeedRest(ARGS)
{
int needRest;
if ((argc != 2) && (argc != 3)) {
return (TCL_ERROR);
}
if (argc == 3) {
if (Tcl_GetInt(interp, argv[2], &needRest) != TCL_OK) {
return (TCL_ERROR);
}
NeedRest = needRest;
}
sprintf(interp->result, "%d", NeedRest);
return (TCL_OK);
}
int SimCmdMultiPlayerMode(ARGS)
{
/* This is read-only because it's specified on
the command line and effects how the user
interface is initialized. */
if (argc != 2) {
return (TCL_ERROR);
}
sprintf(interp->result, "%d", MultiPlayerMode);
return (TCL_OK);
}
/************************************************************************/
int
SimCmd(CLIENT_ARGS)
{
Tcl_HashEntry *ent;
int result = TCL_OK;
int (*cmd)();
if (argc < 2) {
return TCL_ERROR;
}
if (ent = Tcl_FindHashEntry(&SimCmds, argv[1])) {
cmd = (int (*)())ent->clientData;
result = cmd(interp, argc, argv);
} else {
result = TCL_ERROR;
}
return result;
}
sim_command_init()
{
int new;
Tcl_CreateCommand(tk_mainInterp, "sim", SimCmd,
(ClientData)MainWindow, (void (*)()) NULL);
Tcl_InitHashTable(&SimCmds, TCL_STRING_KEYS);
#define SIM_CMD(name) HASHED_CMD(Sim, name)
SIM_CMD(GameStarted);
SIM_CMD(InitGame);
SIM_CMD(SaveCity);
SIM_CMD(ReallyQuit);
SIM_CMD(UpdateHeads);
SIM_CMD(UpdateMaps);
SIM_CMD(RedrawEditors);
SIM_CMD(RedrawMaps);
SIM_CMD(UpdateEditors);
SIM_CMD(UpdateGraphs);
SIM_CMD(UpdateEvaluation);
SIM_CMD(UpdateBudget);
SIM_CMD(UpdateBudgetWindow);
SIM_CMD(DoBudget);
SIM_CMD(DoBudgetFromMenu);
SIM_CMD(Pause);
SIM_CMD(Resume);
SIM_CMD(StartBulldozer);
SIM_CMD(StopBulldozer);
SIM_CMD(MakeFire);
SIM_CMD(MakeFlood);
SIM_CMD(MakeTornado);
SIM_CMD(MakeEarthquake);
SIM_CMD(MakeMonster);
SIM_CMD(MakeMeltdown);
SIM_CMD(FireBomb);
SIM_CMD(SoundOff);
SIM_CMD(GenerateNewCity);
SIM_CMD(GenerateSomeCity);
SIM_CMD(TreeLevel);
SIM_CMD(LakeLevel);
SIM_CMD(CurveLevel);
SIM_CMD(CreateIsland);
SIM_CMD(ClearMap);
SIM_CMD(ClearUnnatural);
SIM_CMD(SmoothTrees);
SIM_CMD(SmoothWater);
SIM_CMD(SmoothRiver);
SIM_CMD(LoadScenario);
SIM_CMD(LoadCity);
SIM_CMD(SaveCityAs);
SIM_CMD(MakeExplosion);
SIM_CMD(CityName);
SIM_CMD(CityFileName);
SIM_CMD(GameLevel);
SIM_CMD(Speed);
SIM_CMD(Skips);
SIM_CMD(Skip);
SIM_CMD(WorldX);
SIM_CMD(WorldY);
SIM_CMD(Delay);
SIM_CMD(HeatSteps);
SIM_CMD(HeatFlow);
SIM_CMD(HeatRule);
#ifdef CAM
SIM_CMD(JustCam);
#endif
#ifdef NET
SIM_CMD(ListenTo);
SIM_CMD(HearFrom);
#endif
SIM_CMD(Funds);
SIM_CMD(TaxRate);
SIM_CMD(FireFund);
SIM_CMD(PoliceFund);
SIM_CMD(RoadFund);
SIM_CMD(Year);
SIM_CMD(AutoBudget);
SIM_CMD(AutoGoto);
SIM_CMD(AutoBulldoze);
SIM_CMD(Disasters);
SIM_CMD(Sound);
SIM_CMD(Flush);
SIM_CMD(FlushStyle);
SIM_CMD(DonDither);
SIM_CMD(DoOverlay);
SIM_CMD(MonsterGoal);
SIM_CMD(HelicopterGoal);
SIM_CMD(MonsterDirection);
SIM_CMD(EraseOverlay);
SIM_CMD(Tile);
SIM_CMD(Fill);
SIM_CMD(DynamicData);
SIM_CMD(ResetDynamic);
SIM_CMD(Performance);
SIM_CMD(CollapseMotion);
SIM_CMD(Update);
SIM_CMD(OverRide);
SIM_CMD(Expensive);
SIM_CMD(Players);
SIM_CMD(Votes);
SIM_CMD(BobHeight);
SIM_CMD(PendingTool);
SIM_CMD(PendingX);
SIM_CMD(PendingY);
SIM_CMD(Displays);
SIM_CMD(LandValue);
SIM_CMD(Traffic);
SIM_CMD(Crime);
SIM_CMD(Unemployment);
SIM_CMD(Fires);
SIM_CMD(Pollution);
SIM_CMD(PolMaxX);
SIM_CMD(PolMaxY);
SIM_CMD(TrafMaxX);
SIM_CMD(TrafMaxY);
SIM_CMD(MeltX);
SIM_CMD(MeltY);
SIM_CMD(CrimeMaxX);
SIM_CMD(CrimeMaxY);
SIM_CMD(CenterX);
SIM_CMD(CenterY);
SIM_CMD(FloodX);
SIM_CMD(FloodY);
SIM_CMD(CrashX);
SIM_CMD(CrashY);
SIM_CMD(Dollars);
SIM_CMD(DoAnimation);
SIM_CMD(DoMessages);
SIM_CMD(DoNotices);
SIM_CMD(Rand);
SIM_CMD(Platform);
SIM_CMD(Version);
SIM_CMD(OpenWebBrowser);
SIM_CMD(QuoteURL);
SIM_CMD(NeedRest);
SIM_CMD(MultiPlayerMode);
}
| 412 | 0.830402 | 1 | 0.830402 | game-dev | MEDIA | 0.533935 | game-dev | 0.759893 | 1 | 0.759893 |
kbarni/kindlepuzzles | 75,280 | unequal.c | /*
* unequal.c
*
* Implementation of 'Futoshiki', a puzzle featured in the Guardian.
*
* TTD:
* add multiple-links-on-same-col/row solver nous
* Optimise set solver to use bit operations instead
*
* Guardian puzzles of note:
* #1: 5:0,0L,0L,0,0,0R,0,0L,0D,0L,0R,0,2,0D,0,0,0,0,0,0,0U,0,0,0,0U,
* #2: 5:0,0,0,4L,0L,0,2LU,0L,0U,0,0,0U,0,0,0,0,0D,0,3LRUD,0,0R,3,0L,0,0,
* #3: (reprint of #2)
* #4:
* #5: 5:0,0,0,0,0,0,2,0U,3U,0U,0,0,3,0,0,0,3,0D,4,0,0,0L,0R,0,0,
* #6: 5:0D,0L,0,0R,0,0,0D,0,3,0D,0,0R,0,0R,0D,0U,0L,0,1,2,0,0,0U,0,0L,
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#ifdef NO_TGMATH_H
# include <math.h>
#else
# include <tgmath.h>
#endif
#include "puzzles.h"
#include "latin.h" /* contains typedef for digit */
/* ----------------------------------------------------------
* Constant and structure definitions
*/
#define FLASH_TIME 0.4F
#define PREFERRED_TILE_SIZE 32
#define TILE_SIZE (ds->tilesize)
#define GAP_SIZE (TILE_SIZE/2)
#define SQUARE_SIZE (TILE_SIZE + GAP_SIZE)
#define BORDER (TILE_SIZE / 2)
#define COORD(x) ( (x) * SQUARE_SIZE + BORDER )
#define FROMCOORD(x) ( ((x) - BORDER + SQUARE_SIZE) / SQUARE_SIZE - 1 )
#define GRID(p,w,x,y) ((p)->w[((y)*(p)->order)+(x)])
#define GRID3(p,w,x,y,z) ((p)->w[ (((x)*(p)->order+(y))*(p)->order+(z)) ])
#define HINT(p,x,y,n) GRID3(p, hints, x, y, n)
enum {
COL_BACKGROUND,
COL_GRID,
COL_TEXT, COL_GUESS, COL_ERROR, COL_PENCIL,
COL_HIGHLIGHT, COL_LOWLIGHT, COL_SPENT = COL_LOWLIGHT,
NCOLOURS
};
typedef enum {
MODE_UNEQUAL, /* Puzzle indicators are 'greater-than'. */
MODE_ADJACENT /* Puzzle indicators are 'adjacent number'. */
} Mode;
enum {
PREF_PENCIL_KEEP_HIGHLIGHT,
N_PREF_ITEMS
};
struct game_params {
int order; /* Size of latin square */
int diff; /* Difficulty */
Mode mode;
};
#define F_IMMUTABLE 1 /* passed in as game description */
#define F_ADJ_UP 2
#define F_ADJ_RIGHT 4
#define F_ADJ_DOWN 8
#define F_ADJ_LEFT 16
#define F_ERROR 32
#define F_ERROR_UP 64
#define F_ERROR_RIGHT 128
#define F_ERROR_DOWN 256
#define F_ERROR_LEFT 512
#define F_SPENT_UP 1024
#define F_SPENT_RIGHT 2048
#define F_SPENT_DOWN 4096
#define F_SPENT_LEFT 8192
#define ADJ_TO_SPENT(x) ((x) << 9)
#define F_ERROR_MASK (F_ERROR|F_ERROR_UP|F_ERROR_RIGHT|F_ERROR_DOWN|F_ERROR_LEFT)
#define F_SPENT_MASK (F_SPENT_UP|F_SPENT_RIGHT|F_SPENT_DOWN|F_SPENT_LEFT)
struct game_state {
int order;
bool completed, cheated;
Mode mode;
digit *nums; /* actual numbers (size order^2) */
unsigned char *hints; /* remaining possiblities (size order^3) */
unsigned int *flags; /* flags (size order^2) */
};
/* ----------------------------------------------------------
* Game parameters and presets
*/
/* Steal the method from map.c for difficulty levels. */
#define DIFFLIST(A) \
A(LATIN,Trivial,NULL,t) \
A(EASY,Easy,solver_easy, e) \
A(SET,Tricky,solver_set, k) \
A(EXTREME,Extreme,NULL,x) \
A(RECURSIVE,Recursive,NULL,r)
#define ENUM(upper,title,func,lower) DIFF_ ## upper,
#define TITLE(upper,title,func,lower) #title,
#define ENCODE(upper,title,func,lower) #lower
#define CONFIG(upper,title,func,lower) ":" #title
enum { DIFFLIST(ENUM) DIFFCOUNT, DIFF_IMPOSSIBLE = diff_impossible, DIFF_AMBIGUOUS = diff_ambiguous, DIFF_UNFINISHED = diff_unfinished };
static char const *const unequal_diffnames[] = { DIFFLIST(TITLE) };
static char const unequal_diffchars[] = DIFFLIST(ENCODE);
#define DIFFCONFIG DIFFLIST(CONFIG)
#define DEFAULT_PRESET 0
static const struct game_params unequal_presets[] = {
{ 4, DIFF_EASY, 0 },
{ 5, DIFF_EASY, 0 },
{ 5, DIFF_SET, 0 },
{ 5, DIFF_SET, 1 },
{ 5, DIFF_EXTREME, 0 },
{ 6, DIFF_EASY, 0 },
{ 6, DIFF_SET, 0 },
{ 6, DIFF_SET, 1 },
{ 6, DIFF_EXTREME, 0 },
{ 7, DIFF_SET, 0 },
{ 7, DIFF_SET, 1 },
{ 7, DIFF_EXTREME, 0 }
};
static bool game_fetch_preset(int i, char **name, game_params **params)
{
game_params *ret;
char buf[80];
if (i < 0 || i >= lenof(unequal_presets))
return false;
ret = snew(game_params);
*ret = unequal_presets[i]; /* structure copy */
sprintf(buf, "%s: %dx%d %s",
ret->mode == MODE_ADJACENT ? "Adjacent" : "Unequal",
ret->order, ret->order,
unequal_diffnames[ret->diff]);
*name = dupstr(buf);
*params = ret;
return true;
}
static game_params *default_params(void)
{
game_params *ret;
char *name;
if (!game_fetch_preset(DEFAULT_PRESET, &name, &ret)) return NULL;
sfree(name);
return ret;
}
static void free_params(game_params *params)
{
sfree(params);
}
static game_params *dup_params(const game_params *params)
{
game_params *ret = snew(game_params);
*ret = *params; /* structure copy */
return ret;
}
static void decode_params(game_params *ret, char const *string)
{
char const *p = string;
ret->order = atoi(p);
while (*p && isdigit((unsigned char)*p)) p++;
if (*p == 'a') {
p++;
ret->mode = MODE_ADJACENT;
} else
ret->mode = MODE_UNEQUAL;
if (*p == 'd') {
int i;
p++;
ret->diff = DIFFCOUNT+1; /* ...which is invalid */
if (*p) {
for (i = 0; i < DIFFCOUNT; i++) {
if (*p == unequal_diffchars[i])
ret->diff = i;
}
p++;
}
}
}
static char *encode_params(const game_params *params, bool full)
{
char ret[80];
sprintf(ret, "%d", params->order);
if (params->mode == MODE_ADJACENT)
sprintf(ret + strlen(ret), "a");
if (full)
sprintf(ret + strlen(ret), "d%c", unequal_diffchars[params->diff]);
return dupstr(ret);
}
static config_item *game_configure(const game_params *params)
{
config_item *ret;
char buf[80];
ret = snewn(4, config_item);
ret[0].name = "Mode";
ret[0].type = C_CHOICES;
ret[0].u.choices.choicenames = ":Unequal:Adjacent";
ret[0].u.choices.selected = params->mode;
ret[1].name = "Size (s*s)";
ret[1].type = C_STRING;
sprintf(buf, "%d", params->order);
ret[1].u.string.sval = dupstr(buf);
ret[2].name = "Difficulty";
ret[2].type = C_CHOICES;
ret[2].u.choices.choicenames = DIFFCONFIG;
ret[2].u.choices.selected = params->diff;
ret[3].name = NULL;
ret[3].type = C_END;
return ret;
}
static game_params *custom_params(const config_item *cfg)
{
game_params *ret = snew(game_params);
ret->mode = cfg[0].u.choices.selected;
ret->order = atoi(cfg[1].u.string.sval);
ret->diff = cfg[2].u.choices.selected;
return ret;
}
static const char *validate_params(const game_params *params, bool full)
{
if (params->order < 3 || params->order > 32)
return "Order must be between 3 and 32";
if (params->diff >= DIFFCOUNT)
return "Unknown difficulty rating";
if (params->order < 5 && params->mode == MODE_ADJACENT &&
params->diff >= DIFF_SET)
return "Order must be at least 5 for Adjacent puzzles of this difficulty.";
return NULL;
}
/* ----------------------------------------------------------
* Various utility functions
*/
static const struct { unsigned int f, fo, fe; int dx, dy; char c, ac; } adjthan[] = {
{ F_ADJ_UP, F_ADJ_DOWN, F_ERROR_UP, 0, -1, '^', '-' },
{ F_ADJ_RIGHT, F_ADJ_LEFT, F_ERROR_RIGHT, 1, 0, '>', '|' },
{ F_ADJ_DOWN, F_ADJ_UP, F_ERROR_DOWN, 0, 1, 'v', '-' },
{ F_ADJ_LEFT, F_ADJ_RIGHT, F_ERROR_LEFT, -1, 0, '<', '|' }
};
static game_state *blank_game(int order, Mode mode)
{
game_state *state = snew(game_state);
int o2 = order*order, o3 = o2*order;
state->order = order;
state->mode = mode;
state->completed = false;
state->cheated = false;
state->nums = snewn(o2, digit);
state->hints = snewn(o3, unsigned char);
state->flags = snewn(o2, unsigned int);
memset(state->nums, 0, o2 * sizeof(digit));
memset(state->hints, 0, o3);
memset(state->flags, 0, o2 * sizeof(unsigned int));
return state;
}
static game_state *dup_game(const game_state *state)
{
game_state *ret = blank_game(state->order, state->mode);
int o2 = state->order*state->order, o3 = o2*state->order;
memcpy(ret->nums, state->nums, o2 * sizeof(digit));
memcpy(ret->hints, state->hints, o3);
memcpy(ret->flags, state->flags, o2 * sizeof(unsigned int));
return ret;
}
static void free_game(game_state *state)
{
sfree(state->nums);
sfree(state->hints);
sfree(state->flags);
sfree(state);
}
#define CHECKG(x,y) grid[(y)*o+(x)]
/* Returns false if it finds an error, true if ok. */
static bool check_num_adj(digit *grid, game_state *state,
int x, int y, bool me)
{
unsigned int f = GRID(state, flags, x, y);
bool ret = true;
int i, o = state->order;
for (i = 0; i < 4; i++) {
int dx = adjthan[i].dx, dy = adjthan[i].dy, n, dn;
if (x+dx < 0 || x+dx >= o || y+dy < 0 || y+dy >= o)
continue;
n = CHECKG(x, y);
dn = CHECKG(x+dx, y+dy);
assert (n != 0);
if (dn == 0) continue;
if (state->mode == MODE_ADJACENT) {
int gd = abs(n-dn);
if ((f & adjthan[i].f) && (gd != 1)) {
debug(("check_adj error (%d,%d):%d should be | (%d,%d):%d",
x, y, n, x+dx, y+dy, dn));
if (me) GRID(state, flags, x, y) |= adjthan[i].fe;
ret = false;
}
if (!(f & adjthan[i].f) && (gd == 1)) {
debug(("check_adj error (%d,%d):%d should not be | (%d,%d):%d",
x, y, n, x+dx, y+dy, dn));
if (me) GRID(state, flags, x, y) |= adjthan[i].fe;
ret = false;
}
} else {
if ((f & adjthan[i].f) && (n <= dn)) {
debug(("check_adj error (%d,%d):%d not > (%d,%d):%d",
x, y, n, x+dx, y+dy, dn));
if (me) GRID(state, flags, x, y) |= adjthan[i].fe;
ret = false;
}
}
}
return ret;
}
/* Returns false if it finds an error, true if ok. */
static bool check_num_error(digit *grid, game_state *state,
int x, int y, bool mark_errors)
{
int o = state->order;
int xx, yy, val = CHECKG(x,y);
bool ret = true;
assert(val != 0);
/* check for dups in same column. */
for (yy = 0; yy < state->order; yy++) {
if (yy == y) continue;
if (CHECKG(x,yy) == val) ret = false;
}
/* check for dups in same row. */
for (xx = 0; xx < state->order; xx++) {
if (xx == x) continue;
if (CHECKG(xx,y) == val) ret = false;
}
if (!ret) {
debug(("check_num_error (%d,%d) duplicate %d", x, y, val));
if (mark_errors) GRID(state, flags, x, y) |= F_ERROR;
}
return ret;
}
/* Returns: -1 for 'wrong'
* 0 for 'incomplete'
* 1 for 'complete and correct'
*/
static int check_complete(digit *grid, game_state *state, bool mark_errors)
{
int x, y, ret = 1, o = state->order;
if (mark_errors)
assert(grid == state->nums);
for (x = 0; x < state->order; x++) {
for (y = 0; y < state->order; y++) {
if (mark_errors)
GRID(state, flags, x, y) &= ~F_ERROR_MASK;
if (grid[y*o+x] == 0) {
ret = 0;
} else {
if (!check_num_error(grid, state, x, y, mark_errors)) ret = -1;
if (!check_num_adj(grid, state, x, y, mark_errors)) ret = -1;
}
}
}
if (ret == 1 && latin_check(grid, o))
ret = -1;
return ret;
}
static char n2c(digit n, int order) {
if (n == 0) return ' ';
if (order < 10) {
if (n < 10) return '0' + n;
} else {
if (n < 11) return '0' + n-1;
n -= 11;
if (n <= 26) return 'A' + n;
}
return '?';
}
/* should be 'digit', but includes -1 for 'not a digit'.
* Includes keypresses (0 especially) for interpret_move. */
static int c2n(int c, int order) {
if (c < 0 || c > 0xff)
return -1;
if (c == ' ' || c == '\b')
return 0;
if (order < 10) {
if (c >= '0' && c <= '9')
return (int)(c - '0');
} else {
if (c >= '0' && c <= '9')
return (int)(c - '0' + 1);
if (c >= 'A' && c <= 'Z')
return (int)(c - 'A' + 11);
if (c >= 'a' && c <= 'z')
return (int)(c - 'a' + 11);
}
return -1;
}
static bool game_can_format_as_text_now(const game_params *params)
{
return true;
}
static char *game_text_format(const game_state *state)
{
int x, y, len, n;
char *ret, *p;
len = (state->order*2) * (state->order*2-1) + 1;
ret = snewn(len, char);
p = ret;
for (y = 0; y < state->order; y++) {
for (x = 0; x < state->order; x++) {
n = GRID(state, nums, x, y);
*p++ = n > 0 ? n2c(n, state->order) : '.';
if (x < (state->order-1)) {
if (state->mode == MODE_ADJACENT) {
*p++ = (GRID(state, flags, x, y) & F_ADJ_RIGHT) ? '|' : ' ';
} else {
if (GRID(state, flags, x, y) & F_ADJ_RIGHT)
*p++ = '>';
else if (GRID(state, flags, x+1, y) & F_ADJ_LEFT)
*p++ = '<';
else
*p++ = ' ';
}
}
}
*p++ = '\n';
if (y < (state->order-1)) {
for (x = 0; x < state->order; x++) {
if (state->mode == MODE_ADJACENT) {
*p++ = (GRID(state, flags, x, y) & F_ADJ_DOWN) ? '-' : ' ';
} else {
if (GRID(state, flags, x, y) & F_ADJ_DOWN)
*p++ = 'v';
else if (GRID(state, flags, x, y+1) & F_ADJ_UP)
*p++ = '^';
else
*p++ = ' ';
}
if (x < state->order-1)
*p++ = ' ';
}
*p++ = '\n';
}
}
*p++ = '\0';
assert(p - ret == len);
return ret;
}
#ifdef STANDALONE_SOLVER
static void game_debug(game_state *state)
{
char *dbg = game_text_format(state);
printf("%s", dbg);
sfree(dbg);
}
#endif
/* ----------------------------------------------------------
* Solver.
*/
struct solver_link {
int len, gx, gy, lx, ly;
};
struct solver_ctx {
game_state *state;
int nlinks, alinks;
struct solver_link *links;
};
static void solver_add_link(struct solver_ctx *ctx,
int gx, int gy, int lx, int ly, int len)
{
if (ctx->alinks < ctx->nlinks+1) {
ctx->alinks = ctx->alinks*2 + 1;
/*debug(("resizing ctx->links, new size %d", ctx->alinks));*/
ctx->links = sresize(ctx->links, ctx->alinks, struct solver_link);
}
ctx->links[ctx->nlinks].gx = gx;
ctx->links[ctx->nlinks].gy = gy;
ctx->links[ctx->nlinks].lx = lx;
ctx->links[ctx->nlinks].ly = ly;
ctx->links[ctx->nlinks].len = len;
ctx->nlinks++;
/*debug(("Adding new link: len %d (%d,%d) < (%d,%d), nlinks now %d",
len, lx, ly, gx, gy, ctx->nlinks));*/
}
static struct solver_ctx *new_ctx(game_state *state)
{
struct solver_ctx *ctx = snew(struct solver_ctx);
int o = state->order;
int i, x, y;
unsigned int f;
ctx->nlinks = ctx->alinks = 0;
ctx->links = NULL;
ctx->state = state;
if (state->mode == MODE_ADJACENT)
return ctx; /* adjacent mode doesn't use links. */
for (x = 0; x < o; x++) {
for (y = 0; y < o; y++) {
f = GRID(state, flags, x, y);
for (i = 0; i < 4; i++) {
if (f & adjthan[i].f)
solver_add_link(ctx, x, y, x+adjthan[i].dx, y+adjthan[i].dy, 1);
}
}
}
return ctx;
}
static void *clone_ctx(void *vctx)
{
struct solver_ctx *ctx = (struct solver_ctx *)vctx;
return new_ctx(ctx->state);
}
static void free_ctx(void *vctx)
{
struct solver_ctx *ctx = (struct solver_ctx *)vctx;
if (ctx->links) sfree(ctx->links);
sfree(ctx);
}
static void solver_nminmax(struct latin_solver *solver,
int x, int y, int *min_r, int *max_r,
unsigned char **ns_r)
{
int o = solver->o, min = o, max = 0, n;
unsigned char *ns;
assert(x >= 0 && y >= 0 && x < o && y < o);
ns = solver->cube + cubepos(x,y,1);
if (grid(x,y) > 0) {
min = max = grid(x,y)-1;
} else {
for (n = 0; n < o; n++) {
if (ns[n]) {
if (n > max) max = n;
if (n < min) min = n;
}
}
}
if (min_r) *min_r = min;
if (max_r) *max_r = max;
if (ns_r) *ns_r = ns;
}
static int solver_links(struct latin_solver *solver, void *vctx)
{
struct solver_ctx *ctx = (struct solver_ctx *)vctx;
int i, j, lmin, gmax, nchanged = 0;
unsigned char *gns, *lns;
struct solver_link *link;
for (i = 0; i < ctx->nlinks; i++) {
link = &ctx->links[i];
solver_nminmax(solver, link->gx, link->gy, NULL, &gmax, &gns);
solver_nminmax(solver, link->lx, link->ly, &lmin, NULL, &lns);
for (j = 0; j < solver->o; j++) {
/* For the 'greater' end of the link, discount all numbers
* too small to satisfy the inequality. */
if (gns[j]) {
if (j < (lmin+link->len)) {
#ifdef STANDALONE_SOLVER
if (solver_show_working) {
printf("%*slink elimination, (%d,%d) > (%d,%d):\n",
solver_recurse_depth*4, "",
link->gx+1, link->gy+1, link->lx+1, link->ly+1);
printf("%*s ruling out %d at (%d,%d)\n",
solver_recurse_depth*4, "",
j+1, link->gx+1, link->gy+1);
}
#endif
cube(link->gx, link->gy, j+1) = false;
nchanged++;
}
}
/* For the 'lesser' end of the link, discount all numbers
* too large to satisfy inequality. */
if (lns[j]) {
if (j > (gmax-link->len)) {
#ifdef STANDALONE_SOLVER
if (solver_show_working) {
printf("%*slink elimination, (%d,%d) > (%d,%d):\n",
solver_recurse_depth*4, "",
link->gx+1, link->gy+1, link->lx+1, link->ly+1);
printf("%*s ruling out %d at (%d,%d)\n",
solver_recurse_depth*4, "",
j+1, link->lx+1, link->ly+1);
}
#endif
cube(link->lx, link->ly, j+1) = false;
nchanged++;
}
}
}
}
return nchanged;
}
static int solver_adjacent(struct latin_solver *solver, void *vctx)
{
struct solver_ctx *ctx = (struct solver_ctx *)vctx;
int nchanged = 0, x, y, i, n, o = solver->o, nx, ny, gd;
/* Update possible values based on known values and adjacency clues. */
for (x = 0; x < o; x++) {
for (y = 0; y < o; y++) {
if (grid(x, y) == 0) continue;
/* We have a definite number here. Make sure that any
* adjacent possibles reflect the adjacent/non-adjacent clue. */
for (i = 0; i < 4; i++) {
bool isadjacent =
(GRID(ctx->state, flags, x, y) & adjthan[i].f);
nx = x + adjthan[i].dx, ny = y + adjthan[i].dy;
if (nx < 0 || ny < 0 || nx >= o || ny >= o)
continue;
for (n = 0; n < o; n++) {
/* Continue past numbers the adjacent square _could_ be,
* given the clue we have. */
gd = abs((n+1) - grid(x, y));
if (isadjacent && (gd == 1)) continue;
if (!isadjacent && (gd != 1)) continue;
if (!cube(nx, ny, n+1))
continue; /* already discounted this possibility. */
#ifdef STANDALONE_SOLVER
if (solver_show_working) {
printf("%*sadjacent elimination, (%d,%d):%d %s (%d,%d):\n",
solver_recurse_depth*4, "",
x+1, y+1, grid(x, y), isadjacent ? "|" : "!|", nx+1, ny+1);
printf("%*s ruling out %d at (%d,%d)\n",
solver_recurse_depth*4, "", n+1, nx+1, ny+1);
}
#endif
cube(nx, ny, n+1) = false;
nchanged++;
}
}
}
}
return nchanged;
}
static int solver_adjacent_set(struct latin_solver *solver, void *vctx)
{
struct solver_ctx *ctx = (struct solver_ctx *)vctx;
int x, y, i, n, nn, o = solver->o, nx, ny, gd;
int nchanged = 0, *scratch = snewn(o, int);
/* Update possible values based on other possible values
* of adjacent squares, and adjacency clues. */
for (x = 0; x < o; x++) {
for (y = 0; y < o; y++) {
for (i = 0; i < 4; i++) {
bool isadjacent =
(GRID(ctx->state, flags, x, y) & adjthan[i].f);
nx = x + adjthan[i].dx, ny = y + adjthan[i].dy;
if (nx < 0 || ny < 0 || nx >= o || ny >= o)
continue;
/* We know the current possibles for the square (x,y)
* and also the adjacency clue from (x,y) to (nx,ny).
* Construct a maximum set of possibles for (nx,ny)
* in scratch, based on these constraints... */
memset(scratch, 0, o*sizeof(int));
for (n = 0; n < o; n++) {
if (!cube(x, y, n+1)) continue;
for (nn = 0; nn < o; nn++) {
if (n == nn) continue;
gd = abs(nn - n);
if (isadjacent && (gd != 1)) continue;
if (!isadjacent && (gd == 1)) continue;
scratch[nn] = 1;
}
}
/* ...and remove any possibilities for (nx,ny) that are
* currently set but are not indicated in scratch. */
for (n = 0; n < o; n++) {
if (scratch[n] == 1) continue;
if (!cube(nx, ny, n+1)) continue;
#ifdef STANDALONE_SOLVER
if (solver_show_working) {
printf("%*sadjacent possible elimination, (%d,%d) %s (%d,%d):\n",
solver_recurse_depth*4, "",
x+1, y+1, isadjacent ? "|" : "!|", nx+1, ny+1);
printf("%*s ruling out %d at (%d,%d)\n",
solver_recurse_depth*4, "", n+1, nx+1, ny+1);
}
#endif
cube(nx, ny, n+1) = false;
nchanged++;
}
}
}
}
return nchanged;
}
static int solver_easy(struct latin_solver *solver, void *vctx)
{
struct solver_ctx *ctx = (struct solver_ctx *)vctx;
if (ctx->state->mode == MODE_ADJACENT)
return solver_adjacent(solver, vctx);
else
return solver_links(solver, vctx);
}
static int solver_set(struct latin_solver *solver, void *vctx)
{
struct solver_ctx *ctx = (struct solver_ctx *)vctx;
if (ctx->state->mode == MODE_ADJACENT)
return solver_adjacent_set(solver, vctx);
else
return 0;
}
#define SOLVER(upper,title,func,lower) func,
static usersolver_t const unequal_solvers[] = { DIFFLIST(SOLVER) };
static bool unequal_valid(struct latin_solver *solver, void *vctx)
{
struct solver_ctx *ctx = (struct solver_ctx *)vctx;
if (ctx->state->mode == MODE_ADJACENT) {
int o = solver->o;
int x, y, nx, ny, v, nv, i;
for (x = 0; x+1 < o; x++) {
for (y = 0; y+1 < o; y++) {
v = grid(x, y);
for (i = 0; i < 4; i++) {
bool is_adj, should_be_adj;
should_be_adj =
(GRID(ctx->state, flags, x, y) & adjthan[i].f);
nx = x + adjthan[i].dx, ny = y + adjthan[i].dy;
if (nx < 0 || ny < 0 || nx >= o || ny >= o)
continue;
nv = grid(nx, ny);
is_adj = (labs(v - nv) == 1);
if (is_adj && !should_be_adj) {
#ifdef STANDALONE_SOLVER
if (solver_show_working)
printf("%*s(%d,%d):%d and (%d,%d):%d have "
"adjacent values, but should not\n",
solver_recurse_depth*4, "",
x+1, y+1, v, nx+1, ny+1, nv);
#endif
return false;
}
if (!is_adj && should_be_adj) {
#ifdef STANDALONE_SOLVER
if (solver_show_working)
printf("%*s(%d,%d):%d and (%d,%d):%d do not have "
"adjacent values, but should\n",
solver_recurse_depth*4, "",
x+1, y+1, v, nx+1, ny+1, nv);
#endif
return false;
}
}
}
}
} else {
int i;
for (i = 0; i < ctx->nlinks; i++) {
struct solver_link *link = &ctx->links[i];
int gv = grid(link->gx, link->gy);
int lv = grid(link->lx, link->ly);
if (gv <= lv) {
#ifdef STANDALONE_SOLVER
if (solver_show_working)
printf("%*s(%d,%d):%d should be greater than (%d,%d):%d, "
"but is not\n", solver_recurse_depth*4, "",
link->gx+1, link->gy+1, gv,
link->lx+1, link->ly+1, lv);
#endif
return false;
}
}
}
return true;
}
static int solver_state(game_state *state, int maxdiff)
{
struct solver_ctx *ctx = new_ctx(state);
struct latin_solver solver;
int diff;
if (latin_solver_alloc(&solver, state->nums, state->order))
diff = latin_solver_main(&solver, maxdiff,
DIFF_LATIN, DIFF_SET, DIFF_EXTREME,
DIFF_EXTREME, DIFF_RECURSIVE,
unequal_solvers, unequal_valid, ctx,
clone_ctx, free_ctx);
else
diff = DIFF_IMPOSSIBLE;
memcpy(state->hints, solver.cube, state->order*state->order*state->order);
free_ctx(ctx);
latin_solver_free(&solver);
if (diff == DIFF_IMPOSSIBLE)
return -1;
if (diff == DIFF_UNFINISHED)
return 0;
if (diff == DIFF_AMBIGUOUS)
return 2;
return 1;
}
static game_state *solver_hint(const game_state *state, int *diff_r,
int mindiff, int maxdiff)
{
game_state *ret = dup_game(state);
int diff, r = 0;
for (diff = mindiff; diff <= maxdiff; diff++) {
r = solver_state(ret, diff);
debug(("solver_state after %s %d", unequal_diffnames[diff], r));
if (r != 0) goto done;
}
done:
if (diff_r) *diff_r = (r > 0) ? diff : -1;
return ret;
}
/* ----------------------------------------------------------
* Game generation.
*/
static char *latin_desc(digit *sq, size_t order)
{
int o2 = order*order, i;
char *soln = snewn(o2+2, char);
soln[0] = 'S';
for (i = 0; i < o2; i++)
soln[i+1] = n2c(sq[i], order);
soln[o2+1] = '\0';
return soln;
}
/* returns true if it placed (or could have placed) clue. */
static bool gg_place_clue(game_state *state, int ccode, digit *latin, bool checkonly)
{
int loc = ccode / 5, which = ccode % 5;
int x = loc % state->order, y = loc / state->order;
assert(loc < state->order*state->order);
if (which == 4) { /* add number */
if (state->nums[loc] != 0) {
#ifdef STANDALONE_SOLVER
if (state->nums[loc] != latin[loc]) {
printf("inconsistency for (%d,%d): state %d latin %d\n",
x+1, y+1, state->nums[loc], latin[loc]);
}
#endif
assert(state->nums[loc] == latin[loc]);
return false;
}
if (!checkonly) {
state->nums[loc] = latin[loc];
}
} else { /* add flag */
int lx, ly, lloc;
if (state->mode == MODE_ADJACENT)
return false; /* never add flag clues in adjacent mode
(they're always all present) */
if (state->flags[loc] & adjthan[which].f)
return false; /* already has flag. */
lx = x + adjthan[which].dx;
ly = y + adjthan[which].dy;
if (lx < 0 || ly < 0 || lx >= state->order || ly >= state->order)
return false; /* flag compares to off grid */
lloc = loc + adjthan[which].dx + adjthan[which].dy*state->order;
if (latin[loc] <= latin[lloc])
return false; /* flag would be incorrect */
if (!checkonly) {
state->flags[loc] |= adjthan[which].f;
}
}
return true;
}
/* returns true if it removed (or could have removed) the clue. */
static bool gg_remove_clue(game_state *state, int ccode, bool checkonly)
{
int loc = ccode / 5, which = ccode % 5;
#ifdef STANDALONE_SOLVER
int x = loc % state->order, y = loc / state->order;
#endif
assert(loc < state->order*state->order);
if (which == 4) { /* remove number. */
if (state->nums[loc] == 0) return false;
if (!checkonly) {
#ifdef STANDALONE_SOLVER
if (solver_show_working)
printf("gg_remove_clue: removing %d at (%d,%d)",
state->nums[loc], x+1, y+1);
#endif
state->nums[loc] = 0;
}
} else { /* remove flag */
if (state->mode == MODE_ADJACENT)
return false; /* never remove clues in adjacent mode. */
if (!(state->flags[loc] & adjthan[which].f)) return false;
if (!checkonly) {
#ifdef STANDALONE_SOLVER
if (solver_show_working)
printf("gg_remove_clue: removing %c at (%d,%d)",
adjthan[which].c, x+1, y+1);
#endif
state->flags[loc] &= ~adjthan[which].f;
}
}
return true;
}
static int gg_best_clue(game_state *state, int *scratch, digit *latin)
{
int ls = state->order * state->order * 5;
int maxposs = 0, minclues = 5, best = -1, i, j;
int nposs, nclues, loc;
#ifdef STANDALONE_SOLVER
if (solver_show_working) {
game_debug(state);
latin_solver_debug(state->hints, state->order);
}
#endif
for (i = ls; i-- > 0 ;) {
if (!gg_place_clue(state, scratch[i], latin, true)) continue;
loc = scratch[i] / 5;
for (j = nposs = 0; j < state->order; j++) {
if (state->hints[loc*state->order + j]) nposs++;
}
for (j = nclues = 0; j < 4; j++) {
if (state->flags[loc] & adjthan[j].f) nclues++;
}
if ((nposs > maxposs) ||
(nposs == maxposs && nclues < minclues)) {
best = i; maxposs = nposs; minclues = nclues;
#ifdef STANDALONE_SOLVER
if (solver_show_working) {
int x = loc % state->order, y = loc / state->order;
printf("gg_best_clue: b%d (%d,%d) new best [%d poss, %d clues].\n",
best, x+1, y+1, nposs, nclues);
}
#endif
}
}
/* if we didn't solve, we must have 1 clue to place! */
assert(best != -1);
return best;
}
#ifdef STANDALONE_SOLVER
static int maxtries;
#define MAXTRIES maxtries
#else
#define MAXTRIES 50
#endif
static int gg_solved;
static int game_assemble(game_state *new, int *scratch, digit *latin,
int difficulty)
{
game_state *copy = dup_game(new);
int best;
if (difficulty >= DIFF_RECURSIVE) {
/* We mustn't use any solver that might guess answers;
* if it guesses wrongly but solves, gg_place_clue will
* get mighty confused. We will always trim clues down
* (making it more difficult) in game_strip, which doesn't
* have this problem. */
difficulty = DIFF_RECURSIVE-1;
}
#ifdef STANDALONE_SOLVER
if (solver_show_working) {
game_debug(new);
latin_solver_debug(new->hints, new->order);
}
#endif
while(1) {
gg_solved++;
if (solver_state(copy, difficulty) == 1) break;
best = gg_best_clue(copy, scratch, latin);
gg_place_clue(new, scratch[best], latin, false);
gg_place_clue(copy, scratch[best], latin, false);
}
free_game(copy);
#ifdef STANDALONE_SOLVER
if (solver_show_working) {
char *dbg = game_text_format(new);
printf("game_assemble: done, %d solver iterations:\n%s\n", gg_solved, dbg);
sfree(dbg);
}
#endif
return 0;
}
static void game_strip(game_state *new, int *scratch, digit *latin,
int difficulty)
{
int o = new->order, o2 = o*o, lscratch = o2*5, i;
game_state *copy = blank_game(new->order, new->mode);
/* For each symbol (if it exists in new), try and remove it and
* solve again; if we couldn't solve without it put it back. */
for (i = 0; i < lscratch; i++) {
if (!gg_remove_clue(new, scratch[i], false)) continue;
memcpy(copy->nums, new->nums, o2 * sizeof(digit));
memcpy(copy->flags, new->flags, o2 * sizeof(unsigned int));
gg_solved++;
if (solver_state(copy, difficulty) != 1) {
/* put clue back, we can't solve without it. */
bool ret = gg_place_clue(new, scratch[i], latin, false);
assert(ret);
} else {
#ifdef STANDALONE_SOLVER
if (solver_show_working)
printf("game_strip: clue was redundant.");
#endif
}
}
free_game(copy);
#ifdef STANDALONE_SOLVER
if (solver_show_working) {
char *dbg = game_text_format(new);
debug(("game_strip: done, %d solver iterations.", gg_solved));
debug(("%s", dbg));
sfree(dbg);
}
#endif
}
static void add_adjacent_flags(game_state *state, digit *latin)
{
int x, y, o = state->order;
/* All clues in adjacent mode are always present (the only variables are
* the numbers). This adds all the flags to state based on the supplied
* latin square. */
for (y = 0; y < o; y++) {
for (x = 0; x < o; x++) {
if (x < (o-1) && (abs(latin[y*o+x] - latin[y*o+x+1]) == 1)) {
GRID(state, flags, x, y) |= F_ADJ_RIGHT;
GRID(state, flags, x+1, y) |= F_ADJ_LEFT;
}
if (y < (o-1) && (abs(latin[y*o+x] - latin[(y+1)*o+x]) == 1)) {
GRID(state, flags, x, y) |= F_ADJ_DOWN;
GRID(state, flags, x, y+1) |= F_ADJ_UP;
}
}
}
}
static char *new_game_desc(const game_params *params_in, random_state *rs,
char **aux, bool interactive)
{
game_params params_copy = *params_in; /* structure copy */
game_params *params = ¶ms_copy;
digit *sq = NULL;
int i, x, y, retlen, k, nsol;
int o2 = params->order * params->order, ntries = 1;
int *scratch, lscratch = o2*5;
char *ret, buf[80];
game_state *state = blank_game(params->order, params->mode);
/* Generate a list of 'things to strip' (randomised later) */
scratch = snewn(lscratch, int);
/* Put the numbers (4 mod 5) before the inequalities (0-3 mod 5) */
for (i = 0; i < lscratch; i++) scratch[i] = (i%o2)*5 + 4 - (i/o2);
generate:
#ifdef STANDALONE_SOLVER
if (solver_show_working)
printf("new_game_desc: generating %s puzzle, ntries so far %d\n",
unequal_diffnames[params->diff], ntries);
#endif
if (sq) sfree(sq);
sq = latin_generate(params->order, rs);
latin_debug(sq, params->order);
/* Separately shuffle the numeric and inequality clues */
shuffle(scratch, lscratch/5, sizeof(int), rs);
shuffle(scratch+lscratch/5, 4*lscratch/5, sizeof(int), rs);
memset(state->nums, 0, o2 * sizeof(digit));
memset(state->flags, 0, o2 * sizeof(unsigned int));
if (state->mode == MODE_ADJACENT) {
/* All adjacency flags are always present. */
add_adjacent_flags(state, sq);
}
gg_solved = 0;
if (game_assemble(state, scratch, sq, params->diff) < 0)
goto generate;
game_strip(state, scratch, sq, params->diff);
if (params->diff > 0) {
game_state *copy = dup_game(state);
nsol = solver_state(copy, params->diff-1);
free_game(copy);
if (nsol > 0) {
#ifdef STANDALONE_SOLVER
if (solver_show_working)
printf("game_assemble: puzzle as generated is too easy.\n");
#endif
if (ntries < MAXTRIES) {
ntries++;
goto generate;
}
#ifdef STANDALONE_SOLVER
if (solver_show_working)
printf("Unable to generate %s %dx%d after %d attempts.\n",
unequal_diffnames[params->diff],
params->order, params->order, MAXTRIES);
#endif
params->diff--;
}
}
#ifdef STANDALONE_SOLVER
if (solver_show_working)
printf("new_game_desc: generated %s puzzle; %d attempts (%d solver).\n",
unequal_diffnames[params->diff], ntries, gg_solved);
#endif
ret = NULL; retlen = 0;
for (y = 0; y < params->order; y++) {
for (x = 0; x < params->order; x++) {
unsigned int f = GRID(state, flags, x, y);
k = sprintf(buf, "%d%s%s%s%s,",
GRID(state, nums, x, y),
(f & F_ADJ_UP) ? "U" : "",
(f & F_ADJ_RIGHT) ? "R" : "",
(f & F_ADJ_DOWN) ? "D" : "",
(f & F_ADJ_LEFT) ? "L" : "");
ret = sresize(ret, retlen + k + 1, char);
strcpy(ret + retlen, buf);
retlen += k;
}
}
*aux = latin_desc(sq, params->order);
free_game(state);
sfree(sq);
sfree(scratch);
return ret;
}
static game_state *load_game(const game_params *params, const char *desc,
const char **why_r)
{
game_state *state = blank_game(params->order, params->mode);
const char *p = desc;
int i = 0, n, o = params->order, x, y;
const char *why = NULL;
while (*p) {
while (*p >= 'a' && *p <= 'z') {
i += *p - 'a' + 1;
p++;
}
if (i >= o*o) {
why = "Too much data to fill grid"; goto fail;
}
if (*p < '0' || *p > '9') {
why = "Expecting number in game description"; goto fail;
}
n = atoi(p);
if (n < 0 || n > o) {
why = "Out-of-range number in game description"; goto fail;
}
state->nums[i] = (digit)n;
while (*p >= '0' && *p <= '9') p++; /* skip number */
if (state->nums[i] != 0)
state->flags[i] |= F_IMMUTABLE; /* === number set by game description */
while (*p == 'U' || *p == 'R' || *p == 'D' || *p == 'L') {
switch (*p) {
case 'U': state->flags[i] |= F_ADJ_UP; break;
case 'R': state->flags[i] |= F_ADJ_RIGHT; break;
case 'D': state->flags[i] |= F_ADJ_DOWN; break;
case 'L': state->flags[i] |= F_ADJ_LEFT; break;
default: why = "Expecting flag URDL in game description"; goto fail;
}
p++;
}
i++;
if (i < o*o && *p != ',') {
why = "Missing separator"; goto fail;
}
if (*p == ',') p++;
}
if (i < o*o) {
why = "Not enough data to fill grid"; goto fail;
}
i = 0;
for (y = 0; y < o; y++) {
for (x = 0; x < o; x++) {
for (n = 0; n < 4; n++) {
if (GRID(state, flags, x, y) & adjthan[n].f) {
int nx = x + adjthan[n].dx;
int ny = y + adjthan[n].dy;
/* a flag must not point us off the grid. */
if (nx < 0 || ny < 0 || nx >= o || ny >= o) {
why = "Flags go off grid"; goto fail;
}
if (params->mode == MODE_ADJACENT) {
/* if one cell is adjacent to another, the other must
* also be adjacent to the first. */
if (!(GRID(state, flags, nx, ny) & adjthan[n].fo)) {
why = "Flags contradicting each other"; goto fail;
}
} else {
/* if one cell is GT another, the other must _not_ also
* be GT the first. */
if (GRID(state, flags, nx, ny) & adjthan[n].fo) {
why = "Flags contradicting each other"; goto fail;
}
}
}
}
}
}
return state;
fail:
free_game(state);
if (why_r) *why_r = why;
return NULL;
}
static key_label *game_request_keys(const game_params *params, int *nkeys)
{
int i;
int order = params->order;
char off = (order > 9) ? '0' : '1';
key_label *keys = snewn(order + 1, key_label);
*nkeys = order + 1;
for(i = 0; i < order; i++) {
if (i==10) off = 'a'-10;
keys[i].button = i + off;
keys[i].label = NULL;
}
keys[order].button = '\b';
keys[order].label = NULL;
return keys;
}
static game_state *new_game(midend *me, const game_params *params,
const char *desc)
{
game_state *state = load_game(params, desc, NULL);
if (!state) {
assert("Unable to load ?validated game.");
return NULL;
}
return state;
}
static const char *validate_desc(const game_params *params, const char *desc)
{
const char *why = NULL;
game_state *dummy = load_game(params, desc, &why);
if (dummy) {
free_game(dummy);
assert(!why);
} else
assert(why);
return why;
}
static char *solve_game(const game_state *state, const game_state *currstate,
const char *aux, const char **error)
{
game_state *solved;
int r;
char *ret = NULL;
if (aux) return dupstr(aux);
solved = dup_game(state);
for (r = 0; r < state->order*state->order; r++) {
if (!(solved->flags[r] & F_IMMUTABLE))
solved->nums[r] = 0;
}
r = solver_state(solved, DIFFCOUNT-1); /* always use full solver */
if (r > 0) ret = latin_desc(solved->nums, solved->order);
free_game(solved);
return ret;
}
/* ----------------------------------------------------------
* Game UI input processing.
*/
struct game_ui {
int hx, hy; /* as for solo.c, highlight pos */
bool hshow, hpencil, hcursor; /* show state, type, and ?cursor. */
/*
* User preference option: if the user right-clicks in a square
* and presses a number key to add/remove a pencil mark, do we
* hide the mouse highlight again afterwards?
*
* Historically our answer was yes. The Android port prefers no.
* There are advantages both ways, depending how much you dislike
* the highlight cluttering your view. So it's a preference.
*/
bool pencil_keep_highlight;
};
static game_ui *new_ui(const game_state *state)
{
game_ui *ui = snew(game_ui);
ui->hx = ui->hy = 0;
ui->hpencil = false;
ui->hshow = ui->hcursor = getenv_bool("PUZZLES_SHOW_CURSOR", false);
ui->pencil_keep_highlight = false;
return ui;
}
static void free_ui(game_ui *ui)
{
sfree(ui);
}
static config_item *get_prefs(game_ui *ui)
{
config_item *ret;
ret = snewn(N_PREF_ITEMS+1, config_item);
ret[PREF_PENCIL_KEEP_HIGHLIGHT].name =
"Keep mouse highlight after changing a pencil mark";
ret[PREF_PENCIL_KEEP_HIGHLIGHT].kw = "pencil-keep-highlight";
ret[PREF_PENCIL_KEEP_HIGHLIGHT].type = C_BOOLEAN;
ret[PREF_PENCIL_KEEP_HIGHLIGHT].u.boolean.bval = ui->pencil_keep_highlight;
ret[N_PREF_ITEMS].name = NULL;
ret[N_PREF_ITEMS].type = C_END;
return ret;
}
static void set_prefs(game_ui *ui, const config_item *cfg)
{
ui->pencil_keep_highlight = cfg[PREF_PENCIL_KEEP_HIGHLIGHT].u.boolean.bval;
}
static void game_changed_state(game_ui *ui, const game_state *oldstate,
const game_state *newstate)
{
/* See solo.c; if we were pencil-mode highlighting and
* somehow a square has just been properly filled, cancel
* pencil mode. */
if (ui->hshow && ui->hpencil && !ui->hcursor &&
GRID(newstate, nums, ui->hx, ui->hy) != 0) {
ui->hshow = false;
}
}
static const char *current_key_label(const game_ui *ui,
const game_state *state, int button)
{
if (ui->hshow && IS_CURSOR_SELECT(button))
return ui->hpencil ? "Ink" : "Pencil";
return "";
}
struct game_drawstate {
int tilesize, order;
bool started;
Mode mode;
digit *nums; /* copy of nums, o^2 */
unsigned char *hints; /* copy of hints, o^3 */
unsigned int *flags; /* o^2 */
int hx, hy;
bool hshow, hpencil; /* as for game_ui. */
bool hflash;
};
static char *interpret_move(const game_state *state, game_ui *ui,
const game_drawstate *ds,
int ox, int oy, int button)
{
int x = FROMCOORD(ox), y = FROMCOORD(oy), n;
char buf[80];
bool shift_or_control = button & (MOD_SHFT | MOD_CTRL);
button = STRIP_BUTTON_MODIFIERS(button);
if (x >= 0 && x < ds->order && y >= 0 && y < ds->order && IS_MOUSE_DOWN(button)) {
if (oy - COORD(y) > TILE_SIZE && ox - COORD(x) > TILE_SIZE)
return NULL;
if (oy - COORD(y) > TILE_SIZE) {
if (GRID(state, flags, x, y) & F_ADJ_DOWN)
sprintf(buf, "F%d,%d,%d", x, y, F_SPENT_DOWN);
else if (y + 1 < ds->order && GRID(state, flags, x, y + 1) & F_ADJ_UP)
sprintf(buf, "F%d,%d,%d", x, y + 1, F_SPENT_UP);
else return NULL;
return dupstr(buf);
}
if (ox - COORD(x) > TILE_SIZE) {
if (GRID(state, flags, x, y) & F_ADJ_RIGHT)
sprintf(buf, "F%d,%d,%d", x, y, F_SPENT_RIGHT);
else if (x + 1 < ds->order && GRID(state, flags, x + 1, y) & F_ADJ_LEFT)
sprintf(buf, "F%d,%d,%d", x + 1, y, F_SPENT_LEFT);
else return NULL;
return dupstr(buf);
}
if (button == LEFT_BUTTON) {
/* normal highlighting for non-immutable squares */
if (GRID(state, flags, x, y) & F_IMMUTABLE)
ui->hshow = false;
else if (x == ui->hx && y == ui->hy &&
ui->hshow && !ui->hpencil)
ui->hshow = false;
else {
ui->hx = x; ui->hy = y; ui->hpencil = false;
ui->hshow = true;
}
ui->hcursor = false;
return MOVE_UI_UPDATE;
}
if (button == RIGHT_BUTTON) {
/* pencil highlighting for non-filled squares */
if (GRID(state, nums, x, y) != 0)
ui->hshow = false;
else if (x == ui->hx && y == ui->hy &&
ui->hshow && ui->hpencil)
ui->hshow = false;
else {
ui->hx = x; ui->hy = y; ui->hpencil = true;
ui->hshow = true;
}
ui->hcursor = false;
return MOVE_UI_UPDATE;
}
}
if (IS_CURSOR_MOVE(button)) {
if (shift_or_control) {
int nx = ui->hx, ny = ui->hy, i;
bool self;
move_cursor(button, &nx, &ny, ds->order, ds->order, false, NULL);
ui->hshow = true;
ui->hcursor = true;
for (i = 0; i < 4 && (nx != ui->hx + adjthan[i].dx ||
ny != ui->hy + adjthan[i].dy); ++i);
if (i == 4)
return MOVE_UI_UPDATE; /* invalid direction, i.e. out of
* the board */
if (!(GRID(state, flags, ui->hx, ui->hy) & adjthan[i].f ||
GRID(state, flags, nx, ny ) & adjthan[i].fo))
return MOVE_UI_UPDATE; /* no clue to toggle */
if (state->mode == MODE_ADJACENT)
self = (adjthan[i].dx >= 0 && adjthan[i].dy >= 0);
else
self = (GRID(state, flags, ui->hx, ui->hy) & adjthan[i].f);
if (self)
sprintf(buf, "F%d,%d,%u", ui->hx, ui->hy,
ADJ_TO_SPENT(adjthan[i].f));
else
sprintf(buf, "F%d,%d,%u", nx, ny,
ADJ_TO_SPENT(adjthan[i].fo));
return dupstr(buf);
} else {
ui->hcursor = true;
return move_cursor(button, &ui->hx, &ui->hy, ds->order, ds->order,
false, &ui->hshow);
}
}
if (ui->hshow && IS_CURSOR_SELECT(button)) {
ui->hpencil = !ui->hpencil;
ui->hcursor = true;
return MOVE_UI_UPDATE;
}
n = c2n(button, state->order);
if (ui->hshow && n >= 0 && n <= ds->order) {
debug(("button %d, cbutton %d", button, (int)((char)button)));
debug(("n %d, h (%d,%d) p %d flags 0x%x nums %d",
n, ui->hx, ui->hy, ui->hpencil,
GRID(state, flags, ui->hx, ui->hy),
GRID(state, nums, ui->hx, ui->hy)));
if (GRID(state, flags, ui->hx, ui->hy) & F_IMMUTABLE)
return NULL; /* can't edit immutable square (!) */
if (ui->hpencil && GRID(state, nums, ui->hx, ui->hy) > 0)
return NULL; /* can't change hints on filled square (!) */
/*
* If you ask to fill a square with what it already contains,
* or blank it when it's already empty, that has no effect...
*/
if ((!ui->hpencil || n == 0) &&
GRID(state, nums, ui->hx, ui->hy) == n) {
bool anypencil = false;
int i;
for (i = 0; i < state->order; i++)
anypencil = anypencil || HINT(state, ui->hx, ui->hy, i);
if (!anypencil) {
/* ... expect to remove the cursor in mouse mode. */
if (!ui->hcursor) {
ui->hshow = false;
return MOVE_UI_UPDATE;
}
return NULL;
}
}
sprintf(buf, "%c%d,%d,%d",
(char)(ui->hpencil && n > 0 ? 'P' : 'R'), ui->hx, ui->hy, n);
/*
* Hide the highlight after a keypress, if it was mouse-
* generated. Also, don't hide it if this move has changed
* pencil marks and the user preference says not to hide the
* highlight in that situation.
*/
if (!ui->hcursor && !(ui->hpencil && ui->pencil_keep_highlight))
ui->hshow = false;
return dupstr(buf);
}
if (button == 'H' || button == 'h')
return dupstr("H");
if (button == 'M' || button == 'm')
return dupstr("M");
return NULL;
}
static game_state *execute_move(const game_state *state, const char *move)
{
game_state *ret = NULL;
int x, y, n, i;
debug(("execute_move: %s", move));
if ((move[0] == 'P' || move[0] == 'R') &&
sscanf(move+1, "%d,%d,%d", &x, &y, &n) == 3 &&
x >= 0 && x < state->order && y >= 0 && y < state->order &&
n >= 0 && n <= state->order) {
ret = dup_game(state);
if (move[0] == 'P' && n > 0)
HINT(ret, x, y, n-1) = !HINT(ret, x, y, n-1);
else {
GRID(ret, nums, x, y) = n;
for (i = 0; i < state->order; i++)
HINT(ret, x, y, i) = 0;
/* real change to grid; check for completion */
if (!ret->completed && check_complete(ret->nums, ret, true) > 0)
ret->completed = true;
}
return ret;
} else if (move[0] == 'S') {
const char *p;
ret = dup_game(state);
ret->cheated = true;
p = move+1;
for (i = 0; i < state->order*state->order; i++) {
n = c2n((int)*p, state->order);
if (!*p || n <= 0 || n > state->order)
goto badmove;
ret->nums[i] = n;
p++;
}
if (*p) goto badmove;
if (!ret->completed && check_complete(ret->nums, ret, true) > 0)
ret->completed = true;
return ret;
} else if (move[0] == 'M') {
ret = dup_game(state);
for (x = 0; x < state->order; x++) {
for (y = 0; y < state->order; y++) {
for (n = 0; n < state->order; n++) {
HINT(ret, x, y, n) = 1;
}
}
}
return ret;
} else if (move[0] == 'H') {
ret = solver_hint(state, NULL, DIFF_EASY, DIFF_EASY);
check_complete(ret->nums, ret, true);
return ret;
} else if (move[0] == 'F' && sscanf(move+1, "%d,%d,%d", &x, &y, &n) == 3 &&
x >= 0 && x < state->order && y >= 0 && y < state->order &&
(n & ~F_SPENT_MASK) == 0) {
ret = dup_game(state);
GRID(ret, flags, x, y) ^= n;
return ret;
}
badmove:
if (ret) free_game(ret);
return NULL;
}
/* ----------------------------------------------------------------------
* Drawing/printing routines.
*/
#define DRAW_SIZE (TILE_SIZE*ds->order + GAP_SIZE*(ds->order-1) + BORDER*2)
static void game_compute_size(const game_params *params, int tilesize,
const game_ui *ui, int *x, int *y)
{
/* Ick: fake up `ds->tilesize' for macro expansion purposes */
struct { int tilesize, order; } ads, *ds = &ads;
ads.tilesize = tilesize;
ads.order = params->order;
*x = *y = DRAW_SIZE;
}
static void game_set_size(drawing *dr, game_drawstate *ds,
const game_params *params, int tilesize)
{
ds->tilesize = tilesize;
}
static float *game_colours(frontend *fe, int *ncolours)
{
float *ret = snewn(3 * NCOLOURS, float);
int i;
game_mkhighlight(fe, ret, COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT);
for (i = 0; i < 3; i++) {
ret[COL_TEXT * 3 + i] = 0.0F;
ret[COL_GRID * 3 + i] = 0.5F;
}
/* Lots of these were taken from solo.c. */
ret[COL_GUESS * 3 + 0] = 0.0F;
ret[COL_GUESS * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
ret[COL_GUESS * 3 + 2] = 0.0F;
ret[COL_ERROR * 3 + 0] = 1.0F;
ret[COL_ERROR * 3 + 1] = 0.0F;
ret[COL_ERROR * 3 + 2] = 0.0F;
ret[COL_PENCIL * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
ret[COL_PENCIL * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
ret[COL_PENCIL * 3 + 2] = ret[COL_BACKGROUND * 3 + 2];
*ncolours = NCOLOURS;
return ret;
}
static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
{
struct game_drawstate *ds = snew(struct game_drawstate);
int o2 = state->order*state->order, o3 = o2*state->order;
ds->tilesize = 0;
ds->order = state->order;
ds->mode = state->mode;
ds->nums = snewn(o2, digit);
ds->hints = snewn(o3, unsigned char);
ds->flags = snewn(o2, unsigned int);
memset(ds->nums, 0, o2*sizeof(digit));
memset(ds->hints, 0, o3);
memset(ds->flags, 0, o2*sizeof(unsigned int));
ds->hx = ds->hy = 0;
ds->started = false;
ds->hshow = false;
ds->hpencil = false;
ds->hflash = false;
return ds;
}
static void game_free_drawstate(drawing *dr, game_drawstate *ds)
{
sfree(ds->nums);
sfree(ds->hints);
sfree(ds->flags);
sfree(ds);
}
static void draw_gt(drawing *dr, int ox, int oy,
int dx1, int dy1, int dx2, int dy2, int col)
{
int coords[12];
int xdx = (dx1+dx2 ? 0 : 1), xdy = (dx1+dx2 ? 1 : 0);
coords[0] = ox + xdx;
coords[1] = oy + xdy;
coords[2] = ox + xdx + dx1;
coords[3] = oy + xdy + dy1;
coords[4] = ox + xdx + dx1 + dx2;
coords[5] = oy + xdy + dy1 + dy2;
coords[6] = ox - xdx + dx1 + dx2;
coords[7] = oy - xdy + dy1 + dy2;
coords[8] = ox - xdx + dx1;
coords[9] = oy - xdy + dy1;
coords[10] = ox - xdx;
coords[11] = oy - xdy;
draw_polygon(dr, coords, 6, col, col);
}
#define COLOUR(direction) (f & (F_ERROR_##direction) ? COL_ERROR : \
f & (F_SPENT_##direction) ? COL_SPENT : fg)
static void draw_gts(drawing *dr, game_drawstate *ds, int ox, int oy,
unsigned int f, int bg, int fg)
{
int g = GAP_SIZE, g2 = (g+1)/2, g4 = (g+1)/4;
/* Draw all the greater-than signs emanating from this tile. */
if (f & F_ADJ_UP) {
if (bg >= 0) draw_rect(dr, ox, oy - g, TILE_SIZE, g, bg);
draw_gt(dr, ox+g2, oy-g4, g2, -g2, g2, g2, COLOUR(UP));
draw_update(dr, ox, oy-g, TILE_SIZE, g);
}
if (f & F_ADJ_RIGHT) {
if (bg >= 0) draw_rect(dr, ox + TILE_SIZE, oy, g, TILE_SIZE, bg);
draw_gt(dr, ox+TILE_SIZE+g4, oy+g2, g2, g2, -g2, g2, COLOUR(RIGHT));
draw_update(dr, ox+TILE_SIZE, oy, g, TILE_SIZE);
}
if (f & F_ADJ_DOWN) {
if (bg >= 0) draw_rect(dr, ox, oy + TILE_SIZE, TILE_SIZE, g, bg);
draw_gt(dr, ox+g2, oy+TILE_SIZE+g4, g2, g2, g2, -g2, COLOUR(DOWN));
draw_update(dr, ox, oy+TILE_SIZE, TILE_SIZE, g);
}
if (f & F_ADJ_LEFT) {
if (bg >= 0) draw_rect(dr, ox - g, oy, g, TILE_SIZE, bg);
draw_gt(dr, ox-g4, oy+g2, -g2, g2, g2, g2, COLOUR(LEFT));
draw_update(dr, ox-g, oy, g, TILE_SIZE);
}
}
static void draw_adjs(drawing *dr, game_drawstate *ds, int ox, int oy,
unsigned int f, int bg, int fg)
{
int g = GAP_SIZE, g38 = 3*(g+1)/8, g4 = (g+1)/4;
/* Draw all the adjacency bars relevant to this tile; we only have
* to worry about F_ADJ_RIGHT and F_ADJ_DOWN.
*
* If we _only_ have the error flag set (i.e. it's not supposed to be
* adjacent, but adjacent numbers were entered) draw an outline red bar.
*/
if (f & (F_ADJ_RIGHT|F_ERROR_RIGHT)) {
if (f & F_ADJ_RIGHT) {
draw_rect(dr, ox+TILE_SIZE+g38, oy, g4, TILE_SIZE, COLOUR(RIGHT));
} else {
draw_rect_outline(dr, ox+TILE_SIZE+g38, oy, g4, TILE_SIZE, COL_ERROR);
}
} else if (bg >= 0) {
draw_rect(dr, ox+TILE_SIZE+g38, oy, g4, TILE_SIZE, bg);
}
draw_update(dr, ox+TILE_SIZE, oy, g, TILE_SIZE);
if (f & (F_ADJ_DOWN|F_ERROR_DOWN)) {
if (f & F_ADJ_DOWN) {
draw_rect(dr, ox, oy+TILE_SIZE+g38, TILE_SIZE, g4, COLOUR(DOWN));
} else {
draw_rect_outline(dr, ox, oy+TILE_SIZE+g38, TILE_SIZE, g4, COL_ERROR);
}
} else if (bg >= 0) {
draw_rect(dr, ox, oy+TILE_SIZE+g38, TILE_SIZE, g4, bg);
}
draw_update(dr, ox, oy+TILE_SIZE, TILE_SIZE, g);
}
static void draw_furniture(drawing *dr, game_drawstate *ds,
const game_state *state, const game_ui *ui,
int x, int y, bool hflash)
{
int ox = COORD(x), oy = COORD(y), bg;
bool hon;
unsigned int f = GRID(state, flags, x, y);
bg = hflash ? COL_HIGHLIGHT : COL_BACKGROUND;
hon = (ui->hshow && x == ui->hx && y == ui->hy);
/* Clear square. */
draw_rect(dr, ox, oy, TILE_SIZE, TILE_SIZE,
(hon && !ui->hpencil) ? COL_HIGHLIGHT : bg);
/* Draw the highlight (pencil or full), if we're the highlight */
if (hon && ui->hpencil) {
int coords[6];
coords[0] = ox;
coords[1] = oy;
coords[2] = ox + TILE_SIZE/2;
coords[3] = oy;
coords[4] = ox;
coords[5] = oy + TILE_SIZE/2;
draw_polygon(dr, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
}
/* Draw the square outline (which is the cursor, if we're the cursor). */
draw_rect_outline(dr, ox, oy, TILE_SIZE, TILE_SIZE, COL_GRID);
draw_update(dr, ox, oy, TILE_SIZE, TILE_SIZE);
/* Draw the adjacent clue signs. */
if (ds->mode == MODE_ADJACENT)
draw_adjs(dr, ds, ox, oy, f, COL_BACKGROUND, COL_GRID);
else
draw_gts(dr, ds, ox, oy, f, COL_BACKGROUND, COL_TEXT);
}
static void draw_num(drawing *dr, game_drawstate *ds, int x, int y)
{
int ox = COORD(x), oy = COORD(y);
unsigned int f = GRID(ds,flags,x,y);
char str[2];
/* (can assume square has just been cleared) */
/* Draw number, choosing appropriate colour */
str[0] = n2c(GRID(ds, nums, x, y), ds->order);
str[1] = '\0';
draw_text(dr, ox + TILE_SIZE/2, oy + TILE_SIZE/2,
FONT_VARIABLE, 3*TILE_SIZE/4, ALIGN_VCENTRE | ALIGN_HCENTRE,
(f & F_IMMUTABLE) ? COL_TEXT : (f & F_ERROR) ? COL_ERROR : COL_GUESS, str);
}
static void draw_hints(drawing *dr, game_drawstate *ds, int x, int y)
{
int ox = COORD(x), oy = COORD(y);
int nhints, i, j, hw, hh, hmax, fontsz;
char str[2];
/* (can assume square has just been cleared) */
/* Draw hints; steal ingenious algorithm (basically)
* from solo.c:draw_number() */
for (i = nhints = 0; i < ds->order; i++) {
if (HINT(ds, x, y, i)) nhints++;
}
for (hw = 1; hw * hw < nhints; hw++);
if (hw < 3) hw = 3;
hh = (nhints + hw - 1) / hw;
if (hh < 2) hh = 2;
hmax = max(hw, hh);
fontsz = TILE_SIZE/(hmax*(11-hmax)/8);
for (i = j = 0; i < ds->order; i++) {
if (HINT(ds,x,y,i)) {
int hx = j % hw, hy = j / hw;
str[0] = n2c(i+1, ds->order);
str[1] = '\0';
draw_text(dr,
ox + (4*hx+3) * TILE_SIZE / (4*hw+2),
oy + (4*hy+3) * TILE_SIZE / (4*hh+2),
FONT_VARIABLE, fontsz,
ALIGN_VCENTRE | ALIGN_HCENTRE, COL_PENCIL, str);
j++;
}
}
}
static void game_redraw(drawing *dr, game_drawstate *ds,
const game_state *oldstate, const game_state *state,
int dir, const game_ui *ui,
float animtime, float flashtime)
{
int x, y, i;
bool hchanged = false, stale, hflash = false;
debug(("highlight old (%d,%d), new (%d,%d)", ds->hx, ds->hy, ui->hx, ui->hy));
if (flashtime > 0 &&
(flashtime <= FLASH_TIME/3 || flashtime >= FLASH_TIME*2/3))
hflash = true;
if (!ds->started) {
draw_rect(dr, 0, 0, DRAW_SIZE, DRAW_SIZE, COL_BACKGROUND);
draw_update(dr, 0, 0, DRAW_SIZE, DRAW_SIZE);
}
if (ds->hx != ui->hx || ds->hy != ui->hy ||
ds->hshow != ui->hshow || ds->hpencil != ui->hpencil)
hchanged = true;
for (x = 0; x < ds->order; x++) {
for (y = 0; y < ds->order; y++) {
if (!ds->started)
stale = true;
else if (hflash != ds->hflash)
stale = true;
else
stale = false;
if (hchanged) {
if ((x == ui->hx && y == ui->hy) ||
(x == ds->hx && y == ds->hy))
stale = true;
}
if (GRID(state, nums, x, y) != GRID(ds, nums, x, y)) {
GRID(ds, nums, x, y) = GRID(state, nums, x, y);
stale = true;
}
if (GRID(state, flags, x, y) != GRID(ds, flags, x, y)) {
GRID(ds, flags, x, y) = GRID(state, flags, x, y);
stale = true;
}
if (GRID(ds, nums, x, y) == 0) {
/* We're not a number square (therefore we might
* display hints); do we need to update? */
for (i = 0; i < ds->order; i++) {
if (HINT(state, x, y, i) != HINT(ds, x, y, i)) {
HINT(ds, x, y, i) = HINT(state, x, y, i);
stale = true;
}
}
}
if (stale) {
draw_furniture(dr, ds, state, ui, x, y, hflash);
if (GRID(ds, nums, x, y) > 0)
draw_num(dr, ds, x, y);
else
draw_hints(dr, ds, x, y);
}
}
}
ds->hx = ui->hx; ds->hy = ui->hy;
ds->hshow = ui->hshow;
ds->hpencil = ui->hpencil;
ds->started = true;
ds->hflash = hflash;
}
static float game_anim_length(const game_state *oldstate,
const game_state *newstate, int dir, game_ui *ui)
{
return 0.0F;
}
static float game_flash_length(const game_state *oldstate,
const game_state *newstate, int dir, game_ui *ui)
{
if (!oldstate->completed && newstate->completed &&
!oldstate->cheated && !newstate->cheated)
return FLASH_TIME;
return 0.0F;
}
static void game_get_cursor_location(const game_ui *ui,
const game_drawstate *ds,
const game_state *state,
const game_params *params,
int *x, int *y, int *w, int *h)
{
if(ui->hshow) {
*x = COORD(ui->hx);
*y = COORD(ui->hy);
*w = *h = TILE_SIZE;
}
}
static int game_status(const game_state *state)
{
return state->completed ? +1 : 0;
}
static void game_print_size(const game_params *params, const game_ui *ui,
float *x, float *y)
{
int pw, ph;
/* 10mm squares by default, roughly the same as Grauniad. */
game_compute_size(params, 1000, ui, &pw, &ph);
*x = pw / 100.0F;
*y = ph / 100.0F;
}
static void game_print(drawing *dr, const game_state *state, const game_ui *ui,
int tilesize)
{
int ink = print_mono_colour(dr, 0);
int x, y, o = state->order, ox, oy, n;
char str[2];
/* Ick: fake up `ds->tilesize' for macro expansion purposes */
game_drawstate ads, *ds = &ads;
game_set_size(dr, ds, NULL, tilesize);
print_line_width(dr, 2 * TILE_SIZE / 40);
/* Squares, numbers, gt signs */
for (y = 0; y < o; y++) {
for (x = 0; x < o; x++) {
ox = COORD(x); oy = COORD(y);
n = GRID(state, nums, x, y);
draw_rect_outline(dr, ox, oy, TILE_SIZE, TILE_SIZE, ink);
str[0] = n ? n2c(n, state->order) : ' ';
str[1] = '\0';
draw_text(dr, ox + TILE_SIZE/2, oy + TILE_SIZE/2,
FONT_VARIABLE, TILE_SIZE/2, ALIGN_VCENTRE | ALIGN_HCENTRE,
ink, str);
if (state->mode == MODE_ADJACENT)
draw_adjs(dr, ds, ox, oy, GRID(state, flags, x, y), -1, ink);
else
draw_gts(dr, ds, ox, oy, GRID(state, flags, x, y), -1, ink);
}
}
}
/* ----------------------------------------------------------------------
* Housekeeping.
*/
#ifdef COMBINED
#define thegame unequal
#endif
const struct game thegame = {
"Unequal","L:A_N:application_PC:T_ID:com.kbarni.unequal", " Fill in the grid with numbers from 1 to the grid size, so that every number \
appears exactly once in each row and column, and so that all the < signs represent true inequalities (i.e. the number at the pointed end \
is smaller than the number at the open end).\nTo place a number, click in a square to select it, then type the number on the keyboard. To \
erase a number, click to select a square and then press Backspace.\nRight-click in a square and then type a number to add or remove the \
number as a pencil mark, indicating numbers that you think might go in that square.",
true,default_params,
game_fetch_preset, NULL,
decode_params,
encode_params,
free_params,
dup_params,
true, game_configure, custom_params,
validate_params,
new_game_desc,
validate_desc,
new_game,
dup_game,
free_game,
true, solve_game,
true, game_can_format_as_text_now, game_text_format,
get_prefs, set_prefs,
new_ui,
free_ui,
NULL, /* encode_ui */
NULL, /* decode_ui */
game_request_keys,
game_changed_state,
current_key_label,
interpret_move,
execute_move,
PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
game_colours,
game_new_drawstate,
game_free_drawstate,
game_redraw,
game_anim_length,
game_flash_length,
game_get_cursor_location,
game_status,
true, false, game_print_size, game_print,
false, /* wants_statusbar */
false, NULL, /* timing_state */
REQUIRE_RBUTTON | REQUIRE_NUMPAD, /* flags */
};
/* ----------------------------------------------------------------------
* Standalone solver.
*/
#ifdef STANDALONE_SOLVER
#include <time.h>
#include <stdarg.h>
static const char *quis = NULL;
#if 0 /* currently unused */
static void debug_printf(const char *fmt, ...)
{
char buf[4096];
va_list ap;
va_start(ap, fmt);
vsprintf(buf, fmt, ap);
puts(buf);
va_end(ap);
}
static void game_printf(game_state *state)
{
char *dbg = game_text_format(state);
printf("%s", dbg);
sfree(dbg);
}
static void game_printf_wide(game_state *state)
{
int x, y, i, n;
for (y = 0; y < state->order; y++) {
for (x = 0; x < state->order; x++) {
n = GRID(state, nums, x, y);
for (i = 0; i < state->order; i++) {
if (n > 0)
printf("%c", n2c(n, state->order));
else if (HINT(state, x, y, i))
printf("%c", n2c(i+1, state->order));
else
printf(".");
}
printf(" ");
}
printf("\n");
}
printf("\n");
}
#endif
static void pdiff(int diff)
{
if (diff == DIFF_IMPOSSIBLE)
printf("Game is impossible.\n");
else if (diff == DIFF_UNFINISHED)
printf("Game has incomplete.\n");
else if (diff == DIFF_AMBIGUOUS)
printf("Game has multiple solutions.\n");
else
printf("Game has difficulty %s.\n", unequal_diffnames[diff]);
}
static int solve(game_params *p, char *desc, int debug)
{
game_state *state = new_game(NULL, p, desc);
struct solver_ctx *ctx = new_ctx(state);
struct latin_solver solver;
int diff;
solver_show_working = debug;
game_debug(state);
if (latin_solver_alloc(&solver, state->nums, state->order))
diff = latin_solver_main(&solver, DIFF_RECURSIVE,
DIFF_LATIN, DIFF_SET, DIFF_EXTREME,
DIFF_EXTREME, DIFF_RECURSIVE,
unequal_solvers, unequal_valid, ctx,
clone_ctx, free_ctx);
else
diff = DIFF_IMPOSSIBLE;
free_ctx(ctx);
latin_solver_free(&solver);
if (debug) pdiff(diff);
game_debug(state);
free_game(state);
return diff;
}
static void check(game_params *p)
{
const char *msg = validate_params(p, true);
if (msg) {
fprintf(stderr, "%s: %s", quis, msg);
exit(1);
}
}
static int gen(game_params *p, random_state *rs, int debug)
{
char *desc, *aux;
int diff;
check(p);
solver_show_working = debug;
desc = new_game_desc(p, rs, &aux, false);
diff = solve(p, desc, debug);
sfree(aux);
sfree(desc);
return diff;
}
static void soak(game_params *p, random_state *rs)
{
time_t tt_start, tt_now, tt_last;
char *aux, *desc;
game_state *st;
int n = 0, neasy = 0, realdiff = p->diff;
check(p);
solver_show_working = 0;
maxtries = 1;
tt_start = tt_now = time(NULL);
printf("Soak-generating an %s %dx%d grid, difficulty %s.\n",
p->mode == MODE_ADJACENT ? "adjacent" : "unequal",
p->order, p->order, unequal_diffnames[p->diff]);
while (1) {
p->diff = realdiff;
desc = new_game_desc(p, rs, &aux, false);
st = new_game(NULL, p, desc);
solver_state(st, DIFF_RECURSIVE);
free_game(st);
sfree(aux);
sfree(desc);
n++;
if (realdiff != p->diff) neasy++;
tt_last = time(NULL);
if (tt_last > tt_now) {
tt_now = tt_last;
printf("%d total, %3.1f/s; %d/%2.1f%% easy, %3.1f/s good.\n",
n, (double)n / ((double)tt_now - tt_start),
neasy, (double)neasy*100.0/(double)n,
(double)(n - neasy) / ((double)tt_now - tt_start));
}
}
}
static void usage_exit(const char *msg)
{
if (msg)
fprintf(stderr, "%s: %s\n", quis, msg);
fprintf(stderr, "Usage: %s [--seed SEED] --soak <params> | [game_id [game_id ...]]\n", quis);
exit(1);
}
int main(int argc, const char *argv[])
{
random_state *rs;
time_t seed = time(NULL);
int do_soak = 0, diff;
game_params *p;
maxtries = 50;
quis = argv[0];
while (--argc > 0) {
const char *p = *++argv;
if (!strcmp(p, "--soak"))
do_soak = 1;
else if (!strcmp(p, "--seed")) {
if (argc == 0)
usage_exit("--seed needs an argument");
seed = (time_t)atoi(*++argv);
argc--;
} else if (*p == '-')
usage_exit("unrecognised option");
else
break;
}
rs = random_new((void*)&seed, sizeof(time_t));
if (do_soak == 1) {
if (argc != 1) usage_exit("only one argument for --soak");
p = default_params();
decode_params(p, *argv);
soak(p, rs);
} else if (argc > 0) {
int i;
for (i = 0; i < argc; i++) {
const char *id = *argv++;
char *desc = strchr(id, ':');
const char *err;
p = default_params();
if (desc) {
*desc++ = '\0';
decode_params(p, id);
err = validate_desc(p, desc);
if (err) {
fprintf(stderr, "%s: %s\n", quis, err);
exit(1);
}
solve(p, desc, 1);
} else {
decode_params(p, id);
diff = gen(p, rs, 1);
}
}
} else {
while(1) {
p = default_params();
p->order = random_upto(rs, 7) + 3;
p->diff = random_upto(rs, 4);
diff = gen(p, rs, 0);
pdiff(diff);
}
}
return 0;
}
#endif
/* vim: set shiftwidth=4 tabstop=8: */
| 412 | 0.948184 | 1 | 0.948184 | game-dev | MEDIA | 0.436062 | game-dev | 0.89438 | 1 | 0.89438 |
Progether/JAdventure | 13,719 | src/main/java/com/jadventure/game/prompts/CommandCollection.java | package com.jadventure.game.prompts;
import com.jadventure.game.DeathException;
import com.jadventure.game.GameBeans;
import com.jadventure.game.QueueProvider;
import com.jadventure.game.conversation.ConversationManager;
import com.jadventure.game.entities.NPC;
import com.jadventure.game.entities.Player;
import com.jadventure.game.monsters.Monster;
import com.jadventure.game.monsters.MonsterFactory;
import com.jadventure.game.navigation.Coordinate;
import com.jadventure.game.navigation.Direction;
import com.jadventure.game.navigation.ILocation;
import com.jadventure.game.navigation.LocationType;
import com.jadventure.game.repository.ItemRepository;
import com.jadventure.game.repository.LocationRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
/**
* CommandCollection contains the declaration of the methods mapped to game commands
*
* The declared command methods are accessed only by reflection.
* To declare a new command, add an appropriate method to this class and Annotate it with
* Command(command, aliases, description)
*/
public enum CommandCollection {
INSTANCE;
private Logger logger = LoggerFactory.getLogger(CommandCollection.class);
public Player player;
private final static Map<String, String> DIRECTION_LINKS = new HashMap<>();
static {
DIRECTION_LINKS.put("n", "north");
DIRECTION_LINKS.put("s", "south");
DIRECTION_LINKS.put("e", "east");
DIRECTION_LINKS.put("w", "west");
DIRECTION_LINKS.put("u", "up");
DIRECTION_LINKS.put("d", "down");
}
public static CommandCollection getInstance() {
return INSTANCE;
}
public void initPlayer(Player player) {
this.player = player;
}
// command methods here
@Command(command="help", aliases="h", description="Prints help", debug=false)
public void command_help() {
Method[] methods = CommandCollection.class.getMethods();
int commandWidth = 0;
int descriptionWidth = 0;
QueueProvider.offer("");
for (Method method : methods) {
if (!method.isAnnotationPresent(Command.class)) {
continue;
}
Command annotation = method.getAnnotation(Command.class);
String command = annotation.command() + "( " + Arrays.toString(annotation.aliases()) + "):";
String description = annotation.description();
if (command.length() > commandWidth) {
commandWidth = command.length();
}
if (description.length() > descriptionWidth) {
descriptionWidth = description.length();
}
}
for (Method method : methods) {
if (!method.isAnnotationPresent(Command.class)) {
continue;
}
Command annotation = method.getAnnotation(Command.class);
StringBuilder command;
command = new StringBuilder(annotation.command());
if (annotation.aliases().length > 0) {
command.append(" (");
for (int i = 0; i < annotation.aliases().length; i++) {
if (i == annotation.aliases().length - 1)
command.append(annotation.aliases()[i]);
else
command.append(annotation.aliases()[i]).append(", ");
}
command.append("):");
}
String message = String.format("%-" +commandWidth + "s %-" + descriptionWidth + "s",
command,
annotation.description());
if (annotation.debug()) {
if ("test".equals(player.getName())) {
QueueProvider.offer(message);
}
} else {
QueueProvider.offer(message);
}
}
}
@Command(command="save", aliases={"s"}, description="Save the game", debug=false)
public void command_save() {
logger.info("Command 'save' is running");
player.save();
}
@Command(command="monster", aliases={"m", "enemy"}, description="Monsters around you", debug=false)
public void command_m() {
List<Monster> monsterList = player.getLocation().getMonsters();
if (monsterList.size() > 0) {
QueueProvider.offer("Monsters around you:");
QueueProvider.offer("----------------------------");
for (Monster monster : monsterList) {
QueueProvider.offer(monster.monsterType);
}
QueueProvider.offer("----------------------------");
} else {
QueueProvider.offer("There are no monsters around you'n");
}
}
@Command(command="go", aliases={"g"}, description="Goto a direction", debug=false)
public void command_g(String arg) throws DeathException {
ILocation location = player.getLocation();
try {
arg = DIRECTION_LINKS.get(arg);
Direction direction = Direction.valueOf(arg.toUpperCase());
Map<Direction, ILocation> exits = location.getExits();
if (exits.containsKey(direction)) {
ILocation newLocation = exits.get(Direction.valueOf(arg.toUpperCase()));
if (!newLocation.getLocationType().equals(LocationType.WALL)) {
player.setLocation(newLocation);
if ("test".equals(player.getName())) {
QueueProvider.offer(player.getLocation().getCoordinate().toString());
}
player.getLocation().print();
Random random = new Random();
if (player.getLocation().getMonsters().size() == 0) {
MonsterFactory monsterFactory = new MonsterFactory();
int upperBound = random.nextInt(player.getLocation().getDangerRating() + 1);
for (int i = 0; i < upperBound; i++) {
Monster monster = monsterFactory.generateMonster(player);
player.getLocation().addMonster(monster);
}
}
if (player.getLocation().getItems().size() == 0) {
int chance = random.nextInt(100);
if (chance < 60) {
addItemToLocation();
}
}
if (random.nextDouble() < 0.5) {
List<Monster> monsters = player.getLocation().getMonsters();
if (monsters.size() > 0) {
int posMonster = random.nextInt(monsters.size());
String monster = monsters.get(posMonster).monsterType;
QueueProvider.offer("A " + monster + " is attacking you!");
player.attack(monster);
}
}
} else {
QueueProvider.offer("You cannot walk through walls.");
}
} else {
QueueProvider.offer("The is no exit that way.");
}
} catch (IllegalArgumentException | NullPointerException ex) {
QueueProvider.offer("That direction doesn't exist");
}
}
@Command(command="inspect", aliases = {"i", "lookat"}, description="Inspect an item", debug=false)
public void command_i(String arg) {
player.inspectItem(arg.trim());
}
@Command(command="equip", aliases= {"e"}, description="Equip an item", debug=false)
public void command_e(String arg) {
player.equipItem(arg.trim());
}
@Command(command="unequip", aliases={"ue"}, description="Unequip an item", debug=false)
public void command_ue(String arg) {
player.dequipItem(arg.trim());
}
@Command(command="view", aliases={"v"}, description="View details for 'stats', 'equipped' or 'backpack'", debug=false)
public void command_v(String arg) {
arg = arg.trim();
switch (arg) {
case "s":
case "stats":
player.getStats();
break;
case "e":
case "equipped":
player.printEquipment();
break;
case "b":
case "backpack":
player.printStorage();
break;
default:
QueueProvider.offer("That is not a valid display");
break;
}
}
@Command(command="pick", aliases={"p", "pickup"}, description="Pick up an item", debug=false)
public void command_p(String arg) {
player.pickUpItem(arg.trim());
}
@Command(command="drop", aliases={"d"}, description="Drop an item", debug=false)
public void command_d(String arg) {
player.dropItem(arg.trim());
}
@Command(command="attack", aliases={"a"}, description="Attacks an entity", debug=false)
public void command_a(String arg) throws DeathException {
player.attack(arg.trim());
}
@Command(command="lookaround", aliases={"la"}, description="Displays the description of the room you are in.", debug=false)
public void command_la() {
player.getLocation().print();
}
// Debug methods here
@Command(command="attack", aliases={""}, description="Adjusts the damage level the player has", debug=true)
public void command_attack(String arg) {
double damage = Double.parseDouble(arg);
player.setDamage(damage);
}
@Command(command="maxhealth", aliases={""}, description="Adjusts the maximum health of the player", debug=true)
public void command_maxhealth(String arg) {
int healthMax = Integer.parseInt(arg);
if (healthMax > 0) {
player.setHealthMax(healthMax);
} else {
QueueProvider.offer("Maximum health must be possitive");
}
}
@Command(command="health", aliases={""}, description="Adjusts the amount of gold the player has", debug=true)
public void command_health(String arg) {
int health = Integer.parseInt(arg);
if (health > 0) {
player.setHealth(health);
} else {
QueueProvider.offer("Health must be possitive");
}
}
@Command(command="armour", aliases={""}, description="Adjusts the amount of armour the player has", debug=true)
public void command_armour(String arg) {
int armour = Integer.parseInt(arg);
player.setArmour(armour);
}
@Command(command="level", aliases={""}, description="Adjusts the level of the player", debug=true)
public void command_level(String arg) {
int level = Integer.parseInt(arg);
player.setLevel(level);
}
@Command(command="gold", aliases={""}, description="Adjusts the amount of gold the player has", debug=true)
public void command_gold(String arg) {
int gold = Integer.parseInt(arg);
player.setGold(gold);
}
@Command(command="teleport", aliases={""}, description="Moves the player to specified coordinates", debug=true)
public void command_teleport(String arg) {
LocationRepository locationRepo = GameBeans.getLocationRepository(player.getName());
ILocation newLocation = locationRepo.getLocation(new Coordinate(arg));
ILocation oldLocation = player.getLocation();
try {
player.setLocation(newLocation);
player.getLocation().print();
} catch (NullPointerException e) {
player.setLocation(oldLocation);
QueueProvider.offer("There is no such location");
}
}
@Command(command="backpack", aliases={""}, description="Opens the backpack debug menu.", debug=true)
public void command_backpack(String arg) {
new BackpackDebugPrompt(player);
}
@Command(command="talk", aliases={"t", "speakto"}, description="Talks to a character.", debug=false)
public void command_talk(String arg) throws DeathException {
ConversationManager cm = new ConversationManager();
List<NPC> npcs = player.getLocation().getNpcs();
NPC npc = null;
for (NPC i : npcs) {
if (i.getName().equalsIgnoreCase(arg)) {
npc = i;
}
}
if (npc != null) {
cm.startConversation(npc, player);
} else {
QueueProvider.offer("Unable to talk to " + arg);
}
}
private void addItemToLocation() {
ItemRepository itemRepo = GameBeans.getItemRepository();
if (player.getHealth() < player.getHealthMax()/3) {
player.getLocation().addItem(itemRepo.getRandomFood(player.getLevel()));
} else {
Random rand = new Random();
int startIndex = rand.nextInt(3);
switch (startIndex) {
case 0:
player.getLocation().addItem(itemRepo.getRandomWeapon(player.getLevel()));
break;
case 1:
player.getLocation().addItem(itemRepo.getRandomFood(player.getLevel()));
break;
case 2:
player.getLocation().addItem(itemRepo.getRandomArmour(player.getLevel()));
break;
case 3:
player.getLocation().addItem(itemRepo.getRandomPotion(player.getLevel()));
break;
}
}
}
}
| 412 | 0.897988 | 1 | 0.897988 | game-dev | MEDIA | 0.919458 | game-dev | 0.98551 | 1 | 0.98551 |
chraft/c-raft | 2,186 | Chraft/Entity/Mobs/Zombie.cs | #region C#raft License
// This file is part of C#raft. Copyright C#raft Team
//
// C#raft 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/>.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Chraft.Entity.Items;
using Chraft.Utilities;
using Chraft.Utilities.Blocks;
using Chraft.Utilities.Coords;
using Chraft.Utilities.Misc;
using Chraft.World;
namespace Chraft.Entity.Mobs
{
public class Zombie : Monster
{
public override string Name
{
get { return "Zombie"; }
}
public override short AttackStrength
{
get
{
// Easy 1
// Normal 5
// Hard 7
return 5; // 2.5 hearts
}
}
public override short MaxHealth
{
get
{
return 20; // 10 hearts
}
}
internal Zombie(Chraft.World.WorldManager world, int entityId, Chraft.Net.MetaData data = null)
: base(world, entityId, MobType.Zombie, data)
{
}
protected override void DoDeath(EntityBase killedBy)
{
sbyte count = (sbyte)Server.Rand.Next(2);
if (count > 0)
{
var item = ItemHelper.GetInstance(BlockData.Items.Feather);
item.Count = count;
Server.DropItem(World, UniversalCoords.FromAbsWorld(Position.X, Position.Y, Position.Z), item);
}
base.DoDeath(killedBy);
}
}
}
| 412 | 0.876183 | 1 | 0.876183 | game-dev | MEDIA | 0.9665 | game-dev | 0.78579 | 1 | 0.78579 |
qcad/qcad | 92,862 | src/scripting/ecmaapi/generated/REcmaXLineEntity.cpp | // ***** AUTOGENERATED CODE, DO NOT EDIT *****
// ***** This class is not copyable.
#include "REcmaXLineEntity.h"
#include "RMetaTypes.h"
#include "../REcmaHelper.h"
// forwards declarations mapped to includes
#include "RDocument.h"
#include "RExporter.h"
// includes for base ecma wrapper classes
#include "REcmaEntity.h"
void REcmaXLineEntity::initEcma(QScriptEngine& engine, QScriptValue* proto
)
{
bool protoCreated = false;
if(proto == NULL){
proto = new QScriptValue(engine.newVariant(qVariantFromValue(
(RXLineEntity*) 0)));
protoCreated = true;
}
// primary base class REntity:
QScriptValue dpt = engine.defaultPrototype(
qMetaTypeId<REntity*>());
if (dpt.isValid()) {
proto->setPrototype(dpt);
}
/*
*/
QScriptValue fun;
// toString:
REcmaHelper::registerFunction(&engine, proto, toString, "toString");
// destroy:
REcmaHelper::registerFunction(&engine, proto, destroy, "destroy");
// conversion for base class REntity
REcmaHelper::registerFunction(&engine, proto, getREntity, "getREntity");
// conversion for base class RObject
REcmaHelper::registerFunction(&engine, proto, getRObject, "getRObject");
// get class name
REcmaHelper::registerFunction(&engine, proto, getClassName, "getClassName");
// conversion to all base classes (multiple inheritance):
REcmaHelper::registerFunction(&engine, proto, getBaseClasses, "getBaseClasses");
// properties:
// methods:
REcmaHelper::registerFunction(&engine, proto, clone, "clone");
REcmaHelper::registerFunction(&engine, proto, cloneToXLineEntity, "cloneToXLineEntity");
REcmaHelper::registerFunction(&engine, proto, setProperty, "setProperty");
REcmaHelper::registerFunction(&engine, proto, getProperty, "getProperty");
REcmaHelper::registerFunction(&engine, proto, exportEntity, "exportEntity");
REcmaHelper::registerFunction(&engine, proto, getData, "getData");
REcmaHelper::registerFunction(&engine, proto, setShape, "setShape");
REcmaHelper::registerFunction(&engine, proto, setBasePoint, "setBasePoint");
REcmaHelper::registerFunction(&engine, proto, getBasePoint, "getBasePoint");
REcmaHelper::registerFunction(&engine, proto, setSecondPoint, "setSecondPoint");
REcmaHelper::registerFunction(&engine, proto, getSecondPoint, "getSecondPoint");
REcmaHelper::registerFunction(&engine, proto, setDirectionVectorPoint, "setDirectionVectorPoint");
REcmaHelper::registerFunction(&engine, proto, getDirectionVector, "getDirectionVector");
REcmaHelper::registerFunction(&engine, proto, getAngle, "getAngle");
REcmaHelper::registerFunction(&engine, proto, hasFixedAngle, "hasFixedAngle");
REcmaHelper::registerFunction(&engine, proto, setFixedAngle, "setFixedAngle");
REcmaHelper::registerFunction(&engine, proto, getDirection1, "getDirection1");
REcmaHelper::registerFunction(&engine, proto, getDirection2, "getDirection2");
REcmaHelper::registerFunction(&engine, proto, reverse, "reverse");
REcmaHelper::registerFunction(&engine, proto, getSideOfPoint, "getSideOfPoint");
REcmaHelper::registerFunction(&engine, proto, getTrimEnd, "getTrimEnd");
REcmaHelper::registerFunction(&engine, proto, trimStartPoint, "trimStartPoint");
REcmaHelper::registerFunction(&engine, proto, trimEndPoint, "trimEndPoint");
REcmaHelper::registerFunction(&engine, proto, getLength, "getLength");
engine.setDefaultPrototype(
qMetaTypeId<RXLineEntity*>(), *proto);
QScriptValue ctor = engine.newFunction(createEcma, *proto, 2);
// static methods:
REcmaHelper::registerFunction(&engine, &ctor, init, "init");
REcmaHelper::registerFunction(&engine, &ctor, getRtti, "getRtti");
REcmaHelper::registerFunction(&engine, &ctor, getStaticPropertyTypeIds, "getStaticPropertyTypeIds");
// static properties:
ctor.setProperty("PropertyCustom",
qScriptValueFromValue(&engine, RXLineEntity::PropertyCustom),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
ctor.setProperty("PropertyHandle",
qScriptValueFromValue(&engine, RXLineEntity::PropertyHandle),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
ctor.setProperty("PropertyProtected",
qScriptValueFromValue(&engine, RXLineEntity::PropertyProtected),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
ctor.setProperty("PropertyWorkingSet",
qScriptValueFromValue(&engine, RXLineEntity::PropertyWorkingSet),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
ctor.setProperty("PropertyType",
qScriptValueFromValue(&engine, RXLineEntity::PropertyType),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
ctor.setProperty("PropertyBlock",
qScriptValueFromValue(&engine, RXLineEntity::PropertyBlock),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
ctor.setProperty("PropertyLayer",
qScriptValueFromValue(&engine, RXLineEntity::PropertyLayer),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
ctor.setProperty("PropertyLinetype",
qScriptValueFromValue(&engine, RXLineEntity::PropertyLinetype),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
ctor.setProperty("PropertyLinetypeScale",
qScriptValueFromValue(&engine, RXLineEntity::PropertyLinetypeScale),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
ctor.setProperty("PropertyLineweight",
qScriptValueFromValue(&engine, RXLineEntity::PropertyLineweight),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
ctor.setProperty("PropertyColor",
qScriptValueFromValue(&engine, RXLineEntity::PropertyColor),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
ctor.setProperty("PropertyDisplayedColor",
qScriptValueFromValue(&engine, RXLineEntity::PropertyDisplayedColor),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
ctor.setProperty("PropertyDrawOrder",
qScriptValueFromValue(&engine, RXLineEntity::PropertyDrawOrder),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
ctor.setProperty("PropertyBasePointX",
qScriptValueFromValue(&engine, RXLineEntity::PropertyBasePointX),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
ctor.setProperty("PropertyBasePointY",
qScriptValueFromValue(&engine, RXLineEntity::PropertyBasePointY),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
ctor.setProperty("PropertyBasePointZ",
qScriptValueFromValue(&engine, RXLineEntity::PropertyBasePointZ),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
ctor.setProperty("PropertySecondPointX",
qScriptValueFromValue(&engine, RXLineEntity::PropertySecondPointX),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
ctor.setProperty("PropertySecondPointY",
qScriptValueFromValue(&engine, RXLineEntity::PropertySecondPointY),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
ctor.setProperty("PropertySecondPointZ",
qScriptValueFromValue(&engine, RXLineEntity::PropertySecondPointZ),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
ctor.setProperty("PropertyDirectionX",
qScriptValueFromValue(&engine, RXLineEntity::PropertyDirectionX),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
ctor.setProperty("PropertyDirectionY",
qScriptValueFromValue(&engine, RXLineEntity::PropertyDirectionY),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
ctor.setProperty("PropertyDirectionZ",
qScriptValueFromValue(&engine, RXLineEntity::PropertyDirectionZ),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
ctor.setProperty("PropertyAngle",
qScriptValueFromValue(&engine, RXLineEntity::PropertyAngle),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
ctor.setProperty("PropertyFixedAngle",
qScriptValueFromValue(&engine, RXLineEntity::PropertyFixedAngle),
QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
// enum values:
// enum conversions:
// init class:
engine.globalObject().setProperty("RXLineEntity",
ctor, QScriptValue::SkipInEnumeration);
if( protoCreated ){
delete proto;
}
}
QScriptValue REcmaXLineEntity::createEcma(QScriptContext* context, QScriptEngine* engine)
{
if (context->thisObject().strictlyEquals(
engine->globalObject())) {
return REcmaHelper::throwError(
QString::fromLatin1("RXLineEntity(): Did you forget to construct with 'new'?"),
context);
}
QScriptValue result;
// generate constructor variants:
if( context->argumentCount() ==
2
&& (
context->argument(
0
).isVariant()
||
context->argument(
0
).isQObject()
||
context->argument(
0
).isNull()
) /* type: RDocument * */
&& (
context->argument(
1
).isVariant()
||
context->argument(
1
).isQObject()
||
context->argument(
1
).isNull()
) /* type: RXLineData */
){
// prepare arguments:
// argument is pointer
RDocument * a0 = NULL;
a0 =
REcmaHelper::scriptValueTo<RDocument >(
context->argument(0)
);
if (a0==NULL &&
!context->argument(0).isNull()) {
return REcmaHelper::throwError("RXLineEntity: Argument 0 is not of type RDocument *RDocument *.", context);
}
// argument isCopyable and has default constructor and isSimpleClass
RXLineData*
ap1 =
qscriptvalue_cast<
RXLineData*
>(
context->argument(
1
)
);
if (ap1 == NULL) {
return REcmaHelper::throwError("RXLineEntity: Argument 1 is not of type RXLineData.",
context);
}
RXLineData
a1 =
*ap1;
// end of arguments
// call C++ constructor:
// non-copyable class:
RXLineEntity
* cppResult =
new
RXLineEntity
(
a0
,
a1
);
// TODO: triggers: Warning: QScriptEngine::newVariant(): changing class of non-QScriptObject not supported:
result = engine->newVariant(context->thisObject(), qVariantFromValue(cppResult));
} else
{
return REcmaHelper::throwError(
QString::fromLatin1("RXLineEntity(): no matching constructor found."),
context);
}
return result;
}
// conversion functions for base classes:
QScriptValue REcmaXLineEntity::getREntity(QScriptContext *context,
QScriptEngine *engine)
{
REntity* cppResult =
qscriptvalue_cast<RXLineEntity*> (context->thisObject());
QScriptValue result = qScriptValueFromValue(engine, cppResult);
return result;
}
QScriptValue REcmaXLineEntity::getRObject(QScriptContext *context,
QScriptEngine *engine)
{
RObject* cppResult =
qscriptvalue_cast<RXLineEntity*> (context->thisObject());
QScriptValue result = qScriptValueFromValue(engine, cppResult);
return result;
}
// returns class name:
QScriptValue REcmaXLineEntity::getClassName(QScriptContext *context, QScriptEngine *engine)
{
return qScriptValueFromValue(engine, QString("RXLineEntity"));
}
// returns all base classes (in case of multiple inheritance):
QScriptValue REcmaXLineEntity::getBaseClasses(QScriptContext *context, QScriptEngine *engine)
{
QStringList list;
list.append("REntity");
list.append("RObject");
return qScriptValueFromSequence(engine, list);
}
// properties:
// public methods:
QScriptValue
REcmaXLineEntity::init
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaXLineEntity::init", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaXLineEntity::init";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'void'
RXLineEntity::
init();
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RXLineEntity.init().",
context);
}
//REcmaHelper::functionEnd("REcmaXLineEntity::init", context, engine);
return result;
}
QScriptValue
REcmaXLineEntity::getRtti
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaXLineEntity::getRtti", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaXLineEntity::getRtti";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'RS::EntityType'
RS::EntityType cppResult =
RXLineEntity::
getRtti();
// return type: RS::EntityType
// standard Type
result = QScriptValue(cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RXLineEntity.getRtti().",
context);
}
//REcmaHelper::functionEnd("REcmaXLineEntity::getRtti", context, engine);
return result;
}
QScriptValue
REcmaXLineEntity::getStaticPropertyTypeIds
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaXLineEntity::getStaticPropertyTypeIds", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaXLineEntity::getStaticPropertyTypeIds";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'QSet < RPropertyTypeId >'
QSet < RPropertyTypeId > cppResult =
RXLineEntity::
getStaticPropertyTypeIds();
// return type: QSet < RPropertyTypeId >
// QSet (convert to QVariantList):
result = REcmaHelper::setToScriptValue(engine, cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RXLineEntity.getStaticPropertyTypeIds().",
context);
}
//REcmaHelper::functionEnd("REcmaXLineEntity::getStaticPropertyTypeIds", context, engine);
return result;
}
QScriptValue
REcmaXLineEntity::clone
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaXLineEntity::clone", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaXLineEntity::clone";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RXLineEntity* self =
getSelf("clone", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'QSharedPointer < RObject >'
QSharedPointer < RObject > cppResult =
self->clone();
// return type: QSharedPointer < RObject >
// Shared pointer to object, cast to best match:
result = REcmaHelper::toScriptValue(engine, cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RXLineEntity.clone().",
context);
}
//REcmaHelper::functionEnd("REcmaXLineEntity::clone", context, engine);
return result;
}
QScriptValue
REcmaXLineEntity::cloneToXLineEntity
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaXLineEntity::cloneToXLineEntity", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaXLineEntity::cloneToXLineEntity";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RXLineEntity* self =
getSelf("cloneToXLineEntity", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'QSharedPointer < RXLineEntity >'
QSharedPointer < RXLineEntity > cppResult =
self->cloneToXLineEntity();
// return type: QSharedPointer < RXLineEntity >
// not standard type nor reference
result = qScriptValueFromValue(engine, cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RXLineEntity.cloneToXLineEntity().",
context);
}
//REcmaHelper::functionEnd("REcmaXLineEntity::cloneToXLineEntity", context, engine);
return result;
}
QScriptValue
REcmaXLineEntity::setProperty
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaXLineEntity::setProperty", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaXLineEntity::setProperty";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RXLineEntity* self =
getSelf("setProperty", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
2 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RPropertyTypeId */
&& (
context->argument(1).isVariant() ||
context->argument(1).isQObject() ||
context->argument(1).isNumber() ||
context->argument(1).isString() ||
context->argument(1).isBool() ||
context->argument(1).isArray() ||
context->argument(1).isNull() ||
context->argument(1).isUndefined()
) /* type: QVariant */
){
// prepare arguments:
// argument isCopyable and has default constructor and isSimpleClass
RPropertyTypeId*
ap0 =
qscriptvalue_cast<
RPropertyTypeId*
>(
context->argument(
0
)
);
if (ap0 == NULL) {
return REcmaHelper::throwError("RXLineEntity: Argument 0 is not of type RPropertyTypeId.",
context);
}
RPropertyTypeId
a0 =
*ap0;
// argument isCopyable or pointer
QVariant
a1 =
qscriptvalue_cast<
QVariant
>(
context->argument(
1
)
);
// end of arguments
// call C++ function:
// return type 'bool'
bool cppResult =
self->setProperty(a0
,
a1);
// return type: bool
// standard Type
result = QScriptValue(cppResult);
} else
if( context->argumentCount() ==
3 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RPropertyTypeId */
&& (
context->argument(1).isVariant() ||
context->argument(1).isQObject() ||
context->argument(1).isNumber() ||
context->argument(1).isString() ||
context->argument(1).isBool() ||
context->argument(1).isArray() ||
context->argument(1).isNull() ||
context->argument(1).isUndefined()
) /* type: QVariant */
&& (
context->argument(2).isVariant() ||
context->argument(2).isQObject() ||
context->argument(2).isNull()
) /* type: RTransaction * */
){
// prepare arguments:
// argument isCopyable and has default constructor and isSimpleClass
RPropertyTypeId*
ap0 =
qscriptvalue_cast<
RPropertyTypeId*
>(
context->argument(
0
)
);
if (ap0 == NULL) {
return REcmaHelper::throwError("RXLineEntity: Argument 0 is not of type RPropertyTypeId.",
context);
}
RPropertyTypeId
a0 =
*ap0;
// argument isCopyable or pointer
QVariant
a1 =
qscriptvalue_cast<
QVariant
>(
context->argument(
1
)
);
// argument is pointer
RTransaction * a2 = NULL;
a2 =
REcmaHelper::scriptValueTo<RTransaction >(
context->argument(2)
);
if (a2==NULL &&
!context->argument(2).isNull()) {
return REcmaHelper::throwError("RXLineEntity: Argument 2 is not of type RTransaction *RTransaction *.", context);
}
// end of arguments
// call C++ function:
// return type 'bool'
bool cppResult =
self->setProperty(a0
,
a1
,
a2);
// return type: bool
// standard Type
result = QScriptValue(cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RXLineEntity.setProperty().",
context);
}
//REcmaHelper::functionEnd("REcmaXLineEntity::setProperty", context, engine);
return result;
}
QScriptValue
REcmaXLineEntity::getProperty
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaXLineEntity::getProperty", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaXLineEntity::getProperty";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RXLineEntity* self =
getSelf("getProperty", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
1 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RPropertyTypeId */
){
// prepare arguments:
// argument isCopyable and has default constructor and isSimpleClass
RPropertyTypeId*
ap0 =
qscriptvalue_cast<
RPropertyTypeId*
>(
context->argument(
0
)
);
if (ap0 == NULL) {
return REcmaHelper::throwError("RXLineEntity: Argument 0 is not of type RPropertyTypeId.",
context);
}
RPropertyTypeId
a0 =
*ap0;
// end of arguments
// call C++ function:
// return type 'QPair < QVariant , RPropertyAttributes >'
QPair < QVariant , RPropertyAttributes > cppResult =
self->getProperty(a0);
// return type: QPair < QVariant , RPropertyAttributes >
// Pair of ...:
//result = REcmaHelper::pairToScriptValue(engine, cppResult);
QVariantList vl;
QVariant v;
// first type of pair is variant:
if (QString(cppResult.first.typeName())=="RLineweight::Lineweight") {
v.setValue((int)cppResult.first.value<RLineweight::Lineweight>());
}
else {
v.setValue(cppResult.first);
}
vl.append(v);
v.setValue(cppResult.second);
vl.append(v);
result = qScriptValueFromValue(engine, vl);
} else
if( context->argumentCount() ==
2 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RPropertyTypeId */
&& (
context->argument(1).isBool()
) /* type: bool */
){
// prepare arguments:
// argument isCopyable and has default constructor and isSimpleClass
RPropertyTypeId*
ap0 =
qscriptvalue_cast<
RPropertyTypeId*
>(
context->argument(
0
)
);
if (ap0 == NULL) {
return REcmaHelper::throwError("RXLineEntity: Argument 0 is not of type RPropertyTypeId.",
context);
}
RPropertyTypeId
a0 =
*ap0;
// argument isStandardType
bool
a1 =
(bool)
context->argument( 1 ).
toBool();
// end of arguments
// call C++ function:
// return type 'QPair < QVariant , RPropertyAttributes >'
QPair < QVariant , RPropertyAttributes > cppResult =
self->getProperty(a0
,
a1);
// return type: QPair < QVariant , RPropertyAttributes >
// Pair of ...:
//result = REcmaHelper::pairToScriptValue(engine, cppResult);
QVariantList vl;
QVariant v;
// first type of pair is variant:
if (QString(cppResult.first.typeName())=="RLineweight::Lineweight") {
v.setValue((int)cppResult.first.value<RLineweight::Lineweight>());
}
else {
v.setValue(cppResult.first);
}
vl.append(v);
v.setValue(cppResult.second);
vl.append(v);
result = qScriptValueFromValue(engine, vl);
} else
if( context->argumentCount() ==
3 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RPropertyTypeId */
&& (
context->argument(1).isBool()
) /* type: bool */
&& (
context->argument(2).isBool()
) /* type: bool */
){
// prepare arguments:
// argument isCopyable and has default constructor and isSimpleClass
RPropertyTypeId*
ap0 =
qscriptvalue_cast<
RPropertyTypeId*
>(
context->argument(
0
)
);
if (ap0 == NULL) {
return REcmaHelper::throwError("RXLineEntity: Argument 0 is not of type RPropertyTypeId.",
context);
}
RPropertyTypeId
a0 =
*ap0;
// argument isStandardType
bool
a1 =
(bool)
context->argument( 1 ).
toBool();
// argument isStandardType
bool
a2 =
(bool)
context->argument( 2 ).
toBool();
// end of arguments
// call C++ function:
// return type 'QPair < QVariant , RPropertyAttributes >'
QPair < QVariant , RPropertyAttributes > cppResult =
self->getProperty(a0
,
a1
,
a2);
// return type: QPair < QVariant , RPropertyAttributes >
// Pair of ...:
//result = REcmaHelper::pairToScriptValue(engine, cppResult);
QVariantList vl;
QVariant v;
// first type of pair is variant:
if (QString(cppResult.first.typeName())=="RLineweight::Lineweight") {
v.setValue((int)cppResult.first.value<RLineweight::Lineweight>());
}
else {
v.setValue(cppResult.first);
}
vl.append(v);
v.setValue(cppResult.second);
vl.append(v);
result = qScriptValueFromValue(engine, vl);
} else
if( context->argumentCount() ==
4 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RPropertyTypeId */
&& (
context->argument(1).isBool()
) /* type: bool */
&& (
context->argument(2).isBool()
) /* type: bool */
&& (
context->argument(3).isBool()
) /* type: bool */
){
// prepare arguments:
// argument isCopyable and has default constructor and isSimpleClass
RPropertyTypeId*
ap0 =
qscriptvalue_cast<
RPropertyTypeId*
>(
context->argument(
0
)
);
if (ap0 == NULL) {
return REcmaHelper::throwError("RXLineEntity: Argument 0 is not of type RPropertyTypeId.",
context);
}
RPropertyTypeId
a0 =
*ap0;
// argument isStandardType
bool
a1 =
(bool)
context->argument( 1 ).
toBool();
// argument isStandardType
bool
a2 =
(bool)
context->argument( 2 ).
toBool();
// argument isStandardType
bool
a3 =
(bool)
context->argument( 3 ).
toBool();
// end of arguments
// call C++ function:
// return type 'QPair < QVariant , RPropertyAttributes >'
QPair < QVariant , RPropertyAttributes > cppResult =
self->getProperty(a0
,
a1
,
a2
,
a3);
// return type: QPair < QVariant , RPropertyAttributes >
// Pair of ...:
//result = REcmaHelper::pairToScriptValue(engine, cppResult);
QVariantList vl;
QVariant v;
// first type of pair is variant:
if (QString(cppResult.first.typeName())=="RLineweight::Lineweight") {
v.setValue((int)cppResult.first.value<RLineweight::Lineweight>());
}
else {
v.setValue(cppResult.first);
}
vl.append(v);
v.setValue(cppResult.second);
vl.append(v);
result = qScriptValueFromValue(engine, vl);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RXLineEntity.getProperty().",
context);
}
//REcmaHelper::functionEnd("REcmaXLineEntity::getProperty", context, engine);
return result;
}
QScriptValue
REcmaXLineEntity::exportEntity
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaXLineEntity::exportEntity", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaXLineEntity::exportEntity";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RXLineEntity* self =
getSelf("exportEntity", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
1 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RExporter */
){
// prepare arguments:
// argument is reference
RExporter*
ap0 =
qscriptvalue_cast<
RExporter*
>(
context->argument(
0
)
);
if( ap0 == NULL ){
return REcmaHelper::throwError("RXLineEntity: Argument 0 is not of type RExporter* or QSharedPointer<RExporter>.",
context);
}
RExporter& a0 = *ap0;
// end of arguments
// call C++ function:
// return type 'void'
self->exportEntity(a0);
} else
if( context->argumentCount() ==
2 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RExporter */
&& (
context->argument(1).isBool()
) /* type: bool */
){
// prepare arguments:
// argument is reference
RExporter*
ap0 =
qscriptvalue_cast<
RExporter*
>(
context->argument(
0
)
);
if( ap0 == NULL ){
return REcmaHelper::throwError("RXLineEntity: Argument 0 is not of type RExporter* or QSharedPointer<RExporter>.",
context);
}
RExporter& a0 = *ap0;
// argument isStandardType
bool
a1 =
(bool)
context->argument( 1 ).
toBool();
// end of arguments
// call C++ function:
// return type 'void'
self->exportEntity(a0
,
a1);
} else
if( context->argumentCount() ==
3 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RExporter */
&& (
context->argument(1).isBool()
) /* type: bool */
&& (
context->argument(2).isBool()
) /* type: bool */
){
// prepare arguments:
// argument is reference
RExporter*
ap0 =
qscriptvalue_cast<
RExporter*
>(
context->argument(
0
)
);
if( ap0 == NULL ){
return REcmaHelper::throwError("RXLineEntity: Argument 0 is not of type RExporter* or QSharedPointer<RExporter>.",
context);
}
RExporter& a0 = *ap0;
// argument isStandardType
bool
a1 =
(bool)
context->argument( 1 ).
toBool();
// argument isStandardType
bool
a2 =
(bool)
context->argument( 2 ).
toBool();
// end of arguments
// call C++ function:
// return type 'void'
self->exportEntity(a0
,
a1
,
a2);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RXLineEntity.exportEntity().",
context);
}
//REcmaHelper::functionEnd("REcmaXLineEntity::exportEntity", context, engine);
return result;
}
QScriptValue
REcmaXLineEntity::getData
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaXLineEntity::getData", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaXLineEntity::getData";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RXLineEntity* self =
getSelf("getData", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'RXLineData &'
RXLineData & cppResult =
self->getData();
// return type: RXLineData &
// reference
result = engine->newVariant(
QVariant::fromValue(&cppResult));
} else
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'const RXLineData &'
const RXLineData & cppResult =
self->getData();
// return type: const RXLineData &
// reference
result = engine->newVariant(
QVariant::fromValue(&cppResult));
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RXLineEntity.getData().",
context);
}
//REcmaHelper::functionEnd("REcmaXLineEntity::getData", context, engine);
return result;
}
QScriptValue
REcmaXLineEntity::setShape
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaXLineEntity::setShape", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaXLineEntity::setShape";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RXLineEntity* self =
getSelf("setShape", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
1 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RXLine */
){
// prepare arguments:
// argument isCopyable and has default constructor and isSimpleClass
RXLine*
ap0 =
qscriptvalue_cast<
RXLine*
>(
context->argument(
0
)
);
if (ap0 == NULL) {
return REcmaHelper::throwError("RXLineEntity: Argument 0 is not of type RXLine.",
context);
}
RXLine
a0 =
*ap0;
// end of arguments
// call C++ function:
// return type 'void'
self->setShape(a0);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RXLineEntity.setShape().",
context);
}
//REcmaHelper::functionEnd("REcmaXLineEntity::setShape", context, engine);
return result;
}
QScriptValue
REcmaXLineEntity::setBasePoint
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaXLineEntity::setBasePoint", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaXLineEntity::setBasePoint";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RXLineEntity* self =
getSelf("setBasePoint", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
1 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RVector */
){
// prepare arguments:
// argument isCopyable and has default constructor and isSimpleClass
RVector*
ap0 =
qscriptvalue_cast<
RVector*
>(
context->argument(
0
)
);
if (ap0 == NULL) {
return REcmaHelper::throwError("RXLineEntity: Argument 0 is not of type RVector.",
context);
}
RVector
a0 =
*ap0;
// end of arguments
// call C++ function:
// return type 'void'
self->setBasePoint(a0);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RXLineEntity.setBasePoint().",
context);
}
//REcmaHelper::functionEnd("REcmaXLineEntity::setBasePoint", context, engine);
return result;
}
QScriptValue
REcmaXLineEntity::getBasePoint
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaXLineEntity::getBasePoint", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaXLineEntity::getBasePoint";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RXLineEntity* self =
getSelf("getBasePoint", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'RVector'
RVector cppResult =
self->getBasePoint();
// return type: RVector
// not standard type nor reference
result = qScriptValueFromValue(engine, cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RXLineEntity.getBasePoint().",
context);
}
//REcmaHelper::functionEnd("REcmaXLineEntity::getBasePoint", context, engine);
return result;
}
QScriptValue
REcmaXLineEntity::setSecondPoint
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaXLineEntity::setSecondPoint", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaXLineEntity::setSecondPoint";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RXLineEntity* self =
getSelf("setSecondPoint", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
1 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RVector */
){
// prepare arguments:
// argument isCopyable and has default constructor and isSimpleClass
RVector*
ap0 =
qscriptvalue_cast<
RVector*
>(
context->argument(
0
)
);
if (ap0 == NULL) {
return REcmaHelper::throwError("RXLineEntity: Argument 0 is not of type RVector.",
context);
}
RVector
a0 =
*ap0;
// end of arguments
// call C++ function:
// return type 'void'
self->setSecondPoint(a0);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RXLineEntity.setSecondPoint().",
context);
}
//REcmaHelper::functionEnd("REcmaXLineEntity::setSecondPoint", context, engine);
return result;
}
QScriptValue
REcmaXLineEntity::getSecondPoint
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaXLineEntity::getSecondPoint", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaXLineEntity::getSecondPoint";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RXLineEntity* self =
getSelf("getSecondPoint", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'RVector'
RVector cppResult =
self->getSecondPoint();
// return type: RVector
// not standard type nor reference
result = qScriptValueFromValue(engine, cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RXLineEntity.getSecondPoint().",
context);
}
//REcmaHelper::functionEnd("REcmaXLineEntity::getSecondPoint", context, engine);
return result;
}
QScriptValue
REcmaXLineEntity::setDirectionVectorPoint
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaXLineEntity::setDirectionVectorPoint", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaXLineEntity::setDirectionVectorPoint";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RXLineEntity* self =
getSelf("setDirectionVectorPoint", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
1 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RVector */
){
// prepare arguments:
// argument isCopyable and has default constructor and isSimpleClass
RVector*
ap0 =
qscriptvalue_cast<
RVector*
>(
context->argument(
0
)
);
if (ap0 == NULL) {
return REcmaHelper::throwError("RXLineEntity: Argument 0 is not of type RVector.",
context);
}
RVector
a0 =
*ap0;
// end of arguments
// call C++ function:
// return type 'void'
self->setDirectionVectorPoint(a0);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RXLineEntity.setDirectionVectorPoint().",
context);
}
//REcmaHelper::functionEnd("REcmaXLineEntity::setDirectionVectorPoint", context, engine);
return result;
}
QScriptValue
REcmaXLineEntity::getDirectionVector
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaXLineEntity::getDirectionVector", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaXLineEntity::getDirectionVector";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RXLineEntity* self =
getSelf("getDirectionVector", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'RVector'
RVector cppResult =
self->getDirectionVector();
// return type: RVector
// not standard type nor reference
result = qScriptValueFromValue(engine, cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RXLineEntity.getDirectionVector().",
context);
}
//REcmaHelper::functionEnd("REcmaXLineEntity::getDirectionVector", context, engine);
return result;
}
QScriptValue
REcmaXLineEntity::getAngle
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaXLineEntity::getAngle", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaXLineEntity::getAngle";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RXLineEntity* self =
getSelf("getAngle", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'double'
double cppResult =
self->getAngle();
// return type: double
// standard Type
result = QScriptValue(cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RXLineEntity.getAngle().",
context);
}
//REcmaHelper::functionEnd("REcmaXLineEntity::getAngle", context, engine);
return result;
}
QScriptValue
REcmaXLineEntity::hasFixedAngle
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaXLineEntity::hasFixedAngle", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaXLineEntity::hasFixedAngle";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RXLineEntity* self =
getSelf("hasFixedAngle", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'bool'
bool cppResult =
self->hasFixedAngle();
// return type: bool
// standard Type
result = QScriptValue(cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RXLineEntity.hasFixedAngle().",
context);
}
//REcmaHelper::functionEnd("REcmaXLineEntity::hasFixedAngle", context, engine);
return result;
}
QScriptValue
REcmaXLineEntity::setFixedAngle
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaXLineEntity::setFixedAngle", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaXLineEntity::setFixedAngle";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RXLineEntity* self =
getSelf("setFixedAngle", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
1 && (
context->argument(0).isBool()
) /* type: bool */
){
// prepare arguments:
// argument isStandardType
bool
a0 =
(bool)
context->argument( 0 ).
toBool();
// end of arguments
// call C++ function:
// return type 'void'
self->setFixedAngle(a0);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RXLineEntity.setFixedAngle().",
context);
}
//REcmaHelper::functionEnd("REcmaXLineEntity::setFixedAngle", context, engine);
return result;
}
QScriptValue
REcmaXLineEntity::getDirection1
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaXLineEntity::getDirection1", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaXLineEntity::getDirection1";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RXLineEntity* self =
getSelf("getDirection1", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'double'
double cppResult =
self->getDirection1();
// return type: double
// standard Type
result = QScriptValue(cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RXLineEntity.getDirection1().",
context);
}
//REcmaHelper::functionEnd("REcmaXLineEntity::getDirection1", context, engine);
return result;
}
QScriptValue
REcmaXLineEntity::getDirection2
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaXLineEntity::getDirection2", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaXLineEntity::getDirection2";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RXLineEntity* self =
getSelf("getDirection2", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'double'
double cppResult =
self->getDirection2();
// return type: double
// standard Type
result = QScriptValue(cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RXLineEntity.getDirection2().",
context);
}
//REcmaHelper::functionEnd("REcmaXLineEntity::getDirection2", context, engine);
return result;
}
QScriptValue
REcmaXLineEntity::reverse
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaXLineEntity::reverse", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaXLineEntity::reverse";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RXLineEntity* self =
getSelf("reverse", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'bool'
bool cppResult =
self->reverse();
// return type: bool
// standard Type
result = QScriptValue(cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RXLineEntity.reverse().",
context);
}
//REcmaHelper::functionEnd("REcmaXLineEntity::reverse", context, engine);
return result;
}
QScriptValue
REcmaXLineEntity::getSideOfPoint
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaXLineEntity::getSideOfPoint", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaXLineEntity::getSideOfPoint";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RXLineEntity* self =
getSelf("getSideOfPoint", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
1 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RVector */
){
// prepare arguments:
// argument isCopyable and has default constructor and isSimpleClass
RVector*
ap0 =
qscriptvalue_cast<
RVector*
>(
context->argument(
0
)
);
if (ap0 == NULL) {
return REcmaHelper::throwError("RXLineEntity: Argument 0 is not of type RVector.",
context);
}
RVector
a0 =
*ap0;
// end of arguments
// call C++ function:
// return type 'RS::Side'
RS::Side cppResult =
self->getSideOfPoint(a0);
// return type: RS::Side
// standard Type
result = QScriptValue(cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RXLineEntity.getSideOfPoint().",
context);
}
//REcmaHelper::functionEnd("REcmaXLineEntity::getSideOfPoint", context, engine);
return result;
}
QScriptValue
REcmaXLineEntity::getTrimEnd
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaXLineEntity::getTrimEnd", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaXLineEntity::getTrimEnd";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RXLineEntity* self =
getSelf("getTrimEnd", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
2 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RVector */
&& (
context->argument(1).isVariant() ||
context->argument(1).isQObject() ||
context->argument(1).isNull()
) /* type: RVector */
){
// prepare arguments:
// argument isCopyable and has default constructor and isSimpleClass
RVector*
ap0 =
qscriptvalue_cast<
RVector*
>(
context->argument(
0
)
);
if (ap0 == NULL) {
return REcmaHelper::throwError("RXLineEntity: Argument 0 is not of type RVector.",
context);
}
RVector
a0 =
*ap0;
// argument isCopyable and has default constructor and isSimpleClass
RVector*
ap1 =
qscriptvalue_cast<
RVector*
>(
context->argument(
1
)
);
if (ap1 == NULL) {
return REcmaHelper::throwError("RXLineEntity: Argument 1 is not of type RVector.",
context);
}
RVector
a1 =
*ap1;
// end of arguments
// call C++ function:
// return type 'RS::Ending'
RS::Ending cppResult =
self->getTrimEnd(a0
,
a1);
// return type: RS::Ending
// standard Type
result = QScriptValue(cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RXLineEntity.getTrimEnd().",
context);
}
//REcmaHelper::functionEnd("REcmaXLineEntity::getTrimEnd", context, engine);
return result;
}
QScriptValue
REcmaXLineEntity::trimStartPoint
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaXLineEntity::trimStartPoint", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaXLineEntity::trimStartPoint";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RXLineEntity* self =
getSelf("trimStartPoint", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
1 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RVector */
){
// prepare arguments:
// argument isCopyable and has default constructor and isSimpleClass
RVector*
ap0 =
qscriptvalue_cast<
RVector*
>(
context->argument(
0
)
);
if (ap0 == NULL) {
return REcmaHelper::throwError("RXLineEntity: Argument 0 is not of type RVector.",
context);
}
RVector
a0 =
*ap0;
// end of arguments
// call C++ function:
// return type 'bool'
bool cppResult =
self->trimStartPoint(a0);
// return type: bool
// standard Type
result = QScriptValue(cppResult);
} else
if( context->argumentCount() ==
2 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RVector */
&& (
context->argument(1).isVariant() ||
context->argument(1).isQObject() ||
context->argument(1).isNull()
) /* type: RVector */
){
// prepare arguments:
// argument isCopyable and has default constructor and isSimpleClass
RVector*
ap0 =
qscriptvalue_cast<
RVector*
>(
context->argument(
0
)
);
if (ap0 == NULL) {
return REcmaHelper::throwError("RXLineEntity: Argument 0 is not of type RVector.",
context);
}
RVector
a0 =
*ap0;
// argument isCopyable and has default constructor and isSimpleClass
RVector*
ap1 =
qscriptvalue_cast<
RVector*
>(
context->argument(
1
)
);
if (ap1 == NULL) {
return REcmaHelper::throwError("RXLineEntity: Argument 1 is not of type RVector.",
context);
}
RVector
a1 =
*ap1;
// end of arguments
// call C++ function:
// return type 'bool'
bool cppResult =
self->trimStartPoint(a0
,
a1);
// return type: bool
// standard Type
result = QScriptValue(cppResult);
} else
if( context->argumentCount() ==
3 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RVector */
&& (
context->argument(1).isVariant() ||
context->argument(1).isQObject() ||
context->argument(1).isNull()
) /* type: RVector */
&& (
context->argument(2).isBool()
) /* type: bool */
){
// prepare arguments:
// argument isCopyable and has default constructor and isSimpleClass
RVector*
ap0 =
qscriptvalue_cast<
RVector*
>(
context->argument(
0
)
);
if (ap0 == NULL) {
return REcmaHelper::throwError("RXLineEntity: Argument 0 is not of type RVector.",
context);
}
RVector
a0 =
*ap0;
// argument isCopyable and has default constructor and isSimpleClass
RVector*
ap1 =
qscriptvalue_cast<
RVector*
>(
context->argument(
1
)
);
if (ap1 == NULL) {
return REcmaHelper::throwError("RXLineEntity: Argument 1 is not of type RVector.",
context);
}
RVector
a1 =
*ap1;
// argument isStandardType
bool
a2 =
(bool)
context->argument( 2 ).
toBool();
// end of arguments
// call C++ function:
// return type 'bool'
bool cppResult =
self->trimStartPoint(a0
,
a1
,
a2);
// return type: bool
// standard Type
result = QScriptValue(cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RXLineEntity.trimStartPoint().",
context);
}
//REcmaHelper::functionEnd("REcmaXLineEntity::trimStartPoint", context, engine);
return result;
}
QScriptValue
REcmaXLineEntity::trimEndPoint
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaXLineEntity::trimEndPoint", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaXLineEntity::trimEndPoint";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RXLineEntity* self =
getSelf("trimEndPoint", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
1 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RVector */
){
// prepare arguments:
// argument isCopyable and has default constructor and isSimpleClass
RVector*
ap0 =
qscriptvalue_cast<
RVector*
>(
context->argument(
0
)
);
if (ap0 == NULL) {
return REcmaHelper::throwError("RXLineEntity: Argument 0 is not of type RVector.",
context);
}
RVector
a0 =
*ap0;
// end of arguments
// call C++ function:
// return type 'bool'
bool cppResult =
self->trimEndPoint(a0);
// return type: bool
// standard Type
result = QScriptValue(cppResult);
} else
if( context->argumentCount() ==
2 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RVector */
&& (
context->argument(1).isVariant() ||
context->argument(1).isQObject() ||
context->argument(1).isNull()
) /* type: RVector */
){
// prepare arguments:
// argument isCopyable and has default constructor and isSimpleClass
RVector*
ap0 =
qscriptvalue_cast<
RVector*
>(
context->argument(
0
)
);
if (ap0 == NULL) {
return REcmaHelper::throwError("RXLineEntity: Argument 0 is not of type RVector.",
context);
}
RVector
a0 =
*ap0;
// argument isCopyable and has default constructor and isSimpleClass
RVector*
ap1 =
qscriptvalue_cast<
RVector*
>(
context->argument(
1
)
);
if (ap1 == NULL) {
return REcmaHelper::throwError("RXLineEntity: Argument 1 is not of type RVector.",
context);
}
RVector
a1 =
*ap1;
// end of arguments
// call C++ function:
// return type 'bool'
bool cppResult =
self->trimEndPoint(a0
,
a1);
// return type: bool
// standard Type
result = QScriptValue(cppResult);
} else
if( context->argumentCount() ==
3 && (
context->argument(0).isVariant() ||
context->argument(0).isQObject() ||
context->argument(0).isNull()
) /* type: RVector */
&& (
context->argument(1).isVariant() ||
context->argument(1).isQObject() ||
context->argument(1).isNull()
) /* type: RVector */
&& (
context->argument(2).isBool()
) /* type: bool */
){
// prepare arguments:
// argument isCopyable and has default constructor and isSimpleClass
RVector*
ap0 =
qscriptvalue_cast<
RVector*
>(
context->argument(
0
)
);
if (ap0 == NULL) {
return REcmaHelper::throwError("RXLineEntity: Argument 0 is not of type RVector.",
context);
}
RVector
a0 =
*ap0;
// argument isCopyable and has default constructor and isSimpleClass
RVector*
ap1 =
qscriptvalue_cast<
RVector*
>(
context->argument(
1
)
);
if (ap1 == NULL) {
return REcmaHelper::throwError("RXLineEntity: Argument 1 is not of type RVector.",
context);
}
RVector
a1 =
*ap1;
// argument isStandardType
bool
a2 =
(bool)
context->argument( 2 ).
toBool();
// end of arguments
// call C++ function:
// return type 'bool'
bool cppResult =
self->trimEndPoint(a0
,
a1
,
a2);
// return type: bool
// standard Type
result = QScriptValue(cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RXLineEntity.trimEndPoint().",
context);
}
//REcmaHelper::functionEnd("REcmaXLineEntity::trimEndPoint", context, engine);
return result;
}
QScriptValue
REcmaXLineEntity::getLength
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaXLineEntity::getLength", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaXLineEntity::getLength";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
// public function: can be called from ECMA wrapper of ECMA shell:
RXLineEntity* self =
getSelf("getLength", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'double'
double cppResult =
self->getLength();
// return type: double
// standard Type
result = QScriptValue(cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RXLineEntity.getLength().",
context);
}
//REcmaHelper::functionEnd("REcmaXLineEntity::getLength", context, engine);
return result;
}
QScriptValue REcmaXLineEntity::toString
(QScriptContext *context, QScriptEngine *engine)
{
RXLineEntity* self = getSelf("toString", context);
QString result;
result = QString("RXLineEntity(0x%1)").arg((unsigned long int)self, 0, 16);
return QScriptValue(result);
}
QScriptValue REcmaXLineEntity::destroy(QScriptContext *context, QScriptEngine *engine)
{
RXLineEntity* self = getSelf("RXLineEntity", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
delete self;
context->thisObject().setData(engine->nullValue());
context->thisObject().prototype().setData(engine->nullValue());
context->thisObject().setPrototype(engine->nullValue());
context->thisObject().setScriptClass(NULL);
return engine->undefinedValue();
}
RXLineEntity* REcmaXLineEntity::getSelf(const QString& fName, QScriptContext* context)
{
RXLineEntity* self = NULL;
// self could be a normal object (e.g. from an UI file) or
// an ECMA shell object (made from an ECMA script):
//self = getSelfShell(fName, context);
//if (self==NULL) {
self = REcmaHelper::scriptValueTo<RXLineEntity >(context->thisObject())
;
//}
if (self == NULL){
// avoid recursion (toString is used by the backtrace):
if (fName!="toString") {
REcmaHelper::throwError(QString("RXLineEntity.%1(): "
"This object is not a RXLineEntity").arg(fName),
context);
}
return NULL;
}
return self;
}
RXLineEntity* REcmaXLineEntity::getSelfShell(const QString& fName, QScriptContext* context)
{
RXLineEntity* selfBase = getSelf(fName, context);
RXLineEntity* self = dynamic_cast<RXLineEntity*>(selfBase);
//return REcmaHelper::scriptValueTo<RXLineEntity >(context->thisObject());
if(self == NULL){
REcmaHelper::throwError(QString("RXLineEntity.%1(): "
"This object is not a RXLineEntity").arg(fName),
context);
}
return self;
}
| 412 | 0.928565 | 1 | 0.928565 | game-dev | MEDIA | 0.787263 | game-dev | 0.817705 | 1 | 0.817705 |
pearuhdox/Cartographer-2.0 | 1,131 | Cartographer - Custom Enchantments/data/carto_event/function/event/custom_ench/throwable/throwable_behavior/enchants/ricochet/flip/z.mcfunction | scoreboard players set $side_reflect ca.ench_ricochet_lvl 3
#execute as @s at @s run particle minecraft:end_rod ~ ~ ~ 0.1 0.1 0.1 0 20 normal
execute store result score $swap ca.ench_ricochet_lvl run data get storage carto_event current[-1].parameters.z_motion 1000
scoreboard players operation $swap ca.ench_ricochet_lvl *= $-1 ca.CONSTANT
execute store result storage carto_event current[-1].parameters.z_motion double 0.001 run scoreboard players get $swap ca.ench_ricochet_lvl
scoreboard players operation $swap ca.ench_ricochet_lvl /= $2 ca.CONSTANT
execute store result storage carto_event current[-1].parameters.z_step double 0.0001 run scoreboard players get $swap ca.ench_ricochet_lvl
scoreboard players remove @s ca.ench_ricochet_lvl 1
execute if score $z_mot ca.ench_ricochet_lvl matches 1.. align z positioned ~ ~ ~-1.5 run function carto_event:event/custom_ench/throwable/throwable_behavior/enchants/ricochet/flip/do_move
execute unless score $z_mot ca.ench_ricochet_lvl matches 1.. align z positioned ~ ~ ~0.5 run function carto_event:event/custom_ench/throwable/throwable_behavior/enchants/ricochet/flip/do_move
| 412 | 0.638691 | 1 | 0.638691 | game-dev | MEDIA | 0.938622 | game-dev | 0.696997 | 1 | 0.696997 |
Pan4ur/ThunderHack-Recode | 1,808 | src/main/java/thunder/hack/features/modules/render/WorldTweaks.java | package thunder.hack.features.modules.render;
import meteordevelopment.orbit.EventHandler;
import net.minecraft.network.packet.s2c.play.WorldTimeUpdateS2CPacket;
import thunder.hack.events.impl.PacketEvent;
import thunder.hack.features.modules.Module;
import thunder.hack.setting.Setting;
import thunder.hack.setting.impl.BooleanSettingGroup;
import thunder.hack.setting.impl.ColorSetting;
import java.awt.*;
public class WorldTweaks extends Module {
public WorldTweaks() {
super("WorldTweaks", Category.RENDER);
}
public static final Setting<BooleanSettingGroup> fogModify = new Setting<>("FogModify", new BooleanSettingGroup(true));
public static final Setting<Integer> fogStart = new Setting<>("FogStart", 0, 0, 256).addToGroup(fogModify);
public static final Setting<Integer> fogEnd = new Setting<>("FogEnd", 64, 10, 256).addToGroup(fogModify);
public static final Setting<ColorSetting> fogColor = new Setting<>("FogColor", new ColorSetting(new Color(0xA900FF))).addToGroup(fogModify);
public final Setting<Boolean> ctime = new Setting<>("ChangeTime", false);
public final Setting<Integer> ctimeVal = new Setting<>("Time", 21, 0, 23);
long oldTime;
@Override
public void onEnable() {
oldTime = mc.world.getTime();
}
@Override
public void onDisable() {
mc.world.setTimeOfDay(oldTime);
}
@EventHandler
private void onPacketReceive(PacketEvent.Receive event) {
if (event.getPacket() instanceof WorldTimeUpdateS2CPacket && ctime.getValue()) {
oldTime = ((WorldTimeUpdateS2CPacket) event.getPacket()).getTime();
event.cancel();
}
}
@Override
public void onUpdate() {
if (ctime.getValue()) mc.world.setTimeOfDay(ctimeVal.getValue() * 1000);
}
}
| 412 | 0.781478 | 1 | 0.781478 | game-dev | MEDIA | 0.933137 | game-dev | 0.931789 | 1 | 0.931789 |
Secrets-of-Sosaria/World | 15,071 | Data/System/Source/MultiData.cs | /***************************************************************************
* MultiData.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id$
*
***************************************************************************/
/***************************************************************************
*
* 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.
*
***************************************************************************/
using System;
using System.Collections;
using System.IO;
namespace Server
{
public static class MultiData
{
private static MultiComponentList[] m_Components;
private static FileStream m_Index, m_Stream;
private static BinaryReader m_IndexReader, m_StreamReader;
public static MultiComponentList GetComponents( int multiID )
{
MultiComponentList mcl;
if ( multiID >= 0 && multiID < m_Components.Length )
{
mcl = m_Components[multiID];
if ( mcl == null )
m_Components[multiID] = mcl = Load( multiID );
}
else
{
mcl = MultiComponentList.Empty;
}
return mcl;
}
public static MultiComponentList Load( int multiID )
{
try
{
m_IndexReader.BaseStream.Seek( multiID * 12, SeekOrigin.Begin );
int lookup = m_IndexReader.ReadInt32();
int length = m_IndexReader.ReadInt32();
if ( lookup < 0 || length <= 0 )
return MultiComponentList.Empty;
m_StreamReader.BaseStream.Seek( lookup, SeekOrigin.Begin );
return new MultiComponentList( m_StreamReader, length / ( MultiComponentList.PostHSFormat ? 16 : 12 ) );
}
catch
{
return MultiComponentList.Empty;
}
}
static MultiData()
{
string idxPath = Core.FindDataFile( "multi.idx" );
string mulPath = Core.FindDataFile( "multi.mul" );
if ( File.Exists( idxPath ) && File.Exists( mulPath ) )
{
m_Index = new FileStream( idxPath, FileMode.Open, FileAccess.Read, FileShare.Read );
m_IndexReader = new BinaryReader( m_Index );
m_Stream = new FileStream( mulPath, FileMode.Open, FileAccess.Read, FileShare.Read );
m_StreamReader = new BinaryReader( m_Stream );
m_Components = new MultiComponentList[(int)(m_Index.Length / 12)];
string vdPath = Core.FindDataFile( "verdata.mul" );
if ( File.Exists( vdPath ) )
{
using ( FileStream fs = new FileStream( vdPath, FileMode.Open, FileAccess.Read, FileShare.Read ) )
{
BinaryReader bin = new BinaryReader( fs );
int count = bin.ReadInt32();
for ( int i = 0; i < count; ++i )
{
int file = bin.ReadInt32();
int index = bin.ReadInt32();
int lookup = bin.ReadInt32();
int length = bin.ReadInt32();
int extra = bin.ReadInt32();
if ( file == 14 && index >= 0 && index < m_Components.Length && lookup >= 0 && length > 0 )
{
bin.BaseStream.Seek( lookup, SeekOrigin.Begin );
m_Components[index] = new MultiComponentList( bin, length / 12 );
bin.BaseStream.Seek( 24 + (i * 20), SeekOrigin.Begin );
}
}
bin.Close();
}
}
}
else
{
Console.WriteLine( "Warning: Multi data files not found" );
m_Components = new MultiComponentList[0];
}
}
}
public struct MultiTileEntry
{
public ushort m_ItemID;
public short m_OffsetX, m_OffsetY, m_OffsetZ;
public int m_Flags;
public MultiTileEntry( ushort itemID, short xOffset, short yOffset, short zOffset, int flags )
{
m_ItemID = itemID;
m_OffsetX = xOffset;
m_OffsetY = yOffset;
m_OffsetZ = zOffset;
m_Flags = flags;
}
}
public sealed class MultiComponentList
{
public static bool PostHSFormat {
get { return _PostHSFormat; }
set { _PostHSFormat = value; }
}
private static bool _PostHSFormat = false;
private Point2D m_Min, m_Max, m_Center;
private int m_Width, m_Height;
private StaticTile[][][] m_Tiles;
private MultiTileEntry[] m_List;
public static readonly MultiComponentList Empty = new MultiComponentList();
public Point2D Min{ get{ return m_Min; } }
public Point2D Max{ get{ return m_Max; } }
public Point2D Center{ get{ return m_Center; } }
public int Width{ get{ return m_Width; } }
public int Height{ get{ return m_Height; } }
public StaticTile[][][] Tiles{ get{ return m_Tiles; } }
public MultiTileEntry[] List{ get{ return m_List; } }
public void Add( int itemID, int x, int y, int z )
{
int vx = x + m_Center.m_X;
int vy = y + m_Center.m_Y;
if ( vx >= 0 && vx < m_Width && vy >= 0 && vy < m_Height )
{
StaticTile[] oldTiles = m_Tiles[vx][vy];
for ( int i = oldTiles.Length - 1; i >= 0; --i )
{
ItemData data = TileData.ItemTable[itemID & TileData.MaxItemValue];
if ( oldTiles[i].Z == z && (oldTiles[i].Height > 0 == data.Height > 0 ) )
{
bool newIsRoof = ( data.Flags & TileFlag.Roof) != 0;
bool oldIsRoof = (TileData.ItemTable[oldTiles[i].ID & TileData.MaxItemValue].Flags & TileFlag.Roof ) != 0;
if ( newIsRoof == oldIsRoof )
Remove( oldTiles[i].ID, x, y, z );
}
}
oldTiles = m_Tiles[vx][vy];
StaticTile[] newTiles = new StaticTile[oldTiles.Length + 1];
for ( int i = 0; i < oldTiles.Length; ++i )
newTiles[i] = oldTiles[i];
newTiles[oldTiles.Length] = new StaticTile( (ushort)itemID, (sbyte)z );
m_Tiles[vx][vy] = newTiles;
MultiTileEntry[] oldList = m_List;
MultiTileEntry[] newList = new MultiTileEntry[oldList.Length + 1];
for ( int i = 0; i < oldList.Length; ++i )
newList[i] = oldList[i];
newList[oldList.Length] = new MultiTileEntry( (ushort)itemID, (short)x, (short)y, (short)z, 1 );
m_List = newList;
if ( x < m_Min.m_X )
m_Min.m_X = x;
if ( y < m_Min.m_Y )
m_Min.m_Y = y;
if ( x > m_Max.m_X )
m_Max.m_X = x;
if ( y > m_Max.m_Y )
m_Max.m_Y = y;
}
}
public void RemoveXYZH( int x, int y, int z, int minHeight )
{
int vx = x + m_Center.m_X;
int vy = y + m_Center.m_Y;
if ( vx >= 0 && vx < m_Width && vy >= 0 && vy < m_Height )
{
StaticTile[] oldTiles = m_Tiles[vx][vy];
for ( int i = 0; i < oldTiles.Length; ++i )
{
StaticTile tile = oldTiles[i];
if ( tile.Z == z && tile.Height >= minHeight )
{
StaticTile[] newTiles = new StaticTile[oldTiles.Length - 1];
for ( int j = 0; j < i; ++j )
newTiles[j] = oldTiles[j];
for ( int j = i + 1; j < oldTiles.Length; ++j )
newTiles[j - 1] = oldTiles[j];
m_Tiles[vx][vy] = newTiles;
break;
}
}
MultiTileEntry[] oldList = m_List;
for ( int i = 0; i < oldList.Length; ++i )
{
MultiTileEntry tile = oldList[i];
if ( tile.m_OffsetX == (short)x && tile.m_OffsetY == (short)y && tile.m_OffsetZ == (short)z && TileData.ItemTable[tile.m_ItemID & TileData.MaxItemValue].Height >= minHeight )
{
MultiTileEntry[] newList = new MultiTileEntry[oldList.Length - 1];
for ( int j = 0; j < i; ++j )
newList[j] = oldList[j];
for ( int j = i + 1; j < oldList.Length; ++j )
newList[j - 1] = oldList[j];
m_List = newList;
break;
}
}
}
}
public void Remove( int itemID, int x, int y, int z )
{
int vx = x + m_Center.m_X;
int vy = y + m_Center.m_Y;
if ( vx >= 0 && vx < m_Width && vy >= 0 && vy < m_Height )
{
StaticTile[] oldTiles = m_Tiles[vx][vy];
for ( int i = 0; i < oldTiles.Length; ++i )
{
StaticTile tile = oldTiles[i];
if ( tile.ID == itemID && tile.Z == z )
{
StaticTile[] newTiles = new StaticTile[oldTiles.Length - 1];
for ( int j = 0; j < i; ++j )
newTiles[j] = oldTiles[j];
for ( int j = i + 1; j < oldTiles.Length; ++j )
newTiles[j - 1] = oldTiles[j];
m_Tiles[vx][vy] = newTiles;
break;
}
}
MultiTileEntry[] oldList = m_List;
for ( int i = 0; i < oldList.Length; ++i )
{
MultiTileEntry tile = oldList[i];
if ( tile.m_ItemID == itemID && tile.m_OffsetX == (short)x && tile.m_OffsetY == (short)y && tile.m_OffsetZ == (short)z )
{
MultiTileEntry[] newList = new MultiTileEntry[oldList.Length - 1];
for ( int j = 0; j < i; ++j )
newList[j] = oldList[j];
for ( int j = i + 1; j < oldList.Length; ++j )
newList[j - 1] = oldList[j];
m_List = newList;
break;
}
}
}
}
public void Resize( int newWidth, int newHeight )
{
int oldWidth = m_Width, oldHeight = m_Height;
StaticTile[][][] oldTiles = m_Tiles;
int totalLength = 0;
StaticTile[][][] newTiles = new StaticTile[newWidth][][];
for ( int x = 0; x < newWidth; ++x )
{
newTiles[x] = new StaticTile[newHeight][];
for ( int y = 0; y < newHeight; ++y )
{
if ( x < oldWidth && y < oldHeight )
newTiles[x][y] = oldTiles[x][y];
else
newTiles[x][y] = new StaticTile[0];
totalLength += newTiles[x][y].Length;
}
}
m_Tiles = newTiles;
m_List = new MultiTileEntry[totalLength];
m_Width = newWidth;
m_Height = newHeight;
m_Min = Point2D.Zero;
m_Max = Point2D.Zero;
int index = 0;
for ( int x = 0; x < newWidth; ++x )
{
for ( int y = 0; y < newHeight; ++y )
{
StaticTile[] tiles = newTiles[x][y];
for ( int i = 0; i < tiles.Length; ++i )
{
StaticTile tile = tiles[i];
int vx = x - m_Center.X;
int vy = y - m_Center.Y;
if ( vx < m_Min.m_X )
m_Min.m_X = vx;
if ( vy < m_Min.m_Y )
m_Min.m_Y = vy;
if ( vx > m_Max.m_X )
m_Max.m_X = vx;
if ( vy > m_Max.m_Y )
m_Max.m_Y = vy;
m_List[index++] = new MultiTileEntry( (ushort)tile.ID, (short)vx, (short)vy, (short)tile.Z, 1 );
}
}
}
}
public MultiComponentList( MultiComponentList toCopy )
{
m_Min = toCopy.m_Min;
m_Max = toCopy.m_Max;
m_Center = toCopy.m_Center;
m_Width = toCopy.m_Width;
m_Height = toCopy.m_Height;
m_Tiles = new StaticTile[m_Width][][];
for ( int x = 0; x < m_Width; ++x )
{
m_Tiles[x] = new StaticTile[m_Height][];
for ( int y = 0; y < m_Height; ++y )
{
m_Tiles[x][y] = new StaticTile[toCopy.m_Tiles[x][y].Length];
for ( int i = 0; i < m_Tiles[x][y].Length; ++i )
m_Tiles[x][y][i] = toCopy.m_Tiles[x][y][i];
}
}
m_List = new MultiTileEntry[toCopy.m_List.Length];
for ( int i = 0; i < m_List.Length; ++i )
m_List[i] = toCopy.m_List[i];
}
public void Serialize( GenericWriter writer )
{
writer.Write( (int) 1 ); // version;
writer.Write( m_Min );
writer.Write( m_Max );
writer.Write( m_Center );
writer.Write( (int) m_Width );
writer.Write( (int) m_Height );
writer.Write( (int) m_List.Length );
for ( int i = 0; i < m_List.Length; ++i )
{
MultiTileEntry ent = m_List[i];
writer.Write( (ushort) ent.m_ItemID );
writer.Write( (short) ent.m_OffsetX );
writer.Write( (short) ent.m_OffsetY );
writer.Write( (short) ent.m_OffsetZ );
writer.Write( (int) ent.m_Flags );
}
}
public MultiComponentList( GenericReader reader )
{
int version = reader.ReadInt();
m_Min = reader.ReadPoint2D();
m_Max = reader.ReadPoint2D();
m_Center = reader.ReadPoint2D();
m_Width = reader.ReadInt();
m_Height = reader.ReadInt();
int length = reader.ReadInt();
MultiTileEntry[] allTiles = m_List = new MultiTileEntry[length];
if ( version == 0 ) {
for ( int i = 0; i < length; ++i )
{
int id = reader.ReadShort();
if ( id >= 0x4000 )
id -= 0x4000;
allTiles[i].m_ItemID = (ushort)id;
allTiles[i].m_OffsetX = reader.ReadShort();
allTiles[i].m_OffsetY = reader.ReadShort();
allTiles[i].m_OffsetZ = reader.ReadShort();
allTiles[i].m_Flags = reader.ReadInt();
}
} else {
for ( int i = 0; i < length; ++i )
{
allTiles[i].m_ItemID = reader.ReadUShort();
allTiles[i].m_OffsetX = reader.ReadShort();
allTiles[i].m_OffsetY = reader.ReadShort();
allTiles[i].m_OffsetZ = reader.ReadShort();
allTiles[i].m_Flags = reader.ReadInt();
}
}
TileList[][] tiles = new TileList[m_Width][];
m_Tiles = new StaticTile[m_Width][][];
for ( int x = 0; x < m_Width; ++x )
{
tiles[x] = new TileList[m_Height];
m_Tiles[x] = new StaticTile[m_Height][];
for ( int y = 0; y < m_Height; ++y )
tiles[x][y] = new TileList();
}
for ( int i = 0; i < allTiles.Length; ++i )
{
if ( i == 0 || allTiles[i].m_Flags != 0 )
{
int xOffset = allTiles[i].m_OffsetX + m_Center.m_X;
int yOffset = allTiles[i].m_OffsetY + m_Center.m_Y;
tiles[xOffset][yOffset].Add( (ushort)allTiles[i].m_ItemID, (sbyte)allTiles[i].m_OffsetZ );
}
}
for ( int x = 0; x < m_Width; ++x )
for ( int y = 0; y < m_Height; ++y )
m_Tiles[x][y] = tiles[x][y].ToArray();
}
public MultiComponentList( BinaryReader reader, int count )
{
MultiTileEntry[] allTiles = m_List = new MultiTileEntry[count];
for ( int i = 0; i < count; ++i )
{
allTiles[i].m_ItemID = reader.ReadUInt16();
allTiles[i].m_OffsetX = reader.ReadInt16();
allTiles[i].m_OffsetY = reader.ReadInt16();
allTiles[i].m_OffsetZ = reader.ReadInt16();
allTiles[i].m_Flags = reader.ReadInt32();
if ( _PostHSFormat )
reader.ReadInt32(); // ??
MultiTileEntry e = allTiles[i];
if ( i == 0 || e.m_Flags != 0 )
{
if ( e.m_OffsetX < m_Min.m_X )
m_Min.m_X = e.m_OffsetX;
if ( e.m_OffsetY < m_Min.m_Y )
m_Min.m_Y = e.m_OffsetY;
if ( e.m_OffsetX > m_Max.m_X )
m_Max.m_X = e.m_OffsetX;
if ( e.m_OffsetY > m_Max.m_Y )
m_Max.m_Y = e.m_OffsetY;
}
}
m_Center = new Point2D( -m_Min.m_X, -m_Min.m_Y );
m_Width = (m_Max.m_X - m_Min.m_X) + 1;
m_Height = (m_Max.m_Y - m_Min.m_Y) + 1;
TileList[][] tiles = new TileList[m_Width][];
m_Tiles = new StaticTile[m_Width][][];
for ( int x = 0; x < m_Width; ++x )
{
tiles[x] = new TileList[m_Height];
m_Tiles[x] = new StaticTile[m_Height][];
for ( int y = 0; y < m_Height; ++y )
tiles[x][y] = new TileList();
}
for ( int i = 0; i < allTiles.Length; ++i )
{
if ( i == 0 || allTiles[i].m_Flags != 0 )
{
int xOffset = allTiles[i].m_OffsetX + m_Center.m_X;
int yOffset = allTiles[i].m_OffsetY + m_Center.m_Y;
tiles[xOffset][yOffset].Add( (ushort)allTiles[i].m_ItemID, (sbyte)allTiles[i].m_OffsetZ );
}
}
for ( int x = 0; x < m_Width; ++x )
for ( int y = 0; y < m_Height; ++y )
m_Tiles[x][y] = tiles[x][y].ToArray();
}
private MultiComponentList()
{
m_Tiles = new StaticTile[0][][];
m_List = new MultiTileEntry[0];
}
}
} | 412 | 0.886483 | 1 | 0.886483 | game-dev | MEDIA | 0.806901 | game-dev | 0.995994 | 1 | 0.995994 |
tangziwen/CubeMiniGame | 11,381 | CubeEngine/External/Bullet/BulletDynamics/ConstraintSolver/btConeTwistConstraint.h | /*
Bullet Continuous Collision Detection and Physics Library
btConeTwistConstraint is Copyright (c) 2007 Starbreeze Studios
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.
Written by: Marcus Hennix
*/
/*
Overview:
btConeTwistConstraint can be used to simulate ragdoll joints (upper arm, leg etc).
It is a fixed translation, 3 degree-of-freedom (DOF) rotational "joint".
It divides the 3 rotational DOFs into swing (movement within a cone) and twist.
Swing is divided into swing1 and swing2 which can have different limits, giving an elliptical shape.
(Note: the cone's base isn't flat, so this ellipse is "embedded" on the surface of a sphere.)
In the contraint's frame of reference:
twist is along the x-axis,
and swing 1 and 2 are along the z and y axes respectively.
*/
#ifndef BT_CONETWISTCONSTRAINT_H
#define BT_CONETWISTCONSTRAINT_H
#include "LinearMath/btVector3.h"
#include "btJacobianEntry.h"
#include "btTypedConstraint.h"
#ifdef BT_USE_DOUBLE_PRECISION
#define btConeTwistConstraintData2 btConeTwistConstraintDoubleData
#define btConeTwistConstraintDataName "btConeTwistConstraintDoubleData"
#else
#define btConeTwistConstraintData2 btConeTwistConstraintData
#define btConeTwistConstraintDataName "btConeTwistConstraintData"
#endif //BT_USE_DOUBLE_PRECISION
class btRigidBody;
enum btConeTwistFlags
{
BT_CONETWIST_FLAGS_LIN_CFM = 1,
BT_CONETWIST_FLAGS_LIN_ERP = 2,
BT_CONETWIST_FLAGS_ANG_CFM = 4
};
///btConeTwistConstraint can be used to simulate ragdoll joints (upper arm, leg etc)
ATTRIBUTE_ALIGNED16(class) btConeTwistConstraint : public btTypedConstraint
{
#ifdef IN_PARALLELL_SOLVER
public:
#endif
btJacobianEntry m_jac[3]; //3 orthogonal linear constraints
btTransform m_rbAFrame;
btTransform m_rbBFrame;
btScalar m_limitSoftness;
btScalar m_biasFactor;
btScalar m_relaxationFactor;
btScalar m_damping;
btScalar m_swingSpan1;
btScalar m_swingSpan2;
btScalar m_twistSpan;
btScalar m_fixThresh;
btVector3 m_swingAxis;
btVector3 m_twistAxis;
btScalar m_kSwing;
btScalar m_kTwist;
btScalar m_twistLimitSign;
btScalar m_swingCorrection;
btScalar m_twistCorrection;
btScalar m_twistAngle;
btScalar m_accSwingLimitImpulse;
btScalar m_accTwistLimitImpulse;
bool m_angularOnly;
bool m_solveTwistLimit;
bool m_solveSwingLimit;
bool m_useSolveConstraintObsolete;
// not yet used...
btScalar m_swingLimitRatio;
btScalar m_twistLimitRatio;
btVector3 m_twistAxisA;
// motor
bool m_bMotorEnabled;
bool m_bNormalizedMotorStrength;
btQuaternion m_qTarget;
btScalar m_maxMotorImpulse;
btVector3 m_accMotorImpulse;
// parameters
int m_flags;
btScalar m_linCFM;
btScalar m_linERP;
btScalar m_angCFM;
protected:
void init();
void computeConeLimitInfo(const btQuaternion& qCone, // in
btScalar& swingAngle, btVector3& vSwingAxis, btScalar& swingLimit); // all outs
void computeTwistLimitInfo(const btQuaternion& qTwist, // in
btScalar& twistAngle, btVector3& vTwistAxis); // all outs
void adjustSwingAxisToUseEllipseNormal(btVector3& vSwingAxis) const;
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
btConeTwistConstraint(btRigidBody& rbA,btRigidBody& rbB,const btTransform& rbAFrame, const btTransform& rbBFrame);
btConeTwistConstraint(btRigidBody& rbA,const btTransform& rbAFrame);
virtual void buildJacobian();
virtual void getInfo1 (btConstraintInfo1* info);
void getInfo1NonVirtual(btConstraintInfo1* info);
virtual void getInfo2 (btConstraintInfo2* info);
void getInfo2NonVirtual(btConstraintInfo2* info,const btTransform& transA,const btTransform& transB,const btMatrix3x3& invInertiaWorldA,const btMatrix3x3& invInertiaWorldB);
virtual void solveConstraintObsolete(btSolverBody& bodyA,btSolverBody& bodyB,btScalar timeStep);
void updateRHS(btScalar timeStep);
const btRigidBody& getRigidBodyA() const
{
return m_rbA;
}
const btRigidBody& getRigidBodyB() const
{
return m_rbB;
}
void setAngularOnly(bool angularOnly)
{
m_angularOnly = angularOnly;
}
bool getAngularOnly() const
{
return m_angularOnly;
}
void setLimit(int limitIndex,btScalar limitValue)
{
switch (limitIndex)
{
case 3:
{
m_twistSpan = limitValue;
break;
}
case 4:
{
m_swingSpan2 = limitValue;
break;
}
case 5:
{
m_swingSpan1 = limitValue;
break;
}
default:
{
}
};
}
btScalar getLimit(int limitIndex) const
{
switch (limitIndex)
{
case 3:
{
return m_twistSpan;
break;
}
case 4:
{
return m_swingSpan2;
break;
}
case 5:
{
return m_swingSpan1;
break;
}
default:
{
btAssert(0 && "Invalid limitIndex specified for btConeTwistConstraint");
return 0.0;
}
};
}
// setLimit(), a few notes:
// _softness:
// 0->1, recommend ~0.8->1.
// describes % of limits where movement is free.
// beyond this softness %, the limit is gradually enforced until the "hard" (1.0) limit is reached.
// _biasFactor:
// 0->1?, recommend 0.3 +/-0.3 or so.
// strength with which constraint resists zeroth order (angular, not angular velocity) limit violation.
// __relaxationFactor:
// 0->1, recommend to stay near 1.
// the lower the value, the less the constraint will fight velocities which violate the angular limits.
void setLimit(btScalar _swingSpan1,btScalar _swingSpan2,btScalar _twistSpan, btScalar _softness = 1.f, btScalar _biasFactor = 0.3f, btScalar _relaxationFactor = 1.0f)
{
m_swingSpan1 = _swingSpan1;
m_swingSpan2 = _swingSpan2;
m_twistSpan = _twistSpan;
m_limitSoftness = _softness;
m_biasFactor = _biasFactor;
m_relaxationFactor = _relaxationFactor;
}
const btTransform& getAFrame() const { return m_rbAFrame; };
const btTransform& getBFrame() const { return m_rbBFrame; };
inline int getSolveTwistLimit()
{
return m_solveTwistLimit;
}
inline int getSolveSwingLimit()
{
return m_solveSwingLimit;
}
inline btScalar getTwistLimitSign()
{
return m_twistLimitSign;
}
void calcAngleInfo();
void calcAngleInfo2(const btTransform& transA, const btTransform& transB,const btMatrix3x3& invInertiaWorldA,const btMatrix3x3& invInertiaWorldB);
inline btScalar getSwingSpan1() const
{
return m_swingSpan1;
}
inline btScalar getSwingSpan2() const
{
return m_swingSpan2;
}
inline btScalar getTwistSpan() const
{
return m_twistSpan;
}
inline btScalar getLimitSoftness() const
{
return m_limitSoftness;
}
inline btScalar getBiasFactor() const
{
return m_biasFactor;
}
inline btScalar getRelaxationFactor() const
{
return m_relaxationFactor;
}
inline btScalar getTwistAngle() const
{
return m_twistAngle;
}
bool isPastSwingLimit() { return m_solveSwingLimit; }
btScalar getDamping() const { return m_damping; }
void setDamping(btScalar damping) { m_damping = damping; }
void enableMotor(bool b) { m_bMotorEnabled = b; }
bool isMotorEnabled() const { return m_bMotorEnabled; }
btScalar getMaxMotorImpulse() const { return m_maxMotorImpulse; }
bool isMaxMotorImpulseNormalized() const { return m_bNormalizedMotorStrength; }
void setMaxMotorImpulse(btScalar maxMotorImpulse) { m_maxMotorImpulse = maxMotorImpulse; m_bNormalizedMotorStrength = false; }
void setMaxMotorImpulseNormalized(btScalar maxMotorImpulse) { m_maxMotorImpulse = maxMotorImpulse; m_bNormalizedMotorStrength = true; }
btScalar getFixThresh() { return m_fixThresh; }
void setFixThresh(btScalar fixThresh) { m_fixThresh = fixThresh; }
// setMotorTarget:
// q: the desired rotation of bodyA wrt bodyB.
// note: if q violates the joint limits, the internal target is clamped to avoid conflicting impulses (very bad for stability)
// note: don't forget to enableMotor()
void setMotorTarget(const btQuaternion &q);
const btQuaternion& getMotorTarget() const { return m_qTarget; }
// same as above, but q is the desired rotation of frameA wrt frameB in constraint space
void setMotorTargetInConstraintSpace(const btQuaternion &q);
btVector3 GetPointForAngle(btScalar fAngleInRadians, btScalar fLength) const;
///override the default global value of a parameter (such as ERP or CFM), optionally provide the axis (0..5).
///If no axis is provided, it uses the default axis for this constraint.
virtual void setParam(int num, btScalar value, int axis = -1);
virtual void setFrames(const btTransform& frameA, const btTransform& frameB);
const btTransform& getFrameOffsetA() const
{
return m_rbAFrame;
}
const btTransform& getFrameOffsetB() const
{
return m_rbBFrame;
}
///return the local value of parameter
virtual btScalar getParam(int num, int axis = -1) const;
int getFlags() const
{
return m_flags;
}
virtual int calculateSerializeBufferSize() const;
///fills the dataBuffer and returns the struct name (and 0 on failure)
virtual const char* serialize(void* dataBuffer, btSerializer* serializer) const;
};
struct btConeTwistConstraintDoubleData
{
btTypedConstraintDoubleData m_typeConstraintData;
btTransformDoubleData m_rbAFrame;
btTransformDoubleData m_rbBFrame;
//limits
double m_swingSpan1;
double m_swingSpan2;
double m_twistSpan;
double m_limitSoftness;
double m_biasFactor;
double m_relaxationFactor;
double m_damping;
};
#ifdef BT_BACKWARDS_COMPATIBLE_SERIALIZATION
///this structure is not used, except for loading pre-2.82 .bullet files
struct btConeTwistConstraintData
{
btTypedConstraintData m_typeConstraintData;
btTransformFloatData m_rbAFrame;
btTransformFloatData m_rbBFrame;
//limits
float m_swingSpan1;
float m_swingSpan2;
float m_twistSpan;
float m_limitSoftness;
float m_biasFactor;
float m_relaxationFactor;
float m_damping;
char m_pad[4];
};
#endif //BT_BACKWARDS_COMPATIBLE_SERIALIZATION
//
SIMD_FORCE_INLINE int btConeTwistConstraint::calculateSerializeBufferSize() const
{
return sizeof(btConeTwistConstraintData2);
}
///fills the dataBuffer and returns the struct name (and 0 on failure)
SIMD_FORCE_INLINE const char* btConeTwistConstraint::serialize(void* dataBuffer, btSerializer* serializer) const
{
btConeTwistConstraintData2* cone = (btConeTwistConstraintData2*) dataBuffer;
btTypedConstraint::serialize(&cone->m_typeConstraintData,serializer);
m_rbAFrame.serialize(cone->m_rbAFrame);
m_rbBFrame.serialize(cone->m_rbBFrame);
cone->m_swingSpan1 = m_swingSpan1;
cone->m_swingSpan2 = m_swingSpan2;
cone->m_twistSpan = m_twistSpan;
cone->m_limitSoftness = m_limitSoftness;
cone->m_biasFactor = m_biasFactor;
cone->m_relaxationFactor = m_relaxationFactor;
cone->m_damping = m_damping;
return btConeTwistConstraintDataName;
}
#endif //BT_CONETWISTCONSTRAINT_H
| 412 | 0.959536 | 1 | 0.959536 | game-dev | MEDIA | 0.960569 | game-dev | 0.980293 | 1 | 0.980293 |
facebookarchive/fbctf | 2,515 | src/controllers/ViewModeController.php | <?hh // strict
class ViewModeController extends Controller {
<<__Override>>
protected function getTitle(): string {
$custom_org = \HH\Asio\join(Configuration::gen('custom_org'));
return tr($custom_org->getValue()).' | '.tr('View mode');
}
<<__Override>>
protected function getFilters(): array<string, mixed> {
return array(
'GET' => array(
'page' => array(
'filter' => FILTER_VALIDATE_REGEXP,
'options' => array('regexp' => '/^[\w-]+$/'),
),
),
);
}
<<__Override>>
protected function getPages(): array<string> {
return array('main');
}
public async function genRenderMainContent(): Awaitable<:xhp> {
$branding_gen = await $this->genRenderBranding();
return
<div id="fb-gameboard" class="fb-gameboard gameboard--viewmode">
<div class="gameboard-header">
<nav class="fb-navigation fb-gameboard-nav">
<div class="branding">
<a href="/">
<div class="branding-rules">
{$branding_gen}
</div>
</a>
</div>
</nav>
</div>
<div class="fb-map"></div>
<div class="fb-module-container container--row">
<aside
data-name={tr('Leaderboard')}
class="module--outer-left active"
data-module="leaderboard-viewmode">
</aside>
<aside
data-name={tr('Activity')}
class="module--inner-right activity-viewmode active"
data-module="activity-viewmode">
</aside>
<aside
data-name={tr('Game Clock')}
class="module--outer-right active"
data-module="game-clock">
</aside>
</div>
</div>;
}
public async function genRenderPage(string $page): Awaitable<:xhp> {
switch ($page) {
case 'main':
return await $this->genRenderMainContent();
break;
default:
return await $this->genRenderMainContent();
break;
}
}
<<__Override>>
public async function genRenderBody(string $page): Awaitable<:xhp> {
$rendered_page = await $this->genRenderPage($page);
return
<body data-section="viewer-mode">
<div class="fb-sprite" id="fb-svg-sprite"></div>
<div id="fb-main-content" class="fb-page">
{$rendered_page}
</div>
<script type="text/javascript" src="static/dist/js/app.js"></script>
</body>;
}
}
| 412 | 0.58837 | 1 | 0.58837 | game-dev | MEDIA | 0.630199 | game-dev,web-frontend | 0.771508 | 1 | 0.771508 |
hack-mans/Unity-ControlNet-Rig | 1,203 | Assets/RuntimeGizmo/UndoRedo/UndoRedo.cs | using System;
using System.Collections.Generic;
namespace CommandUndoRedo
{
public class UndoRedo
{
public int maxUndoStored {get {return undoCommands.maxLength;} set {SetMaxLength(value);}}
DropoutStack<ICommand> undoCommands = new DropoutStack<ICommand>();
DropoutStack<ICommand> redoCommands = new DropoutStack<ICommand>();
public UndoRedo() {}
public UndoRedo(int maxUndoStored)
{
this.maxUndoStored = maxUndoStored;
}
public void Clear()
{
undoCommands.Clear();
redoCommands.Clear();
}
public void Undo()
{
if(undoCommands.Count > 0)
{
ICommand command = undoCommands.Pop();
command.UnExecute();
redoCommands.Push(command);
}
}
public void Redo()
{
if(redoCommands.Count > 0)
{
ICommand command = redoCommands.Pop();
command.Execute();
undoCommands.Push(command);
}
}
public void Insert(ICommand command)
{
if(maxUndoStored <= 0) return;
undoCommands.Push(command);
redoCommands.Clear();
}
public void Execute(ICommand command)
{
command.Execute();
Insert(command);
}
void SetMaxLength(int max)
{
undoCommands.maxLength = max;
redoCommands.maxLength = max;
}
}
}
| 412 | 0.739083 | 1 | 0.739083 | game-dev | MEDIA | 0.522999 | game-dev | 0.520199 | 1 | 0.520199 |
anotak/doombuilderx | 4,609 | Source/Core/Types/TypeHandler.cs |
#region ================== Copyright (c) 2007 Pascal vd Heiden
/*
* Copyright (c) 2007 Pascal vd Heiden, www.codeimp.com
* This program is released under GNU General Public License
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#endregion
#region ================== Namespaces
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Text;
using CodeImp.DoomBuilder.IO;
using CodeImp.DoomBuilder.Data;
using System.IO;
using System.Diagnostics;
using System.Windows.Forms;
using CodeImp.DoomBuilder.Config;
#endregion
namespace CodeImp.DoomBuilder.Types
{
/// <summary>
/// Type Handler base class. A Type Handler takes care of editing, validating and
/// displaying values of different types for UDMF fields and hexen arguments.
/// </summary>
internal abstract class TypeHandler
{
#region ================== Constants
#endregion
#region ================== Variables
protected int index;
protected string typename;
protected bool customusable;
protected bool forargument;
protected ArgumentInfo arginfo;
protected TypeHandlerAttribute attribute;
#endregion
#region ================== Properties
public int Index { get { return index; } }
public string TypeName { get { return typename; } }
public bool IsCustomUsable { get { return customusable; } }
public bool IsForArgument { get { return forargument; } }
public TypeHandlerAttribute Attribute { get { return attribute; } }
public virtual bool IsBrowseable { get { return false; } }
public virtual bool IsEnumerable { get { return false; } }
public virtual bool IsLimitedToEnums { get { return false; } }
public virtual Image BrowseImage { get { return null; } }
#endregion
#region ================== Constructor
// Constructor
public TypeHandler()
{
}
// This sets up the handler for arguments
public virtual void SetupArgument(TypeHandlerAttribute attr, ArgumentInfo arginfo)
{
// Setup
this.forargument = true;
this.arginfo = arginfo;
if(attr != null)
{
// Set attributes
this.attribute = attr;
this.index = attr.Index;
this.typename = attr.Name;
this.customusable = attr.IsCustomUsable;
}
else
{
// Indexless
this.attribute = null;
this.index = -1;
this.typename = "Unknown";
this.customusable = false;
}
}
// This sets up the handler for arguments
public virtual void SetupField(TypeHandlerAttribute attr, UniversalFieldInfo fieldinfo)
{
// Setup
this.forargument = false;
if(attr != null)
{
// Set attributes
this.attribute = attr;
this.index = attr.Index;
this.typename = attr.Name;
this.customusable = attr.IsCustomUsable;
}
else
{
// Indexless
this.attribute = null;
this.index = -1;
this.typename = "Unknown";
this.customusable = false;
}
}
#endregion
#region ================== Methods
// This must set the value
// How the value is actually validated and stored is up to the implementation
public abstract void SetValue(object value);
//mxd. This should replace current value with the default one
public virtual void ApplyDefaultValue() { }
// This must return the value as one of the primitive data types
// supported by UDMF: int, string, float or bool
public abstract object GetValue();
//mxd. This should return the default value
public abstract object GetDefaultValue();
// This must return the value as integer (for arguments)
public virtual int GetIntValue()
{
throw new NotSupportedException("Override this method to support it as integer for arguments");
}
// This must return the value as a string for displaying
public abstract string GetStringValue();
// This is called when the user presses the browse button
public virtual void Browse(IWin32Window parent)
{
}
// This must returns an enum list when IsEnumerable is true
public virtual EnumList GetEnumList()
{
return null;
}
// String representation
public override string ToString()
{
return this.GetStringValue();
}
// This returns the type to display for fixed fields
// Must be a custom usable type
public virtual TypeHandlerAttribute GetDisplayType()
{
return this.attribute;
}
#endregion
}
}
| 412 | 0.848781 | 1 | 0.848781 | game-dev | MEDIA | 0.277762 | game-dev | 0.883966 | 1 | 0.883966 |
needle-mirror/com.unity.entities | 1,260 | Unity.Entities.Hybrid.Tests/Baking/SeparateAssembly/ComponentInAssemblyAuthoring.cs | using UnityEngine;
namespace Unity.Entities.Hybrid.Tests.Baking.SeparateAssembly
{
public class ComponentInAssemblyAuthoring : MonoBehaviour
{
public int value;
}
public struct ComponentInAssemblyBakerC : IComponentData
{
public int value;
}
public struct ComponentInAssemblyBakingSystemC : IComponentData
{
public int value;
}
public class ComponentInAssemblyAuthoringBaker : Baker<ComponentInAssemblyAuthoring>
{
public override void Bake(ComponentInAssemblyAuthoring authoring)
{
var entity = GetEntity(TransformUsageFlags.None);
AddComponent(entity, new ComponentInAssemblyBakerC
{
value = authoring.value
});
}
}
[WorldSystemFilter(WorldSystemFilterFlags.BakingSystem)]
public partial class ComponentInAssemblyBakingSystem : SystemBase
{
private EntityQuery query;
protected override void OnCreate()
{
query = GetEntityQuery(
typeof(ComponentInAssemblyBakerC));
}
protected override void OnUpdate()
{
EntityManager.AddComponent<ComponentInAssemblyBakingSystemC>(query);
}
}
}
| 412 | 0.584806 | 1 | 0.584806 | game-dev | MEDIA | 0.933977 | game-dev | 0.565456 | 1 | 0.565456 |
manateelazycat/deepin-terminal | 18,220 | vapi/gee-1.0.vapi | /* gee-1.0.vapi generated by valac 0.24.0.89-24e8-dirty, do not modify. */
[CCode (gir_namespace = "Gee", gir_version = "1.0")]
namespace Gee {
namespace Functions {
[CCode (cheader_filename = "gee.h")]
public static GLib.CompareFunc get_compare_func_for (GLib.Type t);
[CCode (cheader_filename = "gee.h")]
public static GLib.EqualFunc get_equal_func_for (GLib.Type t);
[CCode (cheader_filename = "gee.h")]
public static GLib.HashFunc get_hash_func_for (GLib.Type t);
}
[CCode (cheader_filename = "gee.h")]
public abstract class AbstractCollection<G> : GLib.Object, Gee.Iterable<G>, Gee.Collection<G> {
public AbstractCollection ();
public abstract bool add (G item);
public virtual bool add_all (Gee.Collection<G> collection);
public abstract void clear ();
public abstract bool contains (G item);
public virtual bool contains_all (Gee.Collection<G> collection);
public abstract Gee.Iterator<G> iterator ();
public abstract bool remove (G item);
public virtual bool remove_all (Gee.Collection<G> collection);
public virtual bool retain_all (Gee.Collection<G> collection);
public virtual G[] to_array ();
public virtual bool is_empty { get; }
public virtual Gee.Collection<G> read_only_view { owned get; }
public abstract int size { get; }
}
[CCode (cheader_filename = "gee.h")]
public abstract class AbstractList<G> : Gee.AbstractCollection<G>, Gee.List<G> {
public AbstractList ();
public virtual G first ();
public abstract new G @get (int index);
public abstract int index_of (G item);
public abstract void insert (int index, G item);
public virtual void insert_all (int index, Gee.Collection<G> collection);
public virtual G last ();
public abstract Gee.ListIterator<G> list_iterator ();
public abstract G remove_at (int index);
public abstract new void @set (int index, G item);
public abstract Gee.List<G>? slice (int start, int stop);
public virtual Gee.List<G> read_only_view { owned get; }
}
[CCode (cheader_filename = "gee.h")]
public abstract class AbstractMap<K,V> : GLib.Object, Gee.Iterable<Gee.Map.Entry<K,V>>, Gee.Map<K,V> {
public AbstractMap ();
public abstract void clear ();
public abstract new V @get (K key);
public abstract bool has (K key, V value);
public virtual bool has_all (Gee.Map<K,V> map);
public abstract bool has_key (K key);
public abstract Gee.MapIterator<K,V> map_iterator ();
public abstract new void @set (K key, V value);
public virtual void set_all (Gee.Map<K,V> map);
public abstract bool unset (K key, out V value = null);
public virtual bool unset_all (Gee.Map<K,V> map);
public abstract Gee.Set<Gee.Map.Entry<K,V>> entries { owned get; }
public virtual bool is_empty { get; }
public abstract Gee.Set<K> keys { owned get; }
public virtual Gee.Map<K,V> read_only_view { owned get; }
public abstract int size { get; }
public abstract Gee.Collection<V> values { owned get; }
}
[CCode (cheader_filename = "gee.h")]
public abstract class AbstractMultiMap<K,V> : GLib.Object, Gee.MultiMap<K,V> {
protected Gee.Map<K,Gee.Collection<V>> _storage_map;
public AbstractMultiMap (Gee.Map<K,Gee.Collection<V>> storage_map);
protected abstract Gee.MultiSet<K> create_multi_key_set ();
protected abstract Gee.Collection<V> create_value_storage ();
protected abstract GLib.EqualFunc get_value_equal_func ();
}
[CCode (cheader_filename = "gee.h")]
public abstract class AbstractMultiSet<G> : Gee.AbstractCollection<G>, Gee.MultiSet<G> {
protected Gee.Map<G,int> _storage_map;
public AbstractMultiSet (Gee.Map<G,int> storage_map);
public override bool add (G item);
public override void clear ();
public override bool contains (G item);
public override Gee.Iterator<G> iterator ();
public override bool remove (G item);
public override int size { get; }
}
[CCode (cheader_filename = "gee.h")]
public abstract class AbstractQueue<G> : Gee.AbstractCollection<G>, Gee.Queue<G> {
public AbstractQueue ();
public abstract int drain (Gee.Collection<G> recipient, int amount = -1);
public abstract bool offer (G element);
public abstract G peek ();
public abstract G poll ();
public abstract int capacity { get; }
public abstract bool is_full { get; }
public abstract int remaining_capacity { get; }
}
[CCode (cheader_filename = "gee.h")]
public abstract class AbstractSet<G> : Gee.AbstractCollection<G>, Gee.Set<G> {
public AbstractSet ();
public virtual Gee.Set<G> read_only_view { owned get; }
}
[CCode (cheader_filename = "gee.h")]
public class ArrayList<G> : Gee.AbstractList<G> {
public ArrayList (GLib.EqualFunc? equal_func = null);
public override bool add (G item);
public override bool add_all (Gee.Collection<G> collection);
public override void clear ();
public override bool contains (G item);
public override G @get (int index);
public override int index_of (G item);
public override void insert (int index, G item);
public override Gee.Iterator<G> iterator ();
public override Gee.ListIterator<G> list_iterator ();
public override bool remove (G item);
public override G remove_at (int index);
public override void @set (int index, G item);
public override Gee.List<G>? slice (int start, int stop);
public void sort_with_data (GLib.CompareDataFunc compare);
public GLib.EqualFunc equal_func { get; private set; }
public override int size { get; }
}
[CCode (cheader_filename = "gee.h")]
public class HashMap<K,V> : Gee.AbstractMap<K,V> {
public HashMap (GLib.HashFunc? key_hash_func = null, GLib.EqualFunc? key_equal_func = null, GLib.EqualFunc? value_equal_func = null);
public override void clear ();
public override V @get (K key);
public override bool has (K key, V value);
public override bool has_key (K key);
public override Gee.MapIterator<K,V> map_iterator ();
public override void @set (K key, V value);
public override bool unset (K key, out V value = null);
public override Gee.Set<Gee.Map.Entry<K,V>> entries { owned get; }
public GLib.EqualFunc key_equal_func { get; private set; }
public GLib.HashFunc key_hash_func { get; private set; }
public override Gee.Set<K> keys { owned get; }
public override int size { get; }
public GLib.EqualFunc value_equal_func { get; private set; }
public override Gee.Collection<V> values { owned get; }
}
[CCode (cheader_filename = "gee.h")]
public class HashMultiMap<K,V> : Gee.AbstractMultiMap<K,V> {
public HashMultiMap (GLib.HashFunc? key_hash_func = null, GLib.EqualFunc? key_equal_func = null, GLib.HashFunc? value_hash_func = null, GLib.EqualFunc? value_equal_func = null);
protected override Gee.MultiSet<K> create_multi_key_set ();
protected override Gee.Collection<V> create_value_storage ();
protected override GLib.EqualFunc get_value_equal_func ();
public GLib.EqualFunc key_equal_func { get; }
public GLib.HashFunc key_hash_func { get; }
public GLib.EqualFunc value_equal_func { get; private set; }
public GLib.HashFunc value_hash_func { get; private set; }
}
[CCode (cheader_filename = "gee.h")]
public class HashMultiSet<G> : Gee.AbstractMultiSet<G> {
public HashMultiSet (GLib.HashFunc? hash_func = null, GLib.EqualFunc? equal_func = null);
public GLib.EqualFunc equal_func { get; }
public GLib.HashFunc hash_func { get; }
}
[CCode (cheader_filename = "gee.h")]
public class HashSet<G> : Gee.AbstractSet<G> {
public HashSet (GLib.HashFunc? hash_func = null, GLib.EqualFunc? equal_func = null);
public override bool add (G key);
public override void clear ();
public override bool contains (G key);
public override Gee.Iterator<G> iterator ();
public override bool remove (G key);
public GLib.EqualFunc equal_func { get; private set; }
public GLib.HashFunc hash_func { get; private set; }
public override int size { get; }
}
[CCode (cheader_filename = "gee.h")]
public class LinkedList<G> : Gee.AbstractList<G>, Gee.Queue<G>, Gee.Deque<G> {
public LinkedList (GLib.EqualFunc? equal_func = null);
public override bool add (G item);
public override void clear ();
public override bool contains (G item);
public override G first ();
public override G @get (int index);
public override int index_of (G item);
public override void insert (int index, G item);
public override Gee.Iterator<G> iterator ();
public override G last ();
public override Gee.ListIterator<G> list_iterator ();
public override bool remove (G item);
public override G remove_at (int index);
public override void @set (int index, G item);
public override Gee.List<G>? slice (int start, int stop);
public GLib.EqualFunc equal_func { get; private set; }
public override int size { get; }
}
[CCode (cheader_filename = "gee.h")]
public class PriorityQueue<G> : Gee.AbstractQueue<G> {
public PriorityQueue (GLib.CompareFunc? compare_func = null);
public override bool add (G item);
public override void clear ();
public override bool contains (G item);
public override int drain (Gee.Collection<G> recipient, int amount = -1);
public override Gee.Iterator<G> iterator ();
public override bool offer (G element);
public override G peek ();
public override G poll ();
public override bool remove (G item);
public override int capacity { get; }
public GLib.CompareFunc compare_func { get; private set; }
public override bool is_full { get; }
public override int remaining_capacity { get; }
public override int size { get; }
}
[CCode (cheader_filename = "gee.h")]
public class TreeMap<K,V> : Gee.AbstractMap<K,V> {
public TreeMap (GLib.CompareFunc? key_compare_func = null, GLib.EqualFunc? value_equal_func = null);
public override void clear ();
public override V @get (K key);
public override bool has (K key, V value);
public override bool has_key (K key);
public override Gee.MapIterator<K,V> map_iterator ();
public override void @set (K key, V value);
public override bool unset (K key, out V value = null);
public override Gee.Set<Gee.Map.Entry<K,V>> entries { owned get; }
public GLib.CompareFunc key_compare_func { get; private set; }
public override Gee.Set<K> keys { owned get; }
public override int size { get; }
public GLib.EqualFunc value_equal_func { get; private set; }
public override Gee.Collection<V> values { owned get; }
}
[CCode (cheader_filename = "gee.h")]
public class TreeMultiMap<K,V> : Gee.AbstractMultiMap<K,V> {
public TreeMultiMap (GLib.CompareFunc? key_compare_func = null, GLib.CompareFunc? value_compare_func = null);
protected override Gee.MultiSet<K> create_multi_key_set ();
protected override Gee.Collection<V> create_value_storage ();
protected override GLib.EqualFunc get_value_equal_func ();
public GLib.CompareFunc key_compare_func { get; }
public GLib.CompareFunc value_compare_func { get; private set; }
}
[CCode (cheader_filename = "gee.h")]
public class TreeMultiSet<G> : Gee.AbstractMultiSet<G> {
public TreeMultiSet (GLib.CompareFunc? compare_func = null);
public GLib.CompareFunc compare_func { get; }
}
[CCode (cheader_filename = "gee.h")]
public class TreeSet<G> : Gee.AbstractSet<G>, Gee.SortedSet<G> {
public TreeSet (GLib.CompareFunc? compare_func = null);
public override bool add (G item);
public override void clear ();
public override bool contains (G item);
public override Gee.Iterator<G> iterator ();
public override bool remove (G item);
public GLib.CompareFunc compare_func { get; private set; }
public override int size { get; }
}
[CCode (cheader_filename = "gee.h")]
public interface BidirIterator<G> : Gee.Iterator<G> {
public abstract bool has_previous ();
public abstract bool last ();
public abstract bool previous ();
}
[CCode (cheader_filename = "gee.h")]
public interface Collection<G> : Gee.Iterable<G> {
public abstract bool add (G item);
public abstract bool add_all (Gee.Collection<G> collection);
public abstract void clear ();
public abstract bool contains (G item);
public abstract bool contains_all (Gee.Collection<G> collection);
public static Gee.Collection<G> empty<G> ();
public abstract bool remove (G item);
public abstract bool remove_all (Gee.Collection<G> collection);
public abstract bool retain_all (Gee.Collection<G> collection);
public abstract G[] to_array ();
public abstract bool is_empty { get; }
public abstract Gee.Collection<G> read_only_view { owned get; }
public abstract int size { get; }
}
[CCode (cheader_filename = "gee.h")]
public interface Comparable<G> : GLib.Object {
public abstract int compare_to (G object);
}
[CCode (cheader_filename = "gee.h")]
public interface Deque<G> : Gee.Queue<G> {
public abstract int drain_head (Gee.Collection<G> recipient, int amount = -1);
public abstract int drain_tail (Gee.Collection<G> recipient, int amount = -1);
public abstract bool offer_head (G element);
public abstract bool offer_tail (G element);
public abstract G peek_head ();
public abstract G peek_tail ();
public abstract G poll_head ();
public abstract G poll_tail ();
}
[CCode (cheader_filename = "gee.h")]
public interface Iterable<G> : GLib.Object {
public abstract Gee.Iterator<G> iterator ();
public abstract GLib.Type element_type { get; }
}
[CCode (cheader_filename = "gee.h")]
public interface Iterator<G> : GLib.Object {
public abstract bool first ();
public abstract G @get ();
public abstract bool has_next ();
public abstract bool next ();
public abstract void remove ();
}
[CCode (cheader_filename = "gee.h")]
public interface List<G> : Gee.Collection<G> {
public static Gee.List<G> empty<G> ();
public abstract G first ();
public abstract G @get (int index);
public abstract int index_of (G item);
public abstract void insert (int index, G item);
public abstract void insert_all (int index, Gee.Collection<G> collection);
public abstract G last ();
public abstract new Gee.ListIterator<G> list_iterator ();
public abstract G remove_at (int index);
public abstract void @set (int index, G item);
public abstract Gee.List<G>? slice (int start, int stop);
public abstract void sort (GLib.CompareFunc? compare_func = null);
public abstract Gee.List<G> read_only_view { owned get; }
}
[CCode (cheader_filename = "gee.h")]
public interface ListIterator<G> : Gee.BidirIterator<G> {
public abstract void add (G item);
public abstract int index ();
public abstract void insert (G item);
public abstract void @set (G item);
}
[CCode (cheader_filename = "gee.h")]
public interface Map<K,V> : GLib.Object, Gee.Iterable<Gee.Map.Entry<K,V>> {
public abstract class Entry<K,V> : GLib.Object {
public Entry ();
public abstract K key { get; }
public abstract V value { get; set; }
}
public abstract void clear ();
[Deprecated]
public abstract bool contains (K key);
[Deprecated]
public abstract bool contains_all (Gee.Map<K,V> map);
public static Gee.Map<K,V> empty<K,V> ();
public abstract V @get (K key);
public abstract bool has (K key, V value);
public abstract bool has_all (Gee.Map<K,V> map);
public abstract bool has_key (K key);
public abstract Gee.MapIterator<K,V> map_iterator ();
[Deprecated]
public abstract bool remove (K key, out V value = null);
[Deprecated]
public abstract bool remove_all (Gee.Map<K,V> map);
public abstract void @set (K key, V value);
public abstract void set_all (Gee.Map<K,V> map);
public abstract bool unset (K key, out V value = null);
public abstract bool unset_all (Gee.Map<K,V> map);
public abstract Gee.Set<Gee.Map.Entry<K,V>> entries { owned get; }
public abstract bool is_empty { get; }
public abstract GLib.Type key_type { get; }
public abstract Gee.Set<K> keys { owned get; }
public abstract Gee.Map<K,V> read_only_view { owned get; }
public abstract int size { get; }
public abstract GLib.Type value_type { get; }
public abstract Gee.Collection<V> values { owned get; }
}
[CCode (cheader_filename = "gee.h")]
public interface MapIterator<K,V> : GLib.Object {
public abstract bool first ();
public abstract K get_key ();
public abstract V get_value ();
public abstract bool has_next ();
public abstract bool next ();
public abstract void set_value (V value);
public abstract void unset ();
}
[CCode (cheader_filename = "gee.h")]
public interface MultiMap<K,V> : GLib.Object {
public abstract void clear ();
public abstract bool contains (K key);
public abstract Gee.Collection<V> @get (K key);
public abstract Gee.MultiSet<K> get_all_keys ();
public abstract Gee.Set<K> get_keys ();
public abstract Gee.Collection<V> get_values ();
public abstract bool remove (K key, V value);
public abstract bool remove_all (K key);
public abstract void @set (K key, V value);
public abstract int size { get; }
}
[CCode (cheader_filename = "gee.h")]
public interface MultiSet<G> : Gee.Collection<G> {
public abstract int count (G item);
}
[CCode (cheader_filename = "gee.h")]
public interface Queue<G> : Gee.Collection<G> {
public const int UNBOUNDED_CAPACITY;
public abstract int drain (Gee.Collection<G> recipient, int amount = -1);
public abstract bool offer (G element);
public abstract G peek ();
public abstract G poll ();
public abstract int capacity { get; }
public abstract bool is_full { get; }
public abstract int remaining_capacity { get; }
}
[CCode (cheader_filename = "gee.h")]
public interface Set<G> : Gee.Collection<G> {
public static Gee.Set<G> empty<G> ();
public abstract Gee.Set<G> read_only_view { owned get; }
}
[CCode (cheader_filename = "gee.h")]
public interface SortedSet<G> : Gee.Set<G> {
public abstract Gee.BidirIterator<G> bidir_iterator ();
public abstract G ceil (G element);
public abstract G first ();
public abstract G floor (G element);
public abstract Gee.SortedSet<G> head_set (G before);
public abstract G higher (G element);
public abstract Gee.BidirIterator<G>? iterator_at (G element);
public abstract G last ();
public abstract G lower (G element);
public abstract Gee.SortedSet<G> sub_set (G from, G to);
public abstract Gee.SortedSet<G> tail_set (G after);
}
[CCode (cheader_filename = "gee.h")]
public static int direct_compare (void* _val1, void* _val2);
}
| 412 | 0.800892 | 1 | 0.800892 | game-dev | MEDIA | 0.42598 | game-dev | 0.63873 | 1 | 0.63873 |
Retera/WarsmashModEngine | 1,522 | core/src/com/etheller/warsmash/viewer5/handlers/w3x/simulation/abilitybuilder/behavior/action/destructable/ABActionAddDestructableBuff.java | package com.etheller.warsmash.viewer5.handlers.w3x.simulation.abilitybuilder.behavior.action.destructable;
import java.util.Map;
import com.etheller.warsmash.parsers.jass.JassTextGenerator;
import com.etheller.warsmash.viewer5.handlers.w3x.simulation.CSimulation;
import com.etheller.warsmash.viewer5.handlers.w3x.simulation.CUnit;
import com.etheller.warsmash.viewer5.handlers.w3x.simulation.abilities.generic.CDestructableBuff;
import com.etheller.warsmash.viewer5.handlers.w3x.simulation.abilitybuilder.behavior.callback.destructable.ABDestructableCallback;
import com.etheller.warsmash.viewer5.handlers.w3x.simulation.abilitybuilder.behavior.callback.destructablebuff.ABDestructableBuffCallback;
import com.etheller.warsmash.viewer5.handlers.w3x.simulation.abilitybuilder.core.ABSingleAction;
public class ABActionAddDestructableBuff implements ABSingleAction {
private ABDestructableCallback target;
private ABDestructableBuffCallback buff;
@Override
public void runAction(final CSimulation game, final CUnit caster, final Map<String, Object> localStore,
final int castId) {
final CDestructableBuff ability = this.buff.callback(game, caster, localStore, castId);
this.target.callback(game, caster, localStore, castId).add(game, ability);
}
@Override
public String generateJassEquivalent(final JassTextGenerator jassTextGenerator) {
return "AddDestructableBuff(" + this.target.generateJassEquivalent(jassTextGenerator) + ", "
+ this.buff.generateJassEquivalent(jassTextGenerator) + ")";
}
}
| 412 | 0.690964 | 1 | 0.690964 | game-dev | MEDIA | 0.954187 | game-dev | 0.682378 | 1 | 0.682378 |
hyvanmielenpelit/GnollHack | 75,152 | src/worn.c | /* GnollHack File Change Notice: This file has been changed from the original. Date of last change: 2024-08-11 */
/* GnollHack 4.0 worn.c $NHDT-Date: 1550524569 2019/02/18 21:16:09 $ $NHDT-Branch: GnollHack-3.6.2-beta01 $:$NHDT-Revision: 1.56 $ */
/* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
/*-Copyright (c) Robert Patrick Rankin, 2013. */
/* GnollHack may be freely redistributed. See license for details. */
#include "hack.h"
STATIC_DCL void FDECL(m_lose_armor, (struct monst *, struct obj *));
STATIC_DCL boolean FDECL(m_dowear_type,
(struct monst *, int64_t, BOOLEAN_P, BOOLEAN_P));
STATIC_DCL int FDECL(extra_pref, (struct monst *, struct obj *));
STATIC_DCL void FDECL(set_mon_temporary_property, (struct monst*, int, UNSIGNED_SHORT_P));
const struct worn {
int64_t w_mask;
struct obj **w_obj;
} worn[] = { { W_ARM, &uarm },
{ W_ARMC, &uarmc },
{ W_ARMO, &uarmo },
{ W_ARMH, &uarmh },
{ W_ARMS, &uarms },
{ W_ARMB, &uarmb },
{ W_ARMG, &uarmg },
{ W_ARMF, &uarmf },
{ W_ARMU, &uarmu },
{ W_RINGL, &uleft },
{ W_RINGR, &uright },
{ W_WEP, &uwep },
{ W_SWAPWEP, &uswapwep },
{ W_SWAPWEP2, &uswapwep2 },
{ W_QUIVER, &uquiver },
{ W_AMUL, &uamul },
{ W_MISC, &umisc },
{ W_MISC2, &umisc2 },
{ W_MISC3, &umisc3 },
{ W_MISC4, &umisc4 },
{ W_MISC5, &umisc5 },
{ W_BLINDFOLD, &ublindf },
{ W_BALL, &uball },
{ W_CHAIN, &uchain },
{ 0, 0 }
};
void
setworn(obj, mask)
register struct obj* obj;
int64_t mask;
{
setworncore(obj, mask, TRUE);
}
/* Does not update stats */
void
setwornquietly(obj, mask)
register struct obj* obj;
int64_t mask;
{
setworncore(obj, mask, FALSE);
}
/* note: monsters don't have clairvoyance, so your role
has no significant effect on their use of w_blocks() */
/* Updated to use the extrinsic and blocked fields. */
void
setworncore(obj, mask, verbose_and_update_stats)
register struct obj *obj;
int64_t mask;
boolean verbose_and_update_stats;
{
register const struct worn *wp;
register struct obj* oobj = (struct obj*)0;
// register int p;
int oldmanamax = u.uenmax;
int oldhpmax = u.uhpmax;
int oldstr = ACURR(A_STR);
int olddex = ACURR(A_DEX);
int oldcon = ACURR(A_CON);
int oldint = ACURR(A_INT);
int oldwis = ACURR(A_WIS);
int oldcha = ACURR(A_CHA);
int oldac = u.uac;
int oldmc = u.umc;
if ((mask & (W_ARM | I_SPECIAL)) == (W_ARM | I_SPECIAL))
{
/* restoring saved game; no properties are conferred via skin */
uskin = obj;
/* assert( !uarm ); */
}
else
{
if ((mask & W_ARMOR))
u.uroleplay.nudist = FALSE;
for (wp = worn; wp->w_mask; wp++)
{
if (wp->w_mask & mask)
{
oobj = *(wp->w_obj);
if (oobj && !(oobj->owornmask & wp->w_mask))
{
impossible("Setworn: mask = %ld, oworn = %ld, update = %d.", wp->w_mask, oobj->owornmask, verbose_and_update_stats);
}
/* If old object remove wornmask */
if (oobj)
{
oobj->owornmask &= ~wp->w_mask;
/* leave as "x = x <op> y", here and below, for broken
* compilers */
/*
if (wp->w_mask & ~(W_SWAPWEP | W_QUIVER)) {
struct objclass* peritem = &objects[oobj->otyp];
p = objects[oobj->otyp].oc_oprop;
u.uprops[p].extrinsic =
u.uprops[p].extrinsic & ~wp->w_mask;
p = objects[oobj->otyp].oc_oprop2;
u.uprops[p].extrinsic =
u.uprops[p].extrinsic & ~wp->w_mask;
p = objects[oobj->otyp].oc_oprop3;
u.uprops[p].extrinsic =
u.uprops[p].extrinsic & ~wp->w_mask;
if ((p = w_blocks(oobj, mask)) != 0)
u.uprops[p].blocked &= ~wp->w_mask;
if (oobj->oartifact)
set_artifact_intrinsic(oobj, 0, mask);
}
*/
/* in case wearing or removal is in progress or removal
is pending (via 'A' command for multiple items) */
cancel_doff(oobj, wp->w_mask);
}
/* Set new object worn */
*(wp->w_obj) = obj;
if (obj)
{
obj->owornmask |= wp->w_mask;
obj->speflags &= ~SPEFLAGS_PREVIOUSLY_WIELDED;
/* Prevent getting/blocking intrinsics from wielding
* potions, through the quiver, etc.
* Allow weapon-tools, too.
* wp_mask should be same as mask at this point.
*/
/*
if (wp->w_mask & ~(W_SWAPWEP | W_QUIVER)) {
if (obj->oclass == WEAPON_CLASS || is_weptool(obj)
|| mask != W_WEP) {
struct objclass* peritem = &objects[obj->otyp];
p = objects[obj->otyp].oc_oprop;
u.uprops[p].extrinsic =
u.uprops[p].extrinsic | wp->w_mask;
p = objects[obj->otyp].oc_oprop2;
u.uprops[p].extrinsic =
u.uprops[p].extrinsic | wp->w_mask;
p = objects[obj->otyp].oc_oprop3;
u.uprops[p].extrinsic =
u.uprops[p].extrinsic | wp->w_mask;
if ((p = w_blocks(obj, mask)) != 0)
u.uprops[p].blocked |= wp->w_mask;
}
if (obj->oartifact)
set_artifact_intrinsic(obj, 1, mask);
}
*/
}
}
}
}
/* No need to go further if verbose_and_update_stats == FALSE, as we are in newgame or restoring a saved game */
if (!verbose_and_update_stats)
return;
boolean needbecomecursedmsg = FALSE;
/* curse first */
if (obj && (objects[obj->otyp].oc_flags & O1_BECOMES_CURSED_WHEN_WORN) && !obj->cursed && (mask & (W_WEP | W_WEP2 | W_ARMOR | W_ACCESSORY)))
{
needbecomecursedmsg = TRUE;
curse(obj);
}
/* Readying a weapon to quiver or swap weapon slot does not trigger artifact name discovery -- JG */
if ((mask & (W_WEP | W_WEP2 | W_ARMOR | W_ACCESSORY)) && obj && obj->oartifact && !obj->nknown && (artilist[obj->oartifact].aflags & (AF_FAMOUS | AF_NAME_KNOWN_WHEN_PICKED_UP | AF_NAME_KNOWN_WHEN_WORN_OR_WIELDED)))
{
if (verbose_and_update_stats)
{
play_sfx_sound(SFX_ARTIFACT_NAME_KNOWN);
pline_ex(ATR_NONE, CLR_MSG_HINT, "As you %s %s, you become aware that %s named %s!",
(mask == W_WEP || (u.twoweap && mask == W_WEP2)) ? "wield" : "wear", the(cxname(obj)),
(pair_of(obj) || obj->quan > 1) ? "they are" : "it is",
bare_artifactname(obj));
}
obj->nknown = TRUE;
}
update_all_character_properties(obj, verbose_and_update_stats);
/* Note that this does not work for weapons if there is an old weapon, since we do not know whether the change was caused by the old or the new weapon */
if ((obj && !oobj) || (oobj && !obj))
{
if ((
u.uenmax != oldmanamax
|| u.uhpmax != oldhpmax
|| ACURR(A_STR) != oldstr
|| ACURR(A_DEX) != olddex
|| ACURR(A_CON) != oldcon
|| ACURR(A_INT) != oldint
|| ACURR(A_WIS) != oldwis
|| ACURR(A_CHA) != oldcha
|| (obj && obj->oclass != ARMOR_CLASS && u.uac != oldac)
|| (obj && obj->oclass != ARMOR_CLASS && obj->oclass != WEAPON_CLASS && u.umc != oldmc)
|| (!obj && oobj && oobj->oclass != ARMOR_CLASS && u.uac != oldac)
|| (!obj && oobj && oobj->oclass != ARMOR_CLASS && oobj->oclass != WEAPON_CLASS && u.umc != oldmc)
)) // this should identify all objects giving hp or mana or stats or non-armors giving ac or mc
{
if (obj)
{
if (obj->oclass == RING_CLASS || obj->oclass == MISCELLANEOUS_CLASS) //Observable ring
learnring(obj, TRUE);
else
makeknown(obj->otyp);
}
else if (oobj)
{
if (oobj->oclass == RING_CLASS || oobj->oclass == MISCELLANEOUS_CLASS) //Observable ring
learnring(oobj, TRUE);
else
makeknown(oobj->otyp);
}
}
else
{
if (obj)
{
if (obj->oclass == RING_CLASS || obj->oclass == MISCELLANEOUS_CLASS)
{
//Nonobservable ring
learnring(obj, FALSE);
}
}
else if (oobj)
{
if (oobj->oclass == RING_CLASS || oobj->oclass == MISCELLANEOUS_CLASS)
{
//Nonobservable ring
learnring(oobj, FALSE);
}
}
}
context.botl = context.botlx = 1;
if (needbecomecursedmsg)
{
if (Blind)
pline_ex(ATR_NONE, CLR_MSG_WARNING, "%s for a moment.", Tobjnam(obj, "vibrate"));
else
pline_multi_ex(ATR_NONE, Hallucination ? CLR_MSG_HALLUCINATED : CLR_MSG_NEGATIVE, no_multiattrs, multicolor_buffer, "%s %s for a moment.", Tobjnam(obj, "glow"),
hcolor_multi_buf1(NH_BLACK));
}
}
update_inventory();
}
void
setnotworn(obj)
register struct obj* obj;
{
setnotworncore(obj, TRUE);
}
void
setnotwornquietly(obj)
register struct obj* obj;
{
setnotworncore(obj, FALSE);
}
/* called e.g. when obj is destroyed */
/* Updated to use the extrinsic and blocked fields. */
void
setnotworncore(obj, verbose)
register struct obj *obj;
boolean verbose;
{
register const struct worn *wp;
if (!obj)
return;
int oldmanamax = u.uenmax;
int oldhpmax = u.uhpmax;
int oldstr = ACURR(A_STR);
int olddex = ACURR(A_DEX);
int oldcon = ACURR(A_CON);
int oldint = ACURR(A_INT);
int oldwis = ACURR(A_WIS);
int oldcha = ACURR(A_CHA);
int oldac = u.uac;
int oldmc = u.umc;
for (wp = worn; wp->w_mask; wp++)
{
if (obj == *(wp->w_obj))
{
/* in case wearing or removal is in progress or removal
is pending (via 'A' command for multiple items) */
cancel_doff(obj, wp->w_mask);
*(wp->w_obj) = 0;
obj->owornmask &= ~wp->w_mask;
}
}
update_all_character_properties(obj, verbose);
if (obj)
{
if ((
u.uenmax != oldmanamax
|| u.uhpmax != oldhpmax
|| ACURR(A_STR) != oldstr
|| ACURR(A_DEX) != olddex
|| ACURR(A_CON) != oldcon
|| ACURR(A_INT) != oldint
|| ACURR(A_WIS) != oldwis
|| ACURR(A_CHA) != oldcha
|| (obj->oclass != ARMOR_CLASS && u.uac != oldac)
|| (obj->oclass != ARMOR_CLASS && obj->oclass != WEAPON_CLASS && u.umc != oldmc)
)) // this should identify all objects giving hp or mana or stats or ac
{
if (obj->oclass == RING_CLASS || obj->oclass == MISCELLANEOUS_CLASS) //Observable ring
learnring(obj, TRUE);
else
makeknown(obj->otyp);
}
else if (obj->oclass == RING_CLASS || obj->oclass == MISCELLANEOUS_CLASS)
{
//Nonobservable ring
learnring(obj, FALSE);
}
context.botl = context.botlx = 1;
}
update_inventory();
}
/* return item worn in slot indiciated by wornmask; needed by poly_obj() */
struct obj *
wearmask_to_obj(wornmask)
int64_t wornmask;
{
const struct worn *wp;
for (wp = worn; wp->w_mask; wp++)
if (wp->w_mask & wornmask)
return *wp->w_obj;
return (struct obj *) 0;
}
/* return a bitmask of the equipment slot(s) a given item might be worn in */
int64_t
wearslot(obj)
struct obj *obj;
{
int otyp = obj->otyp;
/* practically any item can be wielded or quivered; it's up to
our caller to handle such things--we assume "normal" usage */
int64_t res = 0L; /* default: can't be worn anywhere */
switch (obj->oclass) {
case AMULET_CLASS:
res = W_AMUL; /* WORN_AMUL */
break;
case MISCELLANEOUS_CLASS:
res = W_MISCITEMS;
break;
case RING_CLASS:
res = W_RINGL | W_RINGR; /* W_RING, BOTH_SIDES */
break;
case ARMOR_CLASS:
switch (objects[otyp].oc_armor_category) {
case ARM_SUIT:
res = W_ARM;
break; /* WORN_ARMOR */
case ARM_SHIELD:
res = W_ARMS;
break; /* WORN_SHIELD */
case ARM_HELM:
res = W_ARMH;
break; /* WORN_HELMET */
case ARM_GLOVES:
res = W_ARMG;
break; /* WORN_GLOVES */
case ARM_BOOTS:
res = W_ARMF;
break; /* WORN_BOOTS */
case ARM_CLOAK:
res = W_ARMC;
break; /* WORN_CLOAK */
case ARM_SHIRT:
res = W_ARMU;
break; /* WORN_SHIRT */
case ARM_ROBE:
res = W_ARMO;
break; /* WORN_ROBE */
case ARM_BRACERS:
res = W_ARMB;
break; /* BRACERS */
}
break;
case WEAPON_CLASS:
res = W_WEP | W_SWAPWEP;
if (objects[otyp].oc_merge)
res |= W_QUIVER;
if (u.twoweap)
res |= W_WEP2 | W_SWAPWEP2;
break;
case TOOL_CLASS:
if (otyp == BLINDFOLD || otyp == TOWEL)
res = W_BLINDFOLD; /* WORN_BLINDF */
else if (is_weptool(obj) || otyp == TIN_OPENER)
res = W_WEP | W_SWAPWEP;
else if (otyp == SADDLE)
res = W_SADDLE;
break;
case FOOD_CLASS:
if (obj->otyp == MEAT_RING)
res = W_RINGL | W_RINGR;
break;
case GEM_CLASS:
res = W_QUIVER;
break;
case BALL_CLASS:
res = W_BALL;
break;
case CHAIN_CLASS:
res = W_CHAIN;
break;
default:
break;
}
return res;
}
void
nonadditive_increase_mon_property(mon, prop_index, amount)
struct monst* mon;
int prop_index;
int amount;
{
set_mon_property(mon, prop_index, max(get_mon_property(mon, prop_index), amount));
}
boolean
nonadditive_increase_mon_property_verbosely(mtmp, prop_index, amount)
struct monst* mtmp;
int prop_index;
int amount;
{
return set_mon_property_verbosely(mtmp, prop_index, max(get_mon_property(mtmp, prop_index), amount));
}
boolean
nonadditive_increase_mon_property_b(mtmp, prop_index, duration, verbose)
struct monst* mtmp;
int prop_index;
int duration;
boolean verbose;
{
if (verbose)
return nonadditive_increase_mon_property_verbosely(mtmp, prop_index, duration);
else
{
nonadditive_increase_mon_property(mtmp, prop_index, duration);
return FALSE;
}
}
void
increase_mon_property(mtmp, prop_index, duration)
struct monst* mtmp;
int prop_index;
int duration;
{
int maxvalue = (int)M_TIMEOUT;
unsigned short value = (unsigned short)max(0, min(maxvalue, (get_mon_property(mtmp, prop_index) + duration)));
set_mon_property(mtmp, prop_index, value);
}
boolean
increase_mon_property_verbosely(mtmp, prop_index, duration)
struct monst* mtmp;
int prop_index;
int duration;
{
int maxvalue = (int)M_TIMEOUT;
unsigned short value = (unsigned short)max(0, min(maxvalue, (get_mon_property(mtmp, prop_index) + duration)));
return set_mon_property_verbosely(mtmp, prop_index, value);
}
boolean
increase_mon_property_b(mtmp, prop_index, duration, verbose)
struct monst* mtmp;
int prop_index;
int duration;
boolean verbose;
{
if (verbose)
return increase_mon_property_verbosely(mtmp, prop_index, duration);
else
{
increase_mon_property(mtmp, prop_index, duration);
return 0;
}
}
STATIC_OVL void
set_mon_temporary_property(mon, prop_index, amount)
struct monst* mon;
int prop_index;
unsigned short amount;
{
if (!mon)
return;
if (prop_index < 1 || prop_index > LAST_PROP)
return;
if (mon == &youmonst)
{
set_itimeout(&u.uprops[prop_index].intrinsic, amount);
refresh_u_tile_gui_info(TRUE);
return;
}
if (amount > M_TIMEOUT)
amount = M_TIMEOUT;
unsigned short otherflags = mon->mprops[prop_index] & ~M_TIMEOUT;
mon->mprops[prop_index] = (amount | otherflags);
}
boolean
set_mon_property_b(mtmp, prop_index, value, verbose)
struct monst* mtmp;
int prop_index;
int value; /* -1 sets the intrinsic and -2 clears it; -3 clears both temporary and permanent instrinsic */
boolean verbose;
{
if (verbose)
return set_mon_property_verbosely(mtmp, prop_index, value);
else
{
set_mon_property(mtmp, prop_index, value);
return FALSE;
}
}
void
set_mon_property(mtmp, prop_index, value)
struct monst* mtmp;
int prop_index;
int value; /* -1 sets the intrinsic and -2 clears it; -3 clears both temporary and permanent instrinsic */
{
if (!mtmp)
return;
if (prop_index < 1 || prop_index > LAST_PROP)
return;
boolean was_tame = is_tame(mtmp);
if (value >= 0)
set_mon_temporary_property(mtmp, prop_index, min((unsigned short)M_TIMEOUT, (unsigned short)value));
else if (value == -1)
mtmp->mprops[prop_index] |= M_INTRINSIC_ACQUIRED;
else if (value == -2)
mtmp->mprops[prop_index] &= ~M_INTRINSIC_ACQUIRED;
else if (value == -3)
{
mtmp->mprops[prop_index] &= ~M_INTRINSIC_ACQUIRED;
set_mon_temporary_property(mtmp, prop_index, 0);
}
/* Adjustments */
if (was_tame && !is_tame(mtmp))
{
newsym(mtmp->mx, mtmp->my);
}
else if (is_tame(mtmp) && !was_tame)
{
newsym(mtmp->mx, mtmp->my);
}
}
int
get_mon_property(mon, prop_index)
struct monst* mon;
int prop_index;
{
if (!mon)
return 0;
if (prop_index < 1 || prop_index > LAST_PROP)
return 0;
if (mon == &youmonst)
{
return (u.uprops[prop_index].intrinsic & TIMEOUT);
}
unsigned short amount = mon->mprops[prop_index] & M_TIMEOUT;
return (int)amount;
}
boolean
set_mon_property_verbosely(mtmp, prop_index, value)
struct monst* mtmp;
int prop_index;
int value; /* -1 sets the intrinsic and -2 clears it; -3 clears both temporary and permanent instrinsic */
{
return verbose_wrapper(VERBOSE_FUNCTION_SET_MON_PROPERTY, mtmp, prop_index, value, FALSE);
}
/* return TRUE if a visible effect (something was printed in pline) */
boolean
verbose_wrapper(function_choice, mtmp, prop_index, value, silently)
enum verbose_function_types function_choice;
struct monst* mtmp;
int prop_index;
int value;
boolean silently;
{
boolean res = FALSE;
/* works for fast, very fast, and slowed */
char savedname[BUFSZ * 2] = "";
Strcpy(savedname, mon_nam(mtmp));
char SavedName[BUFSZ * 2] = "";
Strcpy(SavedName, Monnam(mtmp));
boolean could_spot_mon = canspotmon(mtmp);
boolean was_invisible = is_invisible(mtmp);
boolean was_stoning = is_stoning(mtmp);
boolean was_turning_into_slime = is_turning_into_slime(mtmp);
boolean was_strangled = is_being_strangled(mtmp);
boolean was_suffocating = is_suffocating(mtmp);
boolean was_fast = is_fast(mtmp);
boolean was_very_fast = is_very_fast(mtmp);
boolean was_ultra_fast = is_ultra_fast(mtmp);
boolean was_super_fast = is_super_fast(mtmp);
boolean was_lightning_fast = is_lightning_fast(mtmp);
boolean was_slow = is_slow(mtmp);
boolean was_sleeping = is_sleeping(mtmp);
boolean was_stunned = is_stunned(mtmp);
boolean was_paralyzed = is_paralyzed(mtmp);
boolean was_blinded = is_blinded(mtmp);
boolean was_confused = is_confused(mtmp);
boolean was_hallucinating = is_hallucinating(mtmp);
boolean was_levitating = is_levitating(mtmp);
boolean was_flying = is_flying(mtmp);
boolean was_sick = is_sick(mtmp);
boolean was_mummy_rotted = is_mummy_rotted(mtmp);
boolean was_fearful = is_fearful(mtmp);
boolean was_fleeing = is_fleeing(mtmp);
boolean was_charmed = is_charmed(mtmp);
boolean was_tame = is_tame(mtmp);
boolean was_peaceful = is_peaceful(mtmp);
boolean was_silenced = is_silenced(mtmp);
boolean was_cancelled = is_cancelled(mtmp);
boolean was_crazed = is_crazed(mtmp);
boolean was_heroic = is_heroic(mtmp);
boolean was_super_heroic = is_super_heroic(mtmp);
switch (function_choice)
{
case VERBOSE_FUNCTION_UPDATE_MON_STATISTICS:
update_all_mon_statistics_core(mtmp, silently);
break;
case VERBOSE_FUNCTION_SET_MON_PROPERTY:
set_mon_property(mtmp, prop_index, value);
break;
default:
break;
}
refresh_m_tile_gui_info(mtmp, !silently);
if (silently)
return FALSE;
if (canspotmon(mtmp))
{
if (!could_spot_mon)
{
res = TRUE;
pline_ex(ATR_NONE, CLR_MSG_ATTENTION, "Suddenly, you can see %s!", mon_nam(mtmp));
}
else
{
/* Most such messages here */
if (is_invisible(mtmp) && !was_invisible && knowninvisible(mtmp))
{
res = TRUE;
pline_ex(ATR_NONE, CLR_MSG_ATTENTION, "%s turns transparent!", SavedName);
}
else if (!is_invisible(mtmp) && was_invisible)
{
res = TRUE;
pline_ex(ATR_NONE, CLR_MSG_ATTENTION, "%s body loses its transparency!", s_suffix(Monnam(mtmp)));
}
}
/* Stoned */
if (is_stoning(mtmp) && !was_stoning)
{
res = TRUE;
pline_ex(ATR_NONE, is_tame(mtmp) ? CLR_MSG_NEGATIVE : CLR_MSG_ATTENTION, "%s starts turning into stone!", Monnam(mtmp));
}
else if (!is_stoning(mtmp) && was_stoning)
{
res = TRUE;
pline_ex(ATR_NONE, is_tame(mtmp) ? CLR_MSG_POSITIVE : CLR_MSG_ATTENTION, "%s stops turning into stone.", Monnam(mtmp));
}
/* Slimed */
if (is_turning_into_slime(mtmp) && !was_turning_into_slime)
{
res = TRUE;
pline_ex(ATR_NONE, is_tame(mtmp) ? CLR_MSG_NEGATIVE : CLR_MSG_ATTENTION, "%s is turning into green slime!", Monnam(mtmp));
}
else if (!is_turning_into_slime(mtmp) && was_turning_into_slime)
{
res = TRUE;
pline_ex(ATR_NONE, is_tame(mtmp) ? CLR_MSG_POSITIVE : CLR_MSG_ATTENTION, "%s is not turning into green slime anymore.", Monnam(mtmp));
}
/* Speed */
if (
(!is_slow(mtmp) && was_slow)
)
{
res = TRUE;
pline_ex(ATR_NONE, is_tame(mtmp) ? CLR_MSG_POSITIVE : is_peaceful(mtmp) ? CLR_MSG_ATTENTION : CLR_MSG_WARNING,
"%s is moving %sfaster.", Monnam(mtmp),
is_fast(mtmp) || is_very_fast(mtmp) || is_ultra_fast(mtmp) || is_super_fast(mtmp) || is_lightning_fast(mtmp) ? "much " : "");
}
else if (
(is_fast(mtmp) && !was_fast && !was_very_fast && !was_ultra_fast && !was_super_fast && !was_lightning_fast)
|| (is_very_fast(mtmp) && !was_very_fast && !was_ultra_fast && !was_super_fast && !was_lightning_fast)
|| (is_ultra_fast(mtmp) && !was_ultra_fast && !was_super_fast && !was_lightning_fast)
|| (is_super_fast(mtmp) && !was_super_fast && !was_lightning_fast)
|| (is_lightning_fast(mtmp) && !was_lightning_fast)
)
{
res = TRUE;
pline_ex(ATR_NONE, is_tame(mtmp) ? CLR_MSG_POSITIVE : is_peaceful(mtmp) ? CLR_MSG_ATTENTION : CLR_MSG_WARNING,
"%s is moving faster.", Monnam(mtmp));
}
else if (
(!is_fast(mtmp) && !is_very_fast(mtmp) && !is_ultra_fast(mtmp) && !is_super_fast(mtmp) && !is_lightning_fast(mtmp) && (was_fast || was_very_fast || was_ultra_fast || was_super_fast || was_lightning_fast))
|| (!is_very_fast(mtmp) && !is_ultra_fast(mtmp) && !is_super_fast(mtmp) && !is_lightning_fast(mtmp) && (was_very_fast || was_ultra_fast || was_super_fast || was_lightning_fast))
|| (!is_ultra_fast(mtmp) && !is_super_fast(mtmp) && !is_lightning_fast(mtmp) && (was_ultra_fast || was_super_fast || was_lightning_fast))
|| (!is_super_fast(mtmp) && !is_lightning_fast(mtmp) && (was_super_fast || was_lightning_fast))
|| (!is_lightning_fast(mtmp) && (was_lightning_fast))
)
{
res = TRUE;
pline_ex(ATR_NONE, CLR_MSG_ATTENTION, "%s is moving slower.", Monnam(mtmp));
}
else if (is_slow(mtmp) && !was_slow)
{
res = TRUE;
if ((prop_index == STONED || prop_index == SLIMED) && value > 0)
pline_ex(ATR_NONE, is_tame(mtmp) ? CLR_MSG_WARNING : CLR_MSG_ATTENTION, "%s is slowing down!", Monnam(mtmp));
else if (prop_index == SLOWED && value > 0)
pline_ex(ATR_NONE, CLR_MSG_ATTENTION, "%s slows down%s.", Monnam(mtmp), was_fast || was_very_fast ? " a lot" : "");
else
pline_ex(ATR_NONE, CLR_MSG_ATTENTION, "%s is moving %sslower.", Monnam(mtmp), was_fast || was_very_fast ? "much " : "");
}
/* Silenced */
if (is_silenced(mtmp) && !was_silenced)
{
res = TRUE;
pline_ex(ATR_NONE, CLR_MSG_ATTENTION, "%s voice disappears.", s_suffix(Monnam(mtmp)));
}
else if (!is_silenced(mtmp) && was_silenced)
{
res = TRUE;
pline_ex(ATR_NONE, CLR_MSG_ATTENTION, "%s voice returns.", s_suffix(Monnam(mtmp)));
}
/* Cancellation */
if (is_cancelled(mtmp) && !was_cancelled)
{
res = TRUE;
pline_ex(ATR_NONE, CLR_MSG_ATTENTION, "%s magic seems to stop flowing properly.", s_suffix(Monnam(mtmp)));
}
else if (!is_cancelled(mtmp) && was_cancelled)
{
res = TRUE;
pline_ex(ATR_NONE, CLR_MSG_ATTENTION, "%s magic seems to start flowing properly.", s_suffix(Monnam(mtmp)));
}
/* Crazedness */
if (is_crazed(mtmp) && !was_crazed)
{
res = TRUE;
pline_ex(ATR_NONE, CLR_MSG_WARNING, "%s looks crazed.", Monnam(mtmp));
}
else if (!is_crazed(mtmp) && was_crazed)
{
res = TRUE;
pline_ex(ATR_NONE, is_tame(mtmp) ? CLR_MSG_POSITIVE : CLR_MSG_ATTENTION, "%s looks more sane.", Monnam(mtmp));
}
/* Heroism */
if (is_super_heroic(mtmp) && !was_super_heroic)
{
res = TRUE;
pline_ex(ATR_NONE, is_tame(mtmp) ? CLR_MSG_POSITIVE : CLR_MSG_WARNING, "%s looks super-heroic.", Monnam(mtmp));
}
else if (!is_super_heroic(mtmp) && was_super_heroic)
{
res = TRUE;
pline_ex(ATR_NONE, CLR_MSG_ATTENTION, "%s looks less super-heroic than before.", Monnam(mtmp));
}
else if (!is_heroic(mtmp) && !is_super_heroic(mtmp) && was_heroic)
{
res = TRUE;
pline_ex(ATR_NONE, CLR_MSG_ATTENTION, "%s looks less heroic than before.", Monnam(mtmp));
}
else if (is_heroic(mtmp) && !was_heroic && !was_super_heroic && !is_super_heroic(mtmp))
{
res = TRUE;
pline_ex(ATR_NONE, is_tame(mtmp) ? CLR_MSG_POSITIVE : CLR_MSG_WARNING, "%s looks heroic.", Monnam(mtmp));
}
/* Sleeping */
if (is_sleeping(mtmp) && !was_sleeping)
{
res = TRUE;
pline_ex(ATR_NONE, is_tame(mtmp) ? CLR_MSG_WARNING : CLR_MSG_ATTENTION, "%s falls asleep.", Monnam(mtmp));
}
else if (!is_sleeping(mtmp) && was_sleeping)
{
res = TRUE;
pline_ex(ATR_NONE, CLR_MSG_ATTENTION, "%s wakes up.", Monnam(mtmp));
}
/* Paralysis */
if (is_paralyzed(mtmp) && !was_paralyzed)
{
res = TRUE;
pline_ex(ATR_NONE, is_tame(mtmp) ? CLR_MSG_NEGATIVE : CLR_MSG_ATTENTION, "%s is paralyzed!", Monnam(mtmp));
}
else if (!is_paralyzed(mtmp) && was_paralyzed)
{
res = TRUE;
if (mon_can_move(mtmp))
pline_ex(ATR_NONE, is_tame(mtmp) ? CLR_MSG_POSITIVE : CLR_MSG_ATTENTION, "%s can move again!", Monnam(mtmp));
else
pline_ex(ATR_NONE, CLR_MSG_ATTENTION, "%s is no longer paralyzed!", Monnam(mtmp));
}
/* Blindness */
if (is_blinded(mtmp) && !was_blinded)
{
res = TRUE;
pline_ex(ATR_NONE, is_tame(mtmp) ? CLR_MSG_WARNING : CLR_MSG_ATTENTION, "%s is blinded!", Monnam(mtmp));
}
else if (!has_blinded(mtmp) && was_blinded)
{
res = TRUE;
pline_ex(ATR_NONE, is_tame(mtmp) ? CLR_MSG_POSITIVE : CLR_MSG_ATTENTION, "%s can see again!", Monnam(mtmp));
}
/* Stunned */
if (is_stunned(mtmp) && !was_stunned)
{
res = TRUE;
pline_ex(ATR_NONE, is_tame(mtmp) ? CLR_MSG_NEGATIVE : CLR_MSG_ATTENTION, "%s is stunned!", Monnam(mtmp));
}
else if (!is_stunned(mtmp) && was_stunned)
{
res = TRUE;
pline_ex(ATR_NONE, is_tame(mtmp) ? CLR_MSG_POSITIVE : CLR_MSG_ATTENTION, "%s looks less stunned.", Monnam(mtmp));
}
/* Confusion */
if (is_confused(mtmp) && !was_confused)
{
res = TRUE;
pline_ex(ATR_NONE, is_tame(mtmp) ? CLR_MSG_WARNING : CLR_MSG_ATTENTION, "%s is confused!", Monnam(mtmp));
}
else if (!is_confused(mtmp) && was_confused)
{
res = TRUE;
pline_ex(ATR_NONE, is_tame(mtmp) ? CLR_MSG_POSITIVE : CLR_MSG_ATTENTION, "%s looks less confused.", Monnam(mtmp));
}
/* Hallucination */
if (is_hallucinating(mtmp) && !was_hallucinating)
{
res = TRUE;
pline_ex(ATR_NONE, is_tame(mtmp) ? CLR_MSG_NEGATIVE : CLR_MSG_ATTENTION, "%s looks seriously confused!", Monnam(mtmp));
}
else if (!is_hallucinating(mtmp) && was_hallucinating)
{
res = TRUE;
pline_ex(ATR_NONE, is_tame(mtmp) ? CLR_MSG_POSITIVE : CLR_MSG_ATTENTION, "%s looks more straight-minded.", Monnam(mtmp));
}
/* Fearful*/
if (is_fleeing(mtmp) && !was_fleeing)
{
if (M_AP_TYPE(mtmp) != M_AP_FURNITURE && M_AP_TYPE(mtmp) != M_AP_OBJECT)
{
res = TRUE;
if (!mon_can_move(mtmp) || !mtmp->data->mmove)
pline_ex(ATR_NONE, CLR_MSG_ATTENTION, "%s looks frightened.", Monnam(mtmp));
else
pline_ex(ATR_NONE, CLR_MSG_ATTENTION, "%s %sturns to flee.", Monnam(mtmp), is_fearful(mtmp) ? "looks frightened and " : "");
}
}
else if (is_fearful(mtmp) && !was_fearful && was_fleeing)
{
res = TRUE;
pline_ex(ATR_NONE, CLR_MSG_ATTENTION, "%s looks even more frightened than before.", Monnam(mtmp));
}
else if (!is_fleeing(mtmp) && was_fleeing)
{
res = TRUE;
pline_ex(ATR_NONE, CLR_MSG_ATTENTION, "%s %sstops fleeing.", Monnam(mtmp), !is_fearful(mtmp) && was_fearful ? "looks less frightened and " : "");
}
/* Charm */
if (is_charmed(mtmp) && !was_charmed)
{
res = TRUE;
pline("%s is charmed!", Monnam(mtmp));
if (is_tame(mtmp) && !was_tame)
pline_ex(ATR_NONE, CLR_MSG_POSITIVE, "%s looks friendly.", Monnam(mtmp));
else
pline_ex(ATR_NONE, CLR_MSG_WARNING, "%s looks %s for a while.", Monnam(mtmp), is_tame(mtmp) ? "a little perplexed" :
is_peaceful(mtmp) ? "a little uncomfortable" : "uncomfortable");
}
if (!is_charmed(mtmp) && was_charmed)
{
res = TRUE;
if (is_tame(mtmp))
pline_ex(ATR_NONE, CLR_MSG_ATTENTION, "%s looks perplexed for a while.", Monnam(mtmp));
else
pline_ex(ATR_NONE, CLR_MSG_WARNING, "%s looks more in control of %sself.", Monnam(mtmp), mhim(mtmp));
if (!is_peaceful(mtmp) && was_peaceful)
pline_ex(ATR_NONE, CLR_MSG_WARNING, "%s turns hostile!", Monnam(mtmp));
}
/* Levitation */
if (is_levitating(mtmp) && !was_levitating)
{
res = TRUE;
pline_ex(ATR_NONE, CLR_MSG_ATTENTION, "%s starts levitating.", Monnam(mtmp));
}
else if (!is_levitating(mtmp) && was_levitating)
{
res = TRUE;
pline_ex(ATR_NONE, CLR_MSG_ATTENTION, "%s stops levitating.", Monnam(mtmp));
}
/* Flying */
if (is_flying(mtmp) && !was_flying)
{
res = TRUE;
pline_ex(ATR_NONE, CLR_MSG_ATTENTION, "%s starts flying.", Monnam(mtmp));
}
else if (!is_flying(mtmp) && was_flying)
{
res = TRUE;
pline_ex(ATR_NONE, CLR_MSG_ATTENTION, "%s stops flying.", Monnam(mtmp));
}
if (is_being_strangled(mtmp) && !was_strangled)
{
res = TRUE;
pline_ex(ATR_NONE, is_tame(mtmp) ? CLR_MSG_NEGATIVE : CLR_MSG_ATTENTION, "%s is being strangled to death!", Monnam(mtmp));
}
else if (!is_being_strangled(mtmp) && was_strangled)
{
res = TRUE;
pline_ex(ATR_NONE, is_tame(mtmp) ? CLR_MSG_POSITIVE : CLR_MSG_ATTENTION, "%s stops being strangled.", Monnam(mtmp));
}
if (is_suffocating(mtmp) && !was_suffocating)
{
res = TRUE;
pline_ex(ATR_NONE, is_tame(mtmp) ? CLR_MSG_NEGATIVE : CLR_MSG_ATTENTION, "%s is suffocating!", Monnam(mtmp));
}
else if (!is_suffocating(mtmp) && was_suffocating)
{
res = TRUE;
pline_ex(ATR_NONE, is_tame(mtmp) ? CLR_MSG_POSITIVE : CLR_MSG_ATTENTION, "%s stops being suffocated.", Monnam(mtmp));
}
if (is_sick(mtmp) && !was_sick)
{
res = TRUE;
pline_ex(ATR_NONE, is_tame(mtmp) ? CLR_MSG_NEGATIVE : CLR_MSG_ATTENTION, "%s looks terminally ill!", Monnam(mtmp));
}
else if (!is_sick(mtmp) && was_sick)
{
res = TRUE;
pline_ex(ATR_NONE, is_tame(mtmp) ? CLR_MSG_POSITIVE : CLR_MSG_ATTENTION, "%s is cured of %s terminal illness.", Monnam(mtmp), mhis(mtmp));
}
if (is_mummy_rotted(mtmp) && !was_mummy_rotted)
{
res = TRUE;
pline_ex(ATR_NONE, is_tame(mtmp) ? CLR_MSG_NEGATIVE : CLR_MSG_ATTENTION, "%s looks severely ill!", Monnam(mtmp));
}
else if (!is_mummy_rotted(mtmp) && was_mummy_rotted)
{
res = TRUE;
pline_ex(ATR_NONE, is_tame(mtmp) ? CLR_MSG_POSITIVE : CLR_MSG_ATTENTION, "%s is cured of %s rot-causing illness.", Monnam(mtmp), mhis(mtmp));
}
/* Cancelled */
/* Half magic resistance */
/* No magic resistance */
/* Summoning is forbidden */
/* Deaf */
/* Sick */
/* Vomiting */
/* Glib */
}
else if (could_spot_mon)
{
res = TRUE;
pline_ex(ATR_NONE, CLR_MSG_ATTENTION, "Suddenly, you cannot see %s anymore!", savedname);
}
if (res)
{
newsym(mtmp->mx, mtmp->my);
flush_screen(1); /* Make sure you see the change immediately */
}
return res;
}
void
update_all_mon_statistics_core(mon, silently)
struct monst* mon;
boolean silently;
{
update_mon_extrinsics(mon, silently);
update_mon_abon(mon);
/* monster do not currently have mana */
update_mon_maxhp(mon);
}
void
update_all_mon_statistics(mon, silently)
struct monst* mon;
boolean silently;
{
(void)verbose_wrapper(VERBOSE_FUNCTION_UPDATE_MON_STATISTICS, mon, 0, 0, silently);
}
/* armor put on or taken off; might be magical variety */
void
update_mon_extrinsics(mon, silently)
struct monst *mon;
boolean silently;
{
if (!mon)
return;
int unseen = 0;
struct obj *otmp = (struct obj*)0;
boolean was_tame = is_tame(mon);
/* clear mon extrinsics */
for (int i = 1; i <= LAST_PROP; i++)
{
mon->mprops[i] &= ~M_EXTRINSIC;
}
/* add them all back*/
for (otmp = mon->minvent; otmp; otmp = otmp->nobj)
{
for (int i = 1; i <= 9; i++)
{
if (!otmp->oartifact && i >= 6)
break;
int otyp = otmp->otyp;
uchar which = 0;
boolean inappr = inappropriate_monster_character_type(mon, otmp);
boolean yields_power = FALSE;
boolean wornrequired = TRUE;
switch (i)
{
case 1:
which = objects[otyp].oc_oprop;
if (objects[otyp].oc_pflags & P1_POWER_1_APPLIES_TO_ALL_CHARACTERS)
yields_power = TRUE;
else if (inappr && (objects[otyp].oc_pflags & P1_POWER_1_APPLIES_TO_INAPPROPRIATE_CHARACTERS_ONLY))
yields_power = TRUE;
else if (!inappr && !(objects[otyp].oc_pflags & P1_POWER_1_APPLIES_TO_INAPPROPRIATE_CHARACTERS_ONLY))
yields_power = TRUE;
if (objects[otyp].oc_pflags & P1_POWER_1_APPLIES_WHEN_CARRIED)
wornrequired = FALSE;
break;
case 2:
which = objects[otyp].oc_oprop2;
if (objects[otyp].oc_pflags & P1_POWER_2_APPLIES_TO_ALL_CHARACTERS)
yields_power = TRUE;
else if (inappr && (objects[otyp].oc_pflags & P1_POWER_2_APPLIES_TO_INAPPROPRIATE_CHARACTERS_ONLY))
yields_power = TRUE;
else if (!inappr && !(objects[otyp].oc_pflags & P1_POWER_2_APPLIES_TO_INAPPROPRIATE_CHARACTERS_ONLY))
yields_power = TRUE;
if (objects[otyp].oc_pflags & P1_POWER_2_APPLIES_WHEN_CARRIED)
wornrequired = FALSE;
break;
case 3:
which = objects[otyp].oc_oprop3;
if (objects[otyp].oc_pflags & P1_POWER_3_APPLIES_TO_ALL_CHARACTERS)
yields_power = TRUE;
else if (inappr && (objects[otyp].oc_pflags & P1_POWER_3_APPLIES_TO_INAPPROPRIATE_CHARACTERS_ONLY))
yields_power = TRUE;
else if (!inappr && !(objects[otyp].oc_pflags & P1_POWER_3_APPLIES_TO_INAPPROPRIATE_CHARACTERS_ONLY))
yields_power = TRUE;
if (objects[otyp].oc_pflags & P1_POWER_3_APPLIES_WHEN_CARRIED)
wornrequired = FALSE;
break;
case 4:
case 5:
yields_power = FALSE; /* Set them separately below */
if (otmp->owornmask)
{
/* Mythic */
boolean isprefix = (i == 4);
uchar mythic_quality = (isprefix ? otmp->mythic_prefix : otmp->mythic_suffix);
if (mythic_quality == 0)
continue;
const struct mythic_power_definition* mythic_powers = (isprefix ? mythic_prefix_powers : mythic_suffix_powers);
const struct mythic_definition* mythic_definitions = (isprefix ? mythic_prefix_qualities : mythic_suffix_qualities);
uchar max_mythic_powers = (isprefix ? (uchar)MAX_MYTHIC_PREFIX_POWERS : (uchar)MAX_MYTHIC_SUFFIX_POWERS);
for (uchar k = 0; k < max_mythic_powers; k++)
{
if (!mythic_powers[k].name)
break;
uint64_t mythic_power_bit = (uint64_t)1 << ((uint64_t)k);
if ((mythic_definitions[mythic_quality].mythic_powers & mythic_power_bit) && mythic_power_applies_to_obj(otmp, mythic_powers[k].power_flags))
{
if (mythic_powers[k].power_type == MYTHIC_POWER_TYPE_CONFERS_PROPERTY)
{
mon->mprops[mythic_powers[k].parameter1] |= M_EXTRINSIC;
}
}
}
}
break;
case 6: /* Artifact carried */
if (otmp->oartifact)
{
which = artilist[otmp->oartifact].carried_prop;
wornrequired = FALSE;
yields_power = TRUE;
}
break;
case 7: /* Artifact worn */
if (otmp->oartifact)
{
which = artilist[otmp->oartifact].worn_prop;
wornrequired = TRUE;
yields_power = TRUE;
}
break;
case 8: /* Artifact invoked */
if (otmp->oartifact)
{
which = otmp->invokeon && artilist[otmp->oartifact].inv_prop > 0 ? artilist[otmp->oartifact].inv_prop : 0;
wornrequired = FALSE;
yields_power = TRUE;
}
break;
case 9: /* Artifact spfx and cspfx */
yields_power = FALSE; /* Handled separately below */
if (otmp->oartifact)
{
int k;
if (otmp->owornmask)
{
for (k = 0; k < 32; k++)
{
uint64_t bit = (uint64_t)1 << k;
int propnum = spfx_to_prop(bit);
if (artilist[otmp->oartifact].spfx & bit)
mon->mprops[propnum] |= M_EXTRINSIC;
}
}
for (k = 0; k < 32; k++)
{
uint64_t bit = (uint64_t)1 << k;
int propnum = spfx_to_prop(bit);
if (artilist[otmp->oartifact].cspfx & bit)
mon->mprops[propnum] |= M_EXTRINSIC;
}
}
break;
default:
break;
}
if (yields_power && (!wornrequired || (wornrequired && otmp->owornmask)))
{
/* OK */
}
else
{
continue;
}
unseen = !canseemon(mon);
mon->mprops[which] |= M_EXTRINSIC;
}
}
if (mon->wormno)
see_wsegs(mon); /* and any tail too */
/* if couldn't see it but now can, or vice versa, update display */
if (!silently && (unseen ^ !canseemon(mon)))
newsym(mon->mx, mon->my);
/* Adjustments */
if (was_tame && !is_tame(mon))
{
newsym(mon->mx, mon->my);
}
else if (is_tame(mon) && !was_tame)
{
newsym(mon->mx, mon->my);
}
}
int
find_mac(mon)
register struct monst *mon;
{
register struct obj *obj;
int natural_ac_base = mon->data->ac;
int natural_ac = natural_ac_base;
int armor_bonus = 0;
int armor_ac = 10;
int mac = 0;
int64_t mwflags = mon->worn_item_flags;
for (obj = mon->minvent; obj; obj = obj->nobj) {
if (obj->owornmask & mwflags)
armor_bonus += ARM_AC_BONUS(obj, mon->data);
/* since ARM_AC_BONUS is positive, subtracting it increases AC */
}
natural_ac -= armor_bonus / 3;
armor_ac -= (armor_bonus + ((10 - natural_ac_base) / 3));
if (natural_ac <= armor_ac)
mac = natural_ac;
else
mac = armor_ac;
//DEX bonus for monsters, reduce the number from AC; not add!
if(mon_can_move(mon))
mac -= dexterity_ac_bonus(m_acurr(mon, A_DEX));
mac -= mon->macbonus;
if (mon->mprops[MAGICAL_STONESKIN])
mac -= MAGICAL_STONESKIN_AC_BONUS;
else if (mon->mprops[MAGICAL_BARKSKIN])
mac -= MAGICAL_BARKSKIN_AC_BONUS;
else if (mon->mprops[MAGICAL_SHIELDING])
mac -= MAGICAL_SHIELDING_AC_BONUS;
else if (mon->mprops[MAGICAL_PROTECTION])
mac -= MAGICAL_PROTECTION_AC_BONUS;
return mac;
}
/*
* weapons are handled separately;
* rings and eyewear aren't used by monsters
*/
/* Wear the best object of each type that the monster has. During creation,
* the monster can put everything on at once; otherwise, wearing takes time.
* This doesn't affect monster searching for objects--a monster may very well
* search for objects it would not want to wear, because we don't want to
* check which_armor() each round.
*
* We'll let monsters put on shirts and/or suits under worn cloaks, but
* not shirts under worn suits. This is somewhat arbitrary, but it's
* too tedious to have them remove and later replace outer garments,
* and preventing suits under cloaks makes it a little bit too easy for
* players to influence what gets worn. Putting on a shirt underneath
* already worn body armor is too obviously buggy...
*/
void
m_dowear(mon, creation, commanded)
register struct monst *mon;
boolean creation, commanded;
{
#define RACE_EXCEPTION TRUE
/* Note the restrictions here are the same as in dowear in do_wear.c
* except for the additional restriction on intelligence. (Players
* are always intelligent, even if polymorphed).
*/
if (!can_wear_objects(mon->data))
return;
if (mon->mfrozen)
return;
/* give mummies a chance to wear their wrappings
* and let skeletons wear their initial armor */
if (mindless(mon->data) && (!creation && !commanded)) // !(mon->data->mlet == S_GREATER_UNDEAD || mon->data->mlet == S_LESSER_UNDEAD)))
return;
boolean wears_shirt = FALSE;
boolean wears_suit = FALSE;
boolean wears_robe = FALSE;
boolean wears_cloak = FALSE;
boolean wears_gloves = FALSE;
boolean wears_helmet = FALSE;
boolean wears_bracers = FALSE;
boolean wears_boots = FALSE;
boolean wears_shield = FALSE;
boolean wears_amulet = FALSE;
boolean wears_ringr = FALSE;
boolean wears_ringl = FALSE;
boolean wears_misc1 = FALSE;
struct obj* old_shirt = which_armor(mon, W_ARMU);
struct obj* old_suit = which_armor(mon, W_ARM);
struct obj* old_robe = which_armor(mon, W_ARMO);
struct obj* old_cloak = which_armor(mon, W_ARMC);
struct obj* old_gloves = which_armor(mon, W_ARMG);
struct obj* old_helmet = which_armor(mon, W_ARMH);
struct obj* old_bracers = which_armor(mon, W_ARMB);
struct obj* old_boots = which_armor(mon, W_ARMF);
struct obj* old_shield = which_armor(mon, W_ARMS);
struct obj* old_amulet = which_armor(mon, W_AMUL);
struct obj* old_ringr = which_armor(mon, W_RINGR);
struct obj* old_ringl = which_armor(mon, W_RINGL);
struct obj* old_misc1 = which_armor(mon, W_MISC);
int old_shirt_delay = old_shirt ? objects[old_shirt->otyp].oc_delay : 0;
int old_suit_delay = old_suit ? objects[old_suit->otyp].oc_delay : 0;
int old_robe_delay = old_robe ? objects[old_robe->otyp].oc_delay : 0;
int old_cloak_delay = old_cloak ? objects[old_cloak->otyp].oc_delay : 0;
int old_gloves_delay = old_gloves ? objects[old_gloves->otyp].oc_delay : 0;
int old_helmet_delay = old_helmet ? objects[old_helmet->otyp].oc_delay : 0;
int old_bracers_delay = old_bracers ? objects[old_bracers->otyp].oc_delay : 0;
int old_boots_delay = old_boots ? objects[old_boots->otyp].oc_delay : 0;
int old_shield_delay = old_shield ? objects[old_shield->otyp].oc_delay : 0;
int old_amulet_delay = old_amulet ? objects[old_amulet->otyp].oc_delay : 0;
int old_ringr_delay = old_ringr ? objects[old_ringr->otyp].oc_delay : 0;
int old_ringl_delay = old_ringl ? objects[old_ringl->otyp].oc_delay : 0;
int old_misc1_delay = old_misc1 ? objects[old_misc1->otyp].oc_delay : 0;
/* Main armor */
if (can_wear_shirt(mon->data) && (cursed_items_are_positive_mon(mon) || !((old_cloak && old_cloak->cursed) || (old_robe && old_robe->cursed) || (old_suit && old_suit->cursed))) )
{
wears_shirt = m_dowear_type(mon, W_ARMU, creation, FALSE);
}
if (can_wear_suit(mon->data) && (cursed_items_are_positive_mon(mon) || !((old_cloak && old_cloak->cursed) || (old_robe && old_robe->cursed))) )
wears_suit = m_dowear_type(mon, W_ARM, creation, FALSE);
else
wears_suit = m_dowear_type(mon, W_ARM, creation, RACE_EXCEPTION);
if (can_wear_robe(mon->data) && (cursed_items_are_positive_mon(mon) || !(old_cloak && old_cloak->cursed)))
{
wears_robe = m_dowear_type(mon, W_ARMO, creation, FALSE);
}
if (can_wear_cloak(mon->data))
{
wears_cloak = m_dowear_type(mon, W_ARMC, creation, FALSE);
}
/* Other armor types */
if (can_wear_helmet(mon->data))
wears_helmet = m_dowear_type(mon, W_ARMH, creation, FALSE);
if (can_wear_shield(mon->data) && (!MON_WEP(mon) || !bimanual(MON_WEP(mon))))
wears_shield = m_dowear_type(mon, W_ARMS, creation, FALSE);
if (can_wear_gloves(mon->data) && !(MON_WEP(mon) && mwelded(MON_WEP(mon), mon)))
wears_gloves = m_dowear_type(mon, W_ARMG, creation, FALSE);
if (can_wear_boots(mon->data))
wears_boots = m_dowear_type(mon, W_ARMF, creation, FALSE);
if (can_wear_bracers(mon->data))
wears_bracers = m_dowear_type(mon, W_ARMB, creation, FALSE);
/* Accessories */
if (can_wear_amulet(mon->data))
wears_amulet = m_dowear_type(mon, W_AMUL, creation, FALSE);
if (can_wear_rings(mon->data) && (cursed_items_are_positive_mon(mon) || (!(MON_WEP(mon) && mwelded(MON_WEP(mon), mon)) && !(old_gloves && old_gloves->cursed))))
{
wears_ringr = m_dowear_type(mon, W_RINGR, creation, FALSE);
wears_ringl = m_dowear_type(mon, W_RINGL, creation, FALSE);
}
/* Always check miscellaneous */
wears_misc1 = m_dowear_type(mon, W_MISC, creation, FALSE);
update_all_mon_statistics(mon, creation);
struct obj* new_shirt = which_armor(mon, W_ARMU);
struct obj* new_suit = which_armor(mon, W_ARM);
struct obj* new_robe = which_armor(mon, W_ARMO);
struct obj* new_cloak = which_armor(mon, W_ARMC);
struct obj* new_gloves = which_armor(mon, W_ARMG);
struct obj* new_helmet = which_armor(mon, W_ARMH);
struct obj* new_bracers = which_armor(mon, W_ARMB);
struct obj* new_boots = which_armor(mon, W_ARMF);
struct obj* new_shield = which_armor(mon, W_ARMS);
struct obj* new_amulet = which_armor(mon, W_AMUL);
struct obj* new_ringr = which_armor(mon, W_RINGR);
struct obj* new_ringl = which_armor(mon, W_RINGL);
struct obj* new_misc1 = which_armor(mon, W_MISC);
int new_shirt_delay = new_shirt ? objects[new_shirt->otyp].oc_delay : 0;
int new_suit_delay = new_suit ? objects[new_suit->otyp].oc_delay : 0;
int new_robe_delay = new_robe ? objects[new_robe->otyp].oc_delay : 0;
int new_cloak_delay = new_cloak ? objects[new_cloak->otyp].oc_delay : 0;
int new_gloves_delay = new_gloves ? objects[new_gloves->otyp].oc_delay : 0;
int new_helmet_delay = new_helmet ? objects[new_helmet->otyp].oc_delay : 0;
int new_bracers_delay = new_bracers ? objects[new_bracers->otyp].oc_delay : 0;
int new_boots_delay = new_boots ? objects[new_boots->otyp].oc_delay : 0;
int new_shield_delay = new_shield ? objects[new_shield->otyp].oc_delay : 0;
int new_amulet_delay = new_amulet ? objects[new_amulet->otyp].oc_delay : 0;
int new_ringr_delay = new_ringr ? objects[new_ringr->otyp].oc_delay : 0;
int new_ringl_delay = new_ringl ? objects[new_ringl->otyp].oc_delay : 0;
int new_misc1_delay = new_misc1 ? objects[new_misc1->otyp].oc_delay : 0;
boolean takes_off_old_suit = wears_shirt || wears_suit;
boolean takes_off_old_robe = wears_shirt || wears_suit || wears_robe;
boolean takes_off_old_cloak = wears_shirt || wears_suit || wears_robe || wears_cloak;
int totaldelay = 0;
totaldelay += takes_off_old_cloak ? old_cloak_delay : 0;
totaldelay += takes_off_old_robe ? old_robe_delay : 0;
totaldelay += takes_off_old_suit ? old_suit_delay : 0;
totaldelay += wears_shirt ? old_shirt_delay + new_shirt_delay : 0;
totaldelay += wears_suit ? new_suit_delay : 0;
totaldelay += wears_robe ? new_robe_delay : 0;
totaldelay += wears_cloak ? new_cloak_delay : 0;
totaldelay += wears_gloves ? old_gloves_delay + new_gloves_delay : 0;
totaldelay += wears_helmet ? old_helmet_delay + new_helmet_delay : 0;
totaldelay += wears_bracers ? old_bracers_delay + new_bracers_delay : 0;
totaldelay += wears_boots ? old_boots_delay + new_boots_delay : 0;
totaldelay += wears_shield ? old_shield_delay + new_shield_delay : 0;
totaldelay += wears_amulet ? old_amulet_delay + new_amulet_delay : 0;
totaldelay += wears_ringl ? old_ringl_delay + new_ringl_delay : 0;
totaldelay += wears_ringr ? old_ringr_delay + new_ringr_delay : 0;
totaldelay += wears_misc1 ? old_misc1_delay + new_misc1_delay : 0;
mon->mfrozen = totaldelay;
if (mon->mfrozen)
mon->mcanmove = 0;
}
/* 0 if nothing happened, TRUE if new was worn (and old consequently removed, if any) */
STATIC_OVL boolean
m_dowear_type(mon, flag, creation, racialexception)
struct monst *mon;
int64_t flag;
boolean creation;
boolean racialexception;
{
struct obj *old, *best, *obj;
int unseen = !canseemon(mon);
boolean ispeaceful = is_peaceful(mon);
boolean autocurse;
char nambuf[BUFSZ];
if (mon->mfrozen)
return 0; /* probably putting previous item on */
/* Get a copy of monster's name before altering its visibility */
Strcpy(nambuf, See_invisible ? Monnam(mon) : mon_nam(mon));
old = which_armor(mon, flag);
if (old && old->cursed && !cursed_items_are_positive_mon(mon))
return 0;
if (old && flag == W_AMUL)
return 0; /* no such thing as better amulets */
if (old && flag == W_RINGL)
return 0; /* no such thing as better rings */
if (old && flag == W_RINGR)
return 0; /* no such thing as better rings */
if (old && flag == W_MISC)
return 0; /* no such thing as better misc items */
best = old;
for (obj = mon->minvent; obj; obj = obj->nobj)
{
if (ispeaceful && (obj->speflags & SPEFLAGS_INTENDED_FOR_SALE) != 0)
continue;
switch (flag)
{
case W_AMUL:
if (obj->oclass != AMULET_CLASS
|| (obj->otyp != AMULET_OF_LIFE_SAVING && obj->otyp != AMULET_VERSUS_PETRIFICATION && obj->otyp != AMULET_OF_UNCHANGING
&& obj->otyp != AMULET_VERSUS_POISON && obj->otyp != AMULET_VERSUS_UNDEATH
&& obj->otyp != AMULET_OF_REFLECTION))
continue;
best = obj;
goto outer_break; /* no such thing as better amulets */
case W_RINGR:
case W_RINGL:
if (obj->oclass != RING_CLASS || (is_priest(mon->data) && obj->cursed) || is_cursed_magic_item(obj) || (obj->owornmask && obj->owornmask != flag))
continue;
best = obj;
goto outer_break; /* no such thing as better rings */
case W_MISC:
if (!can_wear_miscellaneous(mon->data, obj->otyp))
continue;
if (obj->oclass != MISCELLANEOUS_CLASS || (is_priest(mon->data) && obj->cursed) || is_cursed_magic_item(obj) || (obj->owornmask && obj->owornmask != flag))
continue;
if (objects[obj->otyp].oc_subtyp != MISC_BELT && !likes_magic(mon->data) && !(mon->mnum == PM_MINOTAUR && objects[obj->otyp].oc_subtyp == MISC_NOSERING))
continue;
best = obj;
goto outer_break; /* no such thing as better misc items */
case W_ARMU:
if (!is_shirt(obj))
continue;
break;
case W_ARMC:
if (!is_cloak(obj))
continue;
break;
case W_ARMH:
if (!is_helmet(obj))
continue;
/* changing alignment is not implemented for monsters;
priests and minions could change alignment but wouldn't
want to, so they reject helms of opposite alignment */
if (obj->otyp == HELM_OF_OPPOSITE_ALIGNMENT
&& (mon->ispriest || mon->isminion))
continue;
/* (flimsy exception matches polyself handling) */
if (has_horns(mon->data) && !is_flimsy(obj))
continue;
break;
case W_ARMS:
if (!is_shield(obj))
continue;
break;
case W_ARMG:
if (!is_gloves(obj))
continue;
break;
case W_ARMF:
if (!is_boots(obj))
continue;
break;
case W_ARMB:
if (!is_bracers(obj))
continue;
break;
case W_ARMO:
if (!is_robe(obj))
continue;
break;
case W_ARM:
if (!is_suit(obj))
continue;
if (racialexception && (racial_exception(mon, obj) < 1))
continue;
break;
}
if (obj->owornmask)
continue;
/* I'd like to define a VISIBLE_ARM_BONUS which doesn't assume the
* monster knows obj->enchantment, but if I did that, a monster would keep
* switching forever between two -2 caps since when it took off one
* it would forget enchantment and once again think the object is better
* than what it already has.
*/
if (best && (ARM_AC_BONUS(best, mon->data) + extra_pref(mon, best)
>= ARM_AC_BONUS(obj, mon->data) + extra_pref(mon, obj)))
continue;
best = obj;
}
outer_break:
if (!best || best == old)
return 0;
/* same auto-cursing behavior as for hero */
autocurse = ((objects[best->otyp].oc_flags & O1_BECOMES_CURSED_WHEN_WORN) && !best->cursed);
/* Take old off */
if (old)
{/* do this first to avoid "(being worn)" */
old->owornmask = 0L;
/* intrinsics are updated below */
if (mon == u.usteed && old->otyp == SADDLE)
dismount_steed(DISMOUNT_FELL);
}
if (!creation)
{
if (canseemon(mon))
{
char buf[BUFSZ];
if (old)
Sprintf(buf, " removes %s and", distant_name(old, doname));
else
buf[0] = '\0';
pline("%s%s puts on %s.", Monnam(mon), buf,
distant_name(best, doname));
if (autocurse)
pline_multi_ex(ATR_NONE, Hallucination ? CLR_MSG_HALLUCINATED : CLR_MSG_NEGATIVE, no_multiattrs, multicolor_buffer, "%s %s %s %s for a moment.", s_suffix(Monnam(mon)),
simpleonames(best), otense(best, "glow"),
hcolor_multi_buf2(NH_BLACK));
} /* can see it */
}
/* Put new on */
mon->worn_item_flags |= flag;
best->owornmask |= flag;
if (autocurse)
curse(best);
/* if couldn't see it but now can, or vice versa, */
if (!creation && (unseen ^ !canseemon(mon))) {
if (is_invisible(mon) && !See_invisible) {
pline_ex(ATR_NONE, CLR_MSG_ATTENTION, "Suddenly you cannot see %s.", nambuf);
makeknown(best->otyp);
} /* else if (!mon->minvis) pline("%s suddenly appears!",
Amonnam(mon)); */
}
return 1;
}
#undef RACE_EXCEPTION
struct obj *
which_armor(mon, flag)
struct monst *mon;
int64_t flag;
{
if (mon == &youmonst) {
switch (flag) {
case W_ARM:
return uarm;
case W_ARMC:
return uarmc;
case W_ARMO:
return uarmo;
case W_ARMH:
return uarmh;
case W_ARMS:
return ((uarms && is_shield(uarms)) ? uarms : (struct obj*)0);
case W_ARMB:
return uarmb;
case W_ARMG:
return uarmg;
case W_ARMF:
return uarmf;
case W_ARMU:
return uarmu;
case W_AMUL:
return uamul;
case W_MISC:
return umisc;
case W_MISC2:
return umisc2;
case W_MISC3:
return umisc3;
case W_MISC4:
return umisc4;
case W_MISC5:
return umisc5;
case W_RINGL:
return uleft;
case W_RINGR:
return uright;
case W_BLINDFOLD:
return ublindf;
case W_SADDLE: /* might be used to check if you are polymorphed into a horse wearing a saddle */
return (struct obj*)0; //usaddle;
default:
//impossible("bad flag in which_armor");
return 0;
}
} else {
register struct obj *obj;
for (obj = mon->minvent; obj; obj = obj->nobj)
if (obj->owornmask & flag)
return obj;
return (struct obj *) 0;
}
}
/* remove an item of armor and then drop it */
STATIC_OVL void
m_lose_armor(mon, obj)
struct monst *mon;
struct obj *obj;
{
mon->worn_item_flags &= ~obj->owornmask;
if (obj->owornmask)
{
obj->owornmask = 0L;
update_all_mon_statistics(mon, FALSE);
if (mon == u.usteed && obj->otyp == SADDLE)
dismount_steed(DISMOUNT_FELL);
}
Strcpy(debug_buf_2, "m_lose_armor");
obj_extract_self(obj);
place_object(obj, mon->mx, mon->my);
/* call stackobj() if we ever drop anything that can merge */
newsym(mon->mx, mon->my);
}
/* all objects with their bypass bit set should now be reset to normal */
void
clear_bypasses()
{
struct obj *otmp, *nobj;
struct monst *mtmp;
/*
* 'Object' bypass is also used for one monster function:
* polymorph control of long worms. Activated via setting
* context.bypasses even if no specific object has been
* bypassed.
*/
for (otmp = fobj; otmp; otmp = nobj) {
nobj = otmp->nobj;
if (otmp->bypass) {
otmp->bypass = 0;
/* bypass will have inhibited any stacking, but since it's
* used for polymorph handling, the objects here probably
* have been transformed and won't be stacked in the usual
* manner afterwards; so don't bother with this.
* [Changing the fobj chain mid-traversal would also be risky.]
*/
#if 0
if (objects[otmp->otyp].oc_merge) {
xchar ox, oy;
(void) get_obj_location(otmp, &ox, &oy, 0);
stack_object(otmp);
newsym(ox, oy);
}
#endif /*0*/
}
}
for (otmp = invent; otmp; otmp = otmp->nobj)
otmp->bypass = 0;
for (otmp = migrating_objs; otmp; otmp = otmp->nobj)
otmp->bypass = 0;
for (otmp = magic_objs; otmp; otmp = otmp->nobj)
otmp->bypass = 0;
for (mtmp = fmon; mtmp; mtmp = mtmp->nmon) {
if (DEADMONSTER(mtmp))
continue;
for (otmp = mtmp->minvent; otmp; otmp = otmp->nobj)
otmp->bypass = 0;
/* long worm created by polymorph has mon->mextra->mcorpsenm set
to PM_LONG_WORM to flag it as not being subject to further
polymorph (so polymorph zap won't hit monster to transform it
into a long worm, then hit that worm's tail and transform it
again on same zap); clearing mcorpsenm reverts worm to normal */
if (is_long_worm_with_tail(mtmp->data) && has_mcorpsenm(mtmp))
MCORPSENM(mtmp) = NON_PM;
}
for (mtmp = migrating_mons; mtmp; mtmp = mtmp->nmon) {
for (otmp = mtmp->minvent; otmp; otmp = otmp->nobj)
otmp->bypass = 0;
/* no MCORPSENM(mtmp)==PM_LONG_WORM check here; long worms can't
be just created by polymorph and migrating at the same time */
}
/* billobjs and mydogs chains don't matter here */
context.bypasses = FALSE;
}
void
bypass_obj(obj)
struct obj *obj;
{
obj->bypass = 1;
context.bypasses = TRUE;
}
/* set or clear the bypass bit in a list of objects */
void
bypass_objlist(objchain, on)
struct obj *objchain;
boolean on; /* TRUE => set, FALSE => clear */
{
if (on && objchain)
context.bypasses = TRUE;
while (objchain) {
objchain->bypass = on ? 1 : 0;
objchain = objchain->nobj;
}
}
/* return the first object without its bypass bit set; set that bit
before returning so that successive calls will find further objects */
struct obj *
nxt_unbypassed_obj(objchain)
struct obj *objchain;
{
while (objchain) {
if (!objchain->bypass) {
bypass_obj(objchain);
break;
}
objchain = objchain->nobj;
}
return objchain;
}
/* like nxt_unbypassed_obj() but operates on sortloot_item array rather
than an object linked list; the array contains obj==Null terminator;
there's an added complication that the array may have stale pointers
for deleted objects (see Multiple-Drop case in askchain(invent.c)) */
struct obj *
nxt_unbypassed_loot(lootarray, listhead)
Loot *lootarray;
struct obj *listhead;
{
struct obj *o, *obj;
while ((obj = lootarray->obj) != 0) {
for (o = listhead; o; o = o->nobj)
if (o == obj)
break;
if (o && !obj->bypass) {
bypass_obj(obj);
break;
}
++lootarray;
}
return obj;
}
void
mon_break_armor(mon, polyspot)
struct monst *mon;
boolean polyspot;
{
register struct obj *otmp;
struct permonst *mdat = mon->data;
boolean vis = cansee(mon->mx, mon->my);
boolean handless_or_tiny = (nohands(mdat) || verysmall(mdat));
const char *pronoun = mhim(mon), *ppronoun = mhis(mon);
if (breakarm(mdat)) {
if ((otmp = which_armor(mon, W_ARM)) != 0) {
if ((is_dragon_scales(otmp) && mdat == Dragon_scales_to_pm(otmp))
|| (is_dragon_mail(otmp) && mdat == Dragon_mail_to_pm(otmp)))
; /* no message here;
"the dragon merges with his scaly armor" is odd
and the monster's previous form is already gone */
else if (vis)
pline("%s breaks out of %s armor!", Monnam(mon), ppronoun);
else
You_hear("a cracking sound.");
m_useup(mon, otmp);
}
if ((otmp = which_armor(mon, W_ARMC)) != 0) {
if (otmp->oartifact) {
if (vis)
pline("%s %s falls off!", s_suffix(Monnam(mon)),
cloak_simple_name(otmp));
if (polyspot)
bypass_obj(otmp);
m_lose_armor(mon, otmp);
} else {
if (vis)
pline("%s %s tears apart!", s_suffix(Monnam(mon)),
cloak_simple_name(otmp));
else
You_hear("a ripping sound.");
m_useup(mon, otmp);
}
}
if ((otmp = which_armor(mon, W_ARMU)) != 0) {
if (vis)
pline("%s shirt rips to shreds!", s_suffix(Monnam(mon)));
else
You_hear("a ripping sound.");
m_useup(mon, otmp);
}
} else if (sliparm(mdat)) {
if ((otmp = which_armor(mon, W_ARM)) != 0) {
if (vis)
pline("%s armor falls around %s!", s_suffix(Monnam(mon)),
pronoun);
else
You_hear("a thud.");
if (polyspot)
bypass_obj(otmp);
m_lose_armor(mon, otmp);
}
if ((otmp = which_armor(mon, W_ARMC)) != 0) {
if (vis) {
if (is_whirly(mon->data))
pline("%s %s falls, unsupported!", s_suffix(Monnam(mon)),
cloak_simple_name(otmp));
else
pline("%s shrinks out of %s %s!", Monnam(mon), ppronoun,
cloak_simple_name(otmp));
}
if (polyspot)
bypass_obj(otmp);
m_lose_armor(mon, otmp);
}
if ((otmp = which_armor(mon, W_ARMU)) != 0) {
if (vis) {
if (sliparm(mon->data))
pline("%s seeps right through %s shirt!", Monnam(mon),
ppronoun);
else
pline("%s becomes much too small for %s shirt!",
Monnam(mon), ppronoun);
}
if (polyspot)
bypass_obj(otmp);
m_lose_armor(mon, otmp);
}
}
if (handless_or_tiny) {
/* [caller needs to handle weapon checks] */
if ((otmp = which_armor(mon, W_ARMG)) != 0) {
if (vis)
pline("%s drops %s gloves%s!", Monnam(mon), ppronoun,
MON_WEP(mon) ? " and weapon" : "");
if (polyspot)
bypass_obj(otmp);
m_lose_armor(mon, otmp);
}
if ((otmp = which_armor(mon, W_ARMS)) != 0) {
if (vis)
pline("%s can no longer hold %s shield!", Monnam(mon),
ppronoun);
else
You_hear("a clank.");
if (polyspot)
bypass_obj(otmp);
m_lose_armor(mon, otmp);
}
}
if (handless_or_tiny || has_horns(mdat)) {
if ((otmp = which_armor(mon, W_ARMH)) != 0
/* flimsy test for horns matches polyself handling */
&& (handless_or_tiny || !is_flimsy(otmp))) {
if (vis)
pline("%s helmet falls to the %s!", s_suffix(Monnam(mon)),
surface(mon->mx, mon->my));
else
You_hear("a clank.");
if (polyspot)
bypass_obj(otmp);
m_lose_armor(mon, otmp);
}
}
if (handless_or_tiny || slithy(mdat) || mdat->mlet == S_CENTAUR) {
if ((otmp = which_armor(mon, W_ARMF)) != 0) {
if (vis) {
if (is_whirly(mon->data))
pline("%s boots fall away!", s_suffix(Monnam(mon)));
else
pline("%s boots %s off %s feet!", s_suffix(Monnam(mon)),
verysmall(mdat) ? "slide" : "are pushed", ppronoun);
}
if (polyspot)
bypass_obj(otmp);
m_lose_armor(mon, otmp);
}
}
if (!can_saddle(mon)) {
if ((otmp = which_armor(mon, W_SADDLE)) != 0) {
if (polyspot)
bypass_obj(otmp);
m_lose_armor(mon, otmp);
if (vis)
pline("%s saddle falls off.", s_suffix(Monnam(mon)));
}
if (mon == u.usteed)
goto noride;
} else if (mon == u.usteed && !can_ride(mon)) {
noride:
You("can no longer ride %s.", mon_nam(mon));
if (touch_petrifies(u.usteed->data) && !Stone_resistance && rnl(3)) {
char buf[BUFSZ];
You("touch %s.", mon_nam(u.usteed));
Sprintf(buf, "falling off %s", an(mon_monster_name(u.usteed)));
killer.hint_idx = HINT_KILLED_TOUCHED_COCKATRICE;
instapetrify(buf);
}
dismount_steed(DISMOUNT_FELL);
}
return;
}
/* bias a monster's preferences towards armor that has special benefits. */
STATIC_OVL int
extra_pref(mon, obj)
struct monst *mon;
struct obj *obj;
{
/* currently only does speed boots, but might be expanded if monsters
* get to use more armor abilities
*/
if (obj)
{
if ((objects[obj->otyp].oc_oprop == LIGHTNING_FAST || objects[obj->otyp].oc_oprop2 == LIGHTNING_FAST || objects[obj->otyp].oc_oprop3 == LIGHTNING_FAST)
&& !(mon->mprops[LIGHTNING_FAST] & (M_EXTRINSIC | M_INTRINSIC_ACQUIRED)))
return 50;
if ((objects[obj->otyp].oc_oprop == SUPER_FAST || objects[obj->otyp].oc_oprop2 == SUPER_FAST || objects[obj->otyp].oc_oprop3 == SUPER_FAST)
&& !(mon->mprops[SUPER_FAST] & (M_EXTRINSIC | M_INTRINSIC_ACQUIRED)))
return 40;
if ((objects[obj->otyp].oc_oprop == ULTRA_FAST || objects[obj->otyp].oc_oprop2 == ULTRA_FAST || objects[obj->otyp].oc_oprop3 == ULTRA_FAST)
&& !(mon->mprops[ULTRA_FAST] & (M_EXTRINSIC | M_INTRINSIC_ACQUIRED)))
return 30;
if ((objects[obj->otyp].oc_oprop == VERY_FAST || objects[obj->otyp].oc_oprop2 == VERY_FAST || objects[obj->otyp].oc_oprop3 == VERY_FAST)
&& !(mon->mprops[VERY_FAST] & (M_EXTRINSIC | M_INTRINSIC_ACQUIRED)))
return 20;
}
return 0;
}
/*
* Exceptions to things based on race.
* Correctly checks polymorphed player race.
* Returns:
* 0 No exception, normal rules apply.
* 1 If the race/object combination is acceptable.
* -1 If the race/object combination is unacceptable.
*/
int
racial_exception(mon, obj)
struct monst *mon;
struct obj *obj;
{
const struct permonst *ptr = raceptr(mon);
/* Acceptable Exceptions: */
/* Allow hobbits to wear elven armor - LoTR */
if (ptr == &mons[PM_HALFLING] && is_elven_armor(obj))
return 1;
/* Unacceptable Exceptions: */
/* Checks for object that certain races should never use go here */
/* return -1; */
return 0;
}
int
count_unworn_items(struct obj* inv)
{
if (!inv)
return 0;
int cnt = 0;
for (struct obj* otmp = inv; otmp; otmp = otmp->nobj)
{
if (otmp->owornmask == 0UL)
{
cnt++;
}
}
return cnt;
}
/*worn.c*/
| 412 | 0.981892 | 1 | 0.981892 | game-dev | MEDIA | 0.794057 | game-dev | 0.947652 | 1 | 0.947652 |
jerthz/scion | 10,923 | src/core/components/maths/collider.rs | use geo_clipper::Clipper;
use geo_types::{Coord, LineString};
use hecs::Entity;
use crate::core::components::maths::{coordinates::Coordinates, transform::Transform, Pivot};
use crate::utils::maths::{centroid_polygon, rotate_point_around_pivot, Vector};
/// `ColliderMask` will serve as a 'mask' to allow filter while collisions happen
#[derive(PartialEq, Clone, Eq, Hash, Debug)]
pub enum ColliderMask {
None,
Character,
Bullet,
Death,
Landscape,
Item,
Custom(String),
}
/// `ColliderType` will determine the shape of the collider.
#[derive(Clone)]
pub enum ColliderType {
SquareCollider(usize),
RectangleCollider(usize, usize),
PolygonCollider(Vec<Coordinates>)
}
/// The main collider representation to add to an entity, using the new function
#[derive(Clone)]
pub struct Collider {
collider_mask: ColliderMask,
collider_type: ColliderType,
collision_filter: Vec<ColliderMask>,
collisions: Vec<Collision>,
offset: Vector,
debug_lines: bool,
local_pivot: Option<Pivot>,
parent_pivot: Option<Pivot>,
}
impl Collider {
/// Creates a new collider. Note that an empty collision_filter means that this colliders
/// won't collide
pub fn new(
collider_mask: ColliderMask,
collision_filter: Vec<ColliderMask>,
collider_type: ColliderType,
) -> Self {
Collider {
collider_mask,
collider_type,
collision_filter,
collisions: vec![],
offset: Vector::default(),
debug_lines: false,
local_pivot: None,
parent_pivot: None,
}
}
pub fn with_debug_lines(mut self) -> Self {
self.debug_lines = true;
self
}
pub fn with_custom_pivot(mut self, pivot: Pivot) -> Self {
self.local_pivot = Some(pivot);
self
}
pub fn with_offset(mut self, offset: Vector) -> Self {
self.offset = offset;
self
}
/// Return whether or not this collider colliding to any other collider ?
pub fn is_colliding(&self) -> bool {
!self.collisions.is_empty()
}
/// Returns an iterator of current collisions
pub fn collisions(&self) -> &Vec<Collision> {
&self.collisions
}
/// The mask of this collider
pub fn mask(&self) -> &ColliderMask {
&self.collider_mask
}
/// The mask of this collider
pub fn mask_cloned(&self) -> ColliderMask {
self.collider_mask.clone()
}
/// The filters of this collider
pub fn filters(&self) -> &Vec<ColliderMask> {
&self.collision_filter
}
/// Retrieve the collider type of this collider
pub fn collider_type(&self) -> &ColliderType {
&self.collider_type
}
/// Retrieve the offset of this collider
pub fn offset(&self) -> &Vector {
&self.offset
}
pub(crate) fn debug_lines(&self) -> bool {
self.debug_lines
}
pub(crate) fn clear_collisions(&mut self) {
self.collisions.clear();
}
pub(crate) fn set_parent_pivot(&mut self, parent_pivot: Pivot) {
self.parent_pivot = Some(parent_pivot);
}
pub(crate) fn get_pivot(&self) -> Pivot {
if self.local_pivot.is_some() {
self.local_pivot.unwrap()
} else if self.parent_pivot.is_some() {
self.parent_pivot.unwrap()
} else {
Pivot::TopLeft
}
}
pub(crate) fn collider_polygon(&self, transform: &Transform) -> geo_types::Polygon::<f32> {
let base_x = transform.global_translation.x + self.offset.x;
let base_y = transform.global_translation.y + self.offset.y;
let vec = self.collider_coordinates(base_x, base_y);
let pivot_point = match self.get_pivot() {
Pivot::TopLeft => { Coordinates::new(base_x, base_y) }
Pivot::Center => { centroid_polygon(&vec) }
Pivot::Custom(x,y) => {Coordinates::new(base_x + x,base_y + y)}
};
let coords: Vec<Coord<f32>> = vec.iter().map(|c| rotate_point_around_pivot(c, &pivot_point, transform.global_angle))
.map(|c| {
Coord { x: c.x, y: c.y }
})
.collect();
geo_types::Polygon::<f32>::new(LineString::<f32>(coords), vec![])
}
pub(crate) fn collider_coordinates(&self, base_x: f32, base_y: f32) -> Vec<Coordinates> {
match self.collider_type() {
ColliderType::SquareCollider(size) => {
vec![
Coordinates::new(base_x + 0., base_y + 0.),
Coordinates::new(base_x + *size as f32, base_y + 0.),
Coordinates::new(base_x + *size as f32, base_y + *size as f32),
Coordinates::new(base_x + 0., base_y + *size as f32),
]
}
ColliderType::RectangleCollider(width, height) => {
vec![
Coordinates::new(base_x + 0., base_y + 0.),
Coordinates::new(base_x + *width as f32, base_y + 0.),
Coordinates::new(base_x + *width as f32, base_y + *height as f32),
Coordinates::new(base_x + 0., base_y + *height as f32),
]
}
ColliderType::PolygonCollider(coordinates) => {
coordinates.iter().map(|c| Coordinates::new(base_x + c.x, base_y + c.y)).collect()
}
}
}
pub(crate) fn can_collide_with(&self, other: &Collider) -> bool {
self.collision_filter.is_empty() || self.collision_filter.contains(&other.collider_mask)
}
pub(crate) fn collides_with(
&self,
self_transform: &Transform,
target_collider: &Collider,
target_transform: &Transform,
) -> Option<CollisionArea> {
if !self.can_collide_with(target_collider) {
return None;
}
let self_polygon = self.collider_polygon(self_transform);
let target_polygon = target_collider.collider_polygon(target_transform);
let result = self_polygon.intersection(&target_polygon, 1.0);
if !result.0.is_empty() {
let collision = result.0.first().unwrap();
let coordinates: Vec<Coordinates> = collision.exterior().0.iter().map(|c| Coordinates::new(c.x, c.y)).collect();
Some(CollisionArea{
coordinates
})
} else {
None
}
}
pub(crate) fn add_collisions(&mut self, collisions: &mut Vec<Collision>) {
self.collisions.append(collisions);
}
}
/// Representation of a collision
#[derive(Clone, Debug)]
pub struct Collision {
pub(crate) mask: ColliderMask,
pub(crate) entity: Entity,
pub(crate) coordinates: Coordinates,
pub(crate) collision_area: CollisionArea,
}
impl Collision {
pub fn entity(&self) -> &Entity {
&self.entity
}
pub fn mask(&self) -> &ColliderMask {
&self.mask
}
pub fn coordinates(&self) -> &Coordinates {
&self.coordinates
}
pub fn area(&self) -> &CollisionArea {
&self.collision_area
}
}
#[derive(Clone, Debug)]
pub struct CollisionArea {
pub(crate) coordinates: Vec<Coordinates>,
}
impl CollisionArea {
pub fn polygon(&self) -> &Vec<Coordinates> {
&self.coordinates
}
pub fn max_x(&self) -> f32 {
self.coordinates.iter().map(|c|c.x).reduce(f32::max).unwrap()
}
pub fn min_x(&self) -> f32 {
self.coordinates.iter().map(|c|c.x).reduce(f32::min).unwrap()
}
pub fn max_y(&self) -> f32 {
self.coordinates.iter().map(|c|c.y).reduce(f32::max).unwrap()
}
pub fn min_y(&self) -> f32 {
self.coordinates.iter().map(|c|c.y).reduce(f32::min).unwrap()
}
}
/// Internal component used to keep track of a collider debug display
pub(crate) struct ColliderDebug;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_can_collide_with() {
let bullet = Collider::new(ColliderMask::Bullet, vec![], ColliderType::SquareCollider(5));
let ship = Collider::new(
ColliderMask::Character,
vec![ColliderMask::Bullet],
ColliderType::SquareCollider(5),
);
let land = Collider::new(ColliderMask::Landscape, vec![], ColliderType::SquareCollider(5));
assert!(!ship.can_collide_with(&land));
assert!(ship.can_collide_with(&bullet));
}
#[test]
fn test_collides_with_square() {
let bullet = Collider::new(ColliderMask::Bullet, vec![], ColliderType::SquareCollider(5));
let ship = Collider::new(ColliderMask::Character, vec![], ColliderType::SquareCollider(5));
let bullet_transform = Transform::from_xy(4., 4.);
let bullet_transform2 = Transform::from_xy(9., 9.);
let ship_transform_in = Transform::from_xy(5., 5.);
let ship_transform_in2 = Transform::from_xy(8.99999, 8.99999);
let ship_transform_out = Transform::from_xy(50., 50.);
assert!(ship.collides_with(&ship_transform_in, &bullet, &bullet_transform).is_some());
assert!(ship.collides_with(&ship_transform_in2, &bullet, &bullet_transform).is_some());
assert!(ship.collides_with(&ship_transform_in, &bullet, &bullet_transform2).is_some());
assert!(bullet.collides_with(&ship_transform_out, &bullet, &bullet_transform).is_none());
}
#[test]
fn test_does_notcollides_with_square_if_offsets_too_far() {
let mut bullet = Collider::new(
ColliderMask::Bullet,
vec![ColliderMask::Character],
ColliderType::SquareCollider(5),
);
bullet = bullet.with_offset(Vector::new(-3., -3.));
let mut ship = Collider::new(
ColliderMask::Character,
vec![ColliderMask::Bullet],
ColliderType::SquareCollider(5),
);
ship = ship.with_offset(Vector::new(3., 3.));
let bullet_transform = Transform::from_xy(5., 5.);
let ship_transform = Transform::from_xy(5., 5.);
assert!(bullet.collides_with(&bullet_transform, &ship, &ship_transform).is_none());
}
#[test]
fn test_does_collides_with_square_if_offsets_close_enough() {
let mut bullet = Collider::new(
ColliderMask::Bullet,
vec![ColliderMask::Character],
ColliderType::SquareCollider(5),
);
bullet = bullet.with_offset(Vector::new(-1., -1.));
let mut ship = Collider::new(
ColliderMask::Character,
vec![ColliderMask::Bullet],
ColliderType::SquareCollider(5),
);
ship = ship.with_offset(Vector::new(1., 1.));
let bullet_transform = Transform::from_xy(5., 5.);
let ship_transform = Transform::from_xy(5., 5.);
assert!(bullet.collides_with(&bullet_transform, &ship, &ship_transform).is_some());
}
}
| 412 | 0.754974 | 1 | 0.754974 | game-dev | MEDIA | 0.785961 | game-dev | 0.88362 | 1 | 0.88362 |
LINBIT/linstor-server | 2,688 | controller/src/main/java/com/linbit/linstor/event/handler/protobuf/controller/ConnectionStateEventHandler.java | package com.linbit.linstor.event.handler.protobuf.controller;
import com.linbit.linstor.InternalApiConsts;
import com.linbit.linstor.event.EventIdentifier;
import com.linbit.linstor.event.common.ConnectionStateEvent;
import com.linbit.linstor.event.handler.EventHandler;
import com.linbit.linstor.event.handler.SatelliteStateHelper;
import com.linbit.linstor.event.handler.protobuf.ProtobufEventHandler;
import com.linbit.linstor.proto.eventdata.EventConnStateOuterClass;
import javax.inject.Inject;
import java.io.IOException;
import java.io.InputStream;
@ProtobufEventHandler(
eventName = InternalApiConsts.EVENT_CONNECTION_STATE
)
public class ConnectionStateEventHandler implements EventHandler
{
private final SatelliteStateHelper satelliteStateHelper;
private final ConnectionStateEvent connectionStateEvent;
@Inject
public ConnectionStateEventHandler(
SatelliteStateHelper satelliteStateHelperRef,
ConnectionStateEvent connectionStateEventRef
)
{
satelliteStateHelper = satelliteStateHelperRef;
connectionStateEvent = connectionStateEventRef;
}
@Override
public void execute(String eventAction, EventIdentifier eventIdentifier, InputStream eventDataIn)
throws IOException
{
if (eventAction.equals(InternalApiConsts.EVENT_STREAM_VALUE))
{
EventConnStateOuterClass.EventConnState eventVlmDiskState =
EventConnStateOuterClass.EventConnState.parseDelimitedFrom(eventDataIn);
satelliteStateHelper.onSatelliteState(
eventIdentifier.getNodeName(),
satelliteState -> satelliteState.setOnConnection(
eventIdentifier.getResourceName(),
eventIdentifier.getNodeName(),
eventIdentifier.getPeerNodeName(),
eventVlmDiskState.getConnectionState()
)
);
connectionStateEvent.get()
.forwardEvent(
eventIdentifier.getObjectIdentifier(),
eventAction,
eventVlmDiskState.getConnectionState()
);
}
else
{
satelliteStateHelper.onSatelliteState(
eventIdentifier.getNodeName(),
satelliteState -> satelliteState.unsetOnConnection(
eventIdentifier.getResourceName(),
eventIdentifier.getNodeName(),
eventIdentifier.getPeerNodeName()
)
);
connectionStateEvent.get().forwardEvent(eventIdentifier.getObjectIdentifier(), eventAction);
}
}
}
| 412 | 0.746708 | 1 | 0.746708 | game-dev | MEDIA | 0.281708 | game-dev | 0.838044 | 1 | 0.838044 |
danielah05/UndertaleDecomp | 3,626 | objects/obj_loox/Step_0.gml | if (global.mnfight == 3)
attacked = 0
scr_blconmatch()
if (global.mnfight == 1)
{
if (talked == false)
{
alarm[5] = 70
alarm[6] = 1
talked = true
global.heard = 0
}
}
if control_check_pressed(InteractButton)
{
if (alarm[5] > 5 && obj_lborder.x == global.idealborder[0] && alarm[6] < 0)
alarm[5] = 2
}
if (global.hurtanim[myself] == 1)
{
shudder = 16
alarm[3] = global.damagetimer
global.hurtanim[myself] = 3
}
if (global.hurtanim[myself] == 2)
{
global.monsterhp[myself] -= takedamage
with (dmgwriter)
alarm[2] = 15
if (global.monsterhp[myself] >= 1)
{
global.hurtanim[myself] = 0
sprite_index = spr_loox
image_index = 0
global.myfight = 0
global.mnfight = 1
}
else
{
global.myfight = 0
global.mnfight = 1
killed = 1
instance_destroy()
}
}
if (global.hurtanim[myself] == 5)
{
global.damage = 0
instance_create(((x + (sprite_width / 2)) - 48), (y - 24), obj_dmgwriter)
with (obj_dmgwriter)
alarm[2] = 30
global.myfight = 0
global.mnfight = 1
global.hurtanim[myself] = 0
}
if (global.mnfight == 2)
{
if (attacked == 0)
{
global.turntimer = 110
global.firingrate = 4
if (((global.monster[0] + global.monster[1]) + global.monster[2]) == 3)
mycommand = 2
if (mycommand < 50)
{
global.firingrate = 13
if (mercymod < 0)
global.firingrate -= 6
if (mercymod > 6)
global.firingrate += 5
if (((global.monster[0] + global.monster[1]) + global.monster[2]) > true)
global.firingrate = (global.firingrate * 1.5)
if (((global.monster[0] + global.monster[1]) + global.monster[2]) == 3)
global.firingrate = (global.firingrate * 2)
gen = instance_create(0, 0, obj_hoopgen1)
gen.bullettype = 0
}
if (mycommand >= 50)
{
global.firingrate = 15
if (mercymod < 0)
global.firingrate -= 6
if (mercymod > 6)
global.firingrate += 5
if (((global.monster[0] + global.monster[1]) + global.monster[2]) == 2)
global.firingrate = (global.firingrate * 1.5)
if (((global.monster[0] + global.monster[1]) + global.monster[2]) == 3)
global.firingrate = (global.firingrate * 2)
gen = instance_create(0, 0, obj_hoopgen1)
gen.bullettype = 1
}
gen.myself = myself
gen.dmg = global.monsteratk[myself]
if (mycommand >= 0)
global.msg[0] = scr_gettext("obj_loox_403")
if (mycommand >= 30)
global.msg[0] = scr_gettext("obj_loox_404")
if (mycommand >= 70)
global.msg[0] = scr_gettext("obj_loox_405")
if (mycommand >= 90)
global.msg[0] = scr_gettext("obj_loox_406")
if (mercymod < -100)
global.msg[0] = scr_gettext("obj_loox_407")
if (mercymod > 100)
global.msg[0] = scr_gettext("obj_loox_408")
if (global.monsterhp[myself] < (global.monstermaxhp[myself] / 3))
global.msg[0] = scr_gettext("obj_loox_409")
attacked = 1
}
}
if (global.myfight == 2)
{
if (whatiheard != -1)
{
if (global.heard == 0)
{
if (whatiheard == 0)
{
global.msc = 0
global.msg[0] = scr_gettext("obj_loox_425")
obj_writer_set_halt(3)
iii = instance_create(global.idealborder[0], global.idealborder[2], OBJ_WRITER)
with (iii)
halt = 0
}
if (whatiheard == 3)
{
if (mercymod < 100 && global.xpreward[myself] < 20)
global.xpreward[myself] += 5
mercymod = -100
global.myfight = 0
global.mnfight = 1
}
if (whatiheard == 1)
{
FL_SparedLoox = 1
if (global.xpreward[myself] > 4)
global.xpreward[myself] -= 2
mercymod = 100
global.myfight = 0
global.mnfight = 1
}
global.heard = 1
}
}
}
if (global.myfight == 4)
{
if (global.mercyuse == false)
{
scr_mercystandard()
if (mercy < 0)
instance_destroy()
}
}
| 412 | 0.81223 | 1 | 0.81223 | game-dev | MEDIA | 0.925483 | game-dev | 0.673641 | 1 | 0.673641 |
beyond-all-reason/RecoilEngine | 6,969 | cont/base/springcontent/gamedata/weapondefs_post.lua | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- file: weapondefs_post.lua
-- brief: weaponDef post processing
-- author: Dave Rodgers
--
-- Copyright (C) 2008.
-- Licensed under the terms of the GNU GPL, v2 or later.
--
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- Per-unitDef weaponDefs
--
local function isbool(x) return (type(x) == 'boolean') end
local function istable(x) return (type(x) == 'table') end
local function isnumber(x) return (type(x) == 'number') end
local function isstring(x) return (type(x) == 'string') end
local function tobool(val)
local t = type(val)
if (t == 'nil') then
return false
elseif (t == 'boolean') then
return val
elseif (t == 'number') then
return (val ~= 0)
elseif (t == 'string') then
return ((val ~= '0') and (val ~= 'false'))
end
return false
end
local function hs2rgb(h, s)
--// FIXME? ignores saturation completely
s = 1
local invSat = 1 - s
if (h > 0.5) then h = h + 0.1 end
if (h > 1.0) then h = h - 1.0 end
local r = invSat / 2.0
local g = invSat / 2.0
local b = invSat / 2.0
if (h < (1.0 / 6.0)) then
r = r + s
g = g + s * (h * 6.0)
elseif (h < (1.0 / 3.0)) then
g = g + s
r = r + s * ((1.0 / 3.0 - h) * 6.0)
elseif (h < (1.0 / 2.0)) then
g = g + s
b = b + s * ((h - (1.0 / 3.0)) * 6.0)
elseif (h < (2.0 / 3.0)) then
b = b + s
g = g + s * ((2.0 / 3.0 - h) * 6.0)
elseif (h < (5.0 / 6.0)) then
b = b + s
r = r + s * ((h - (2.0 / 3.0)) * 6.0)
else
r = r + s
b = b + s * ((3.0 / 3.0 - h) * 6.0)
end
return ("%0.3f %0.3f %0.3f"):format(r,g,b)
end
--------------------------------------------------------------------------------
local function BackwardCompability(wdName, wd)
-- weapon reloadTime and stockpileTime were separated in 77b1
if (tobool(wd.stockpile) and (wd.stockpiletime==nil)) then
wd.stockpiletime = wd.reloadtime
wd.reloadtime = 2 -- 2 seconds
end
-- auto detect ota weapontypes
if (wd.weapontype == nil) then
local rendertype = tonumber(wd.rendertype) or 0
if (tobool(wd.dropped)) then
wd.weapontype = "AircraftBomb"
elseif (tobool(wd.vlaunch)) then
wd.weapontype = "StarburstLauncher"
elseif (tobool(wd.beamlaser)) then
wd.weapontype = "BeamLaser"
elseif (tobool(wd.isshield)) then
wd.weapontype = "Shield"
elseif (tobool(wd.waterweapon)) then
wd.weapontype = "TorpedoLauncher"
elseif (wdName:lower():find("disintegrator",1,true)) then
wd.weaponType = "DGun"
elseif (tobool(wd.lineofsight)) then
if (rendertype == 7) then
wd.weapontype = "LightningCannon"
-- swta fix (outdated?)
elseif (wd.model and wd.model:lower():find("laser",1,true)) then
wd.weapontype = "LaserCannon"
elseif (tobool(wd.beamweapon)) then
wd.weapontype = "LaserCannon"
elseif (tobool(wd.smoketrail)) then
wd.weapontype = "MissileLauncher"
elseif (rendertype == 4 and tonumber(wd.color)==2) then
wd.weapontype = "EmgCannon"
elseif (rendertype == 5) then
wd.weapontype = "Flame"
--elseif(rendertype == 1) then
-- wd.weapontype = "MissileLauncher"
else
wd.weapontype = "Cannon"
end
else
wd.weapontype = "Cannon"
end
end
if (wd.weapontype == "LightingCannon") then
wd.weapontype = "LightningCannon"
elseif (wd.weapontype == "AircraftBomb") then
if (wd.manualbombsettings) then
wd.reloadtime = tonumber(wd.reloadtime or 1.0)
wd.burstrate = tonumber(wd.burstrate or 0.1)
if (wd.reloadtime < 0.5) then
wd.burstrate = math.min(0.2, wd.reloadtime) -- salvodelay
wd.burst = math.floor((1.0 / wd.burstrate) + 1) -- salvosize
wd.reloadtime = 5.0
else
wd.burstrate = math.min(0.4, wd.reloadtime)
wd.burst = 2
end
end
end
if (not wd.rgbcolor) then
if (wd.weapontype == "Cannon") then
wd.rgbcolor = "1.0 0.5 0.0"
elseif (wd.weapontype == "EmgCannon") then
wd.rgbcolor = "0.9 0.9 0.2"
else
local hue = (wd.color or 0) / 255
local sat = (wd.color2 or 0) / 255
wd.rgbcolor = hs2rgb(hue, sat)
end
end
if (not wd.craterareaofeffect) then
wd.craterareaofeffect = tonumber(wd.areaofeffect or 0) * 1.5
end
if (tobool(wd.ballistic) or tobool(wd.dropped)) then
wd.gravityaffected = true
end
-- remove the legacy tags (so engine doesn't print warnings)
wd.rendertype = nil
wd.dropped = nil
wd.vlaunch = nil
wd.beamlaser = nil
wd.isshield = nil
wd.lineofsight = nil
wd.beamweapon = nil
wd.manualbombsettings = nil
wd.color = nil
wd.color2 = nil
wd.ballistic = nil
end
--------------------------------------------------------------------------------
local function ProcessUnitDef(udName, ud)
local wds = ud.weapondefs
if (not istable(wds)) then
return
end
-- add this unitDef's weaponDefs
for wdName, wd in pairs(wds) do
if (isstring(wdName) and istable(wd)) then
local fullName = udName .. '_' .. wdName
WeaponDefs[fullName] = wd
end
end
-- convert the weapon names
local weapons = ud.weapons
if (istable(weapons)) then
for i = 1, 32 do
local w = weapons[i]
if (istable(w)) then
if (isstring(w.def)) then
local ldef = string.lower(w.def)
local fullName = udName .. '_' .. ldef
local wd = WeaponDefs[fullName]
if (istable(wd)) then
w.name = fullName
end
end
w.def = nil
end
end
end
-- convert the death explosions
if (isstring(ud.explodeas)) then
local fullName = udName .. '_' .. ud.explodeas
if (WeaponDefs[fullName]) then
ud.explodeas = fullName
end
end
if (isstring(ud.selfdestructas)) then
local fullName = udName .. '_' .. ud.selfdestructas
if (WeaponDefs[fullName]) then
ud.selfdestructas = fullName
end
end
end
--------------------------------------------------------------------------------
local function ProcessWeaponDef(wdName, wd)
-- backward compatibility
BackwardCompability(wdName, wd)
end
--------------------------------------------------------------------------------
-- Process the unitDefs
local UnitDefs = DEFS.unitDefs
for udName, ud in pairs(UnitDefs) do
if (isstring(udName) and istable(ud)) then
ProcessUnitDef(udName, ud)
end
end
for wdName, wd in pairs(WeaponDefs) do
if (isstring(wdName) and istable(wd)) then
ProcessWeaponDef(wdName, wd)
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
| 412 | 0.94285 | 1 | 0.94285 | game-dev | MEDIA | 0.861077 | game-dev | 0.751313 | 1 | 0.751313 |
edubart/nelua-decl | 1,940 | libs/sokol/sokol-test.nelua | require 'C.arg'
require 'sokol_args'
require 'sokol_app'
require 'sokol_gfx'
require 'sokol_glue'
require 'sokol_audio'
require 'sokol_time'
local NUM_SAMPLES <comptime> = 32
local state: record{
pass_action: sg_pass_action,
even_odd: uint32,
sample_pos: cint,
samples: [NUM_SAMPLES]float32,
}
local start_time: uint64
local function init()
-- setup graphics
local sgdesc: sg_desc = {
context = sapp_sgcontext()
}
sg_setup(&sgdesc)
state.pass_action.colors[0] = {
action=SG_ACTION_CLEAR, value={1.0, 0.0, 0.0, 1.0}
}
-- setup audio
local saudiodesc: saudio_desc = {}
saudio_setup(&saudiodesc)
-- setup time
stm_setup()
start_time = stm_now()
end
local function frame()
-- draw background
local g: float32 = state.pass_action.colors[0].value.g + 0.01_f32
if g > 1.0_f32 then g = 0.0_f32 end
state.pass_action.colors[0].value.g = g
sg_begin_default_pass(&state.pass_action, sapp_width(), sapp_height())
sg_end_pass()
sg_commit()
-- audio wave
local num_frames = saudio_expect()
local s: float32
for i=0,<num_frames do
if (state.even_odd & (1<<6)) ~= 0 then
s = 0.05_f32
else
s = -0.05_f32
end
state.even_odd = state.even_odd + 1
state.samples[state.sample_pos] = s
state.sample_pos = state.sample_pos + 1
if state.sample_pos == NUM_SAMPLES then
state.sample_pos = 0
saudio_push(&state.samples[0], NUM_SAMPLES)
end
end
-- quit after a while
if stm_ms(stm_since(start_time)) > 1000 then
sapp_quit()
end
end
local function cleanup()
-- shutdown graphics
sg_shutdown()
-- shutdown audio
saudio_shutdown()
end
local args_desc: sargs_desc = {
argc = C.argc,
argv = C.argv,
}
sargs_setup(&args_desc)
local app_desc: sapp_desc = {
init_cb = init,
frame_cb = frame,
cleanup_cb = cleanup,
width = 512,
height = 512,
window_title = "Sokol Clear",
}
sapp_run(&app_desc)
print("Sokol OK!")
| 412 | 0.751243 | 1 | 0.751243 | game-dev | MEDIA | 0.531739 | game-dev | 0.97828 | 1 | 0.97828 |
Chuyu-Team/VC-LTL | 1,134 | src/14.29.30037/vccorlib/climain.cpp | //
// Copyright (C) Microsoft Corporation
// All rights reserved.
//
#include "pch.h"
int __cdecl main(Platform::Array<Platform::String^>^ arg); //User defined main function
#if defined(_GUARDED_CRT)
// define entry point wrappers for the main above
extern "C" void _guard_init();
int _guardES_main(Platform::Array<Platform::String^>^)
{
// initialize the runtime
_guard_init();
return 0;
}
int _guardEE_main(Platform::Array<Platform::String^>^)
{
// argv and env should stay around even after main returns
return 0;
}
#endif
namespace Platform {
namespace Details {
wchar_t** GetCmdArguments(_Out_ int* argc);
} }
int __cdecl _main()
{
int argc = 0;
wchar_t **argv = Platform::Details::GetCmdArguments(&argc);
auto arg = ref new Platform::Array<Platform::String^>(argc);
for(int i = 0; i < argc; i++)
{
arg->set(i, ref new Platform::String(argv[i]));
}
int ret = 0;
try {
ret = main(arg);
}
catch( ::Platform::Exception^ e)
{
::Platform::Details::ReportUnhandledError(e);
throw e;
}
return ret;
}
| 412 | 0.641214 | 1 | 0.641214 | game-dev | MEDIA | 0.473143 | game-dev | 0.647351 | 1 | 0.647351 |
glKarin/com.n0n3m4.diii4a | 2,627 | Q3E/src/main/jni/serioussam/SamTFE/Sources/Entities/Bouncer.es | /* 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. */
105
%{
#include "Entities/StdH/StdH.h"
%}
%{
extern DECL_DLL void JumpFromBouncer(CEntity *penToBounce, CEntity *penBouncer)
{
CEntity *pen = penToBounce;
CBouncer *pbo = (CBouncer *)penBouncer;
// if it is a movable model and some time has passed from the last jump
if ( (pen->GetRenderType()==CEntity::RT_MODEL) &&
(pen->GetPhysicsFlags()&EPF_MOVABLE) ) {
CMovableEntity *pmen = (CMovableEntity *)pen;
if (pmen->en_penReference==NULL) {
return;
}
// give it speed
FLOAT3D vDir;
AnglesToDirectionVector(pbo->m_aDirection, vDir);
pmen->FakeJump(pmen->en_vIntendedTranslation, vDir, pbo->m_fSpeed,
-pbo->m_fParallelComponentMultiplier, pbo->m_fNormalComponentMultiplier, pbo->m_fMaxExitSpeed, pbo->m_tmControl);
}
}
%}
class CBouncer : CRationalEntity {
name "Bouncer";
thumbnail "Thumbnails\\Bouncer.tbn";
features "HasName";
properties:
1 CTString m_strName "Name" 'N' = "Bouncer",
2 CTString m_strDescription = "",
4 FLOAT m_fSpeed "Speed [m/s]" 'S' = 20.0f,
5 ANGLE3D m_aDirection "Direction" 'D' = ANGLE3D(0,90,0),
6 FLOAT m_tmControl "Control time" 'T' = 5.0f,
7 BOOL m_bEntrySpeed = TRUE,
10 FLOAT m_fMaxExitSpeed "Max exit speed" 'M' = 200.0f,
12 FLOAT m_fNormalComponentMultiplier "Normal component multiplier" 'O' = 1.0f,
13 FLOAT m_fParallelComponentMultiplier "Parallel component multiplier" 'P' = 0.0f,
components:
functions:
procedures:
Main() {
// declare yourself as a brush
InitAsBrush();
SetPhysicsFlags(EPF_BRUSH_FIXED|EPF_NOIMPACT);
SetCollisionFlags(ECF_BRUSH);
// if old flag "entry speed" has been reset
if (!m_bEntrySpeed)
{
// kill normal component by default (same behaviour by default)
m_fNormalComponentMultiplier = 0.0f;
m_bEntrySpeed = TRUE;
}
return;
}
};
| 412 | 0.842797 | 1 | 0.842797 | game-dev | MEDIA | 0.82701 | game-dev | 0.947935 | 1 | 0.947935 |
CaffeineMC/lithium | 1,167 | neoforge/src/main/java/net/caffeinemc/mods/lithium/neoforge/mixin/util/initialization/DataMapHooksMixin.java | package net.caffeinemc.mods.lithium.neoforge.mixin.util.initialization;
import net.caffeinemc.mods.lithium.common.initialization.BlockInfoInitializer;
import net.minecraft.core.RegistryAccess;
import net.minecraft.world.flag.FeatureFlagSet;
import net.minecraft.world.level.block.entity.FuelValues;
import net.neoforged.neoforge.common.DataMapHooks;
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.CallbackInfoReturnable;
/**
* Hook into the initialization of fuel values, because those are always updated after block tags are modified,
* and we must among others, update our cache path node information which is also based on block tags.
*/
@Mixin(DataMapHooks.class)
public class DataMapHooksMixin {
@Inject(
method = "populateFuelValues",
at = @At(value = "RETURN")
)
private static void initializeCachedBlockData(RegistryAccess lookupProvider, FeatureFlagSet features, CallbackInfoReturnable<FuelValues> cir) {
BlockInfoInitializer.initializeBlockInfo();
}
}
| 412 | 0.889329 | 1 | 0.889329 | game-dev | MEDIA | 0.986997 | game-dev | 0.803702 | 1 | 0.803702 |
google/xr-objects | 2,803 | XRObjects/Assets/XRObjects/Scripts/ActionWithSubmenu.cs | // Copyright 2024 Google LLC
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using System.Linq;
// Class for menu buttons with rectangular submenus
// helps manage the visual opening/closing of the menus
public class ActionWithSubmenu : MonoBehaviour
{
private GameObject submenu;
private Button actionButton;
private bool menuIsVisible = false;
// Awake function is called on all objects in the Scene before any object's Start function is called
void Awake()
{
submenu = GetComponentInChildren<GridLayoutGroup>(true).gameObject;
actionButton = gameObject.GetComponent<Button>();
actionButton.onClick.AddListener(toggleMenuVisibility);
submenu.SetActive(false);
}
public void toggleMenuVisibility()
{
menuIsVisible = !submenu.activeSelf;
// menuIsVisible = !menuIsVisible;
if (menuIsVisible)
{
// make the main action button go to front for visibility
// puts to the front using SetAsLastSibling as it is now the last UI element to be drawn.
GameObject _mainActionButton = FindParentWithTag(submenu, "mainActionButton");
_mainActionButton.transform.SetAsLastSibling();
// close the panels of other "mainActionButton"s
GameObject[] mainActionButtons = GameObject.FindGameObjectsWithTag("mainActionButton");
foreach (GameObject mainActionButton in mainActionButtons)
{
if (mainActionButton!=_mainActionButton)
{
// close its panel
try
{
mainActionButton.GetComponentInChildren<GridLayoutGroup>().gameObject.SetActive(false);
}
catch
{
Debug.Log("this action doesn't have submenus");
}
}
}
// show my own submenu
submenu.SetActive(true);
// but close all of my own children submenus
Component[] GridLayoutGroups = submenu.GetComponentsInChildren<GridLayoutGroup>().Skip(1).ToArray(); // exclude the object itself
foreach (Component gridLayoutGroup in GridLayoutGroups)
{
gridLayoutGroup.gameObject.SetActive(false);
}
}
else
{
submenu.SetActive(false);
}
}
private GameObject FindParentWithTag(GameObject child, string tag)
{
Transform childTransform = child.transform;
while (childTransform.parent != null)
{
if (childTransform.parent.tag == tag)
{
// the parent at hand has the correct tag
return childTransform.parent.gameObject;
}
childTransform = childTransform.parent.transform;
}
return null;
}
}
| 412 | 0.893232 | 1 | 0.893232 | game-dev | MEDIA | 0.946105 | game-dev | 0.889871 | 1 | 0.889871 |
jrbudda/Vivecraft_117 | 3,997 | src/VR/org/vivecraft/gui/framework/TooltipProviderVROptions.java | package org.vivecraft.gui.framework;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import net.minecraft.ChatFormatting;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.components.AbstractWidget;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.FormattedText;
import net.minecraft.network.chat.Style;
import net.minecraft.network.chat.TextComponent;
import net.optifine.Lang;
import net.optifine.gui.TooltipProvider;
import org.vivecraft.settings.VRSettings;
import org.vivecraft.utils.Utils;
public class TooltipProviderVROptions implements TooltipProvider
{
public Rectangle getTooltipBounds(Screen guiScreen, int x, int y)
{
int i = guiScreen.width / 2 - 150;
int j = guiScreen.height / 6 - 7;
if (y <= j + 98)
{
j += 105;
}
int k = i + 150 + 150;
int l = j + 84 + 10;
return new Rectangle(i, j, k - i, l - j);
}
public boolean isRenderBorder()
{
return false;
}
public String[] getTooltipLines(AbstractWidget btn, int width)
{
if (!(btn instanceof GuiVROptionButton))
{
return null;
}
else
{
VRSettings.VrOptions vrsettings$vroptions = ((GuiVROptionButton)btn).getOption();
if (vrsettings$vroptions == null)
{
return null;
}
else
{
String s = "vivecraft.options." + vrsettings$vroptions.name() + ".tooltip";
String s1 = Lang.get(s, (String)null);
if (s1 == null)
{
return null;
}
else
{
String[] astring = s1.split("\\r?\\n", -1);
List<String> list = new ArrayList<>();
for (String s2 : astring)
{
if (s2.isEmpty())
{
list.add(s2);
}
else
{
int i = s2.indexOf(s2.trim().charAt(0));
TextComponent textcomponent = i > 0 ? new TextComponent(String.join("", Collections.nCopies(i, " "))) : null;
List<FormattedText> list1 = Utils.wrapText(new TextComponent(s2), width, Minecraft.getInstance().font, textcomponent);
Style style = Style.EMPTY;
for (FormattedText formattedtext : list1)
{
list.add(Utils.styleToFormatString(style) + formattedtext.getString());
String s3 = formattedtext.getString();
for (int j = 0; j < s3.length(); ++j)
{
if (s3.charAt(j) == 167)
{
if (j + 1 >= s3.length())
{
break;
}
char c0 = s3.charAt(j + 1);
ChatFormatting chatformatting = ChatFormatting.getByCode(c0);
if (chatformatting != null)
{
style = style.applyLegacyFormat(chatformatting);
}
++j;
}
}
}
}
}
return list.toArray(new String[0]);
}
}
}
}
}
| 412 | 0.869641 | 1 | 0.869641 | game-dev | MEDIA | 0.898026 | game-dev | 0.959541 | 1 | 0.959541 |
alan-et/alanpoi | 9,670 | alanpoi-common/src/main/java/com/alanpoi/common/util/AlanList.java | package com.alanpoi.common.util;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
import java.util.*;
/**
* 参照ArrayList,优化部分逻辑
*
* @param <T>
*/
public class AlanList<T> extends AbstractList<T> implements List<T>, Cloneable, Serializable {
protected static final Logger logger = LoggerFactory.getLogger(AlanList.class);
private int length;
private int maxLength = 30;
private static int MAX_ADD_SIZE = 150;
private Object[] element = {};
private static final Object[] emptyElement = {};
public AlanList(int initSize) {
this.length = initSize;
if (initSize > maxLength) maxLength = initSize;
if (initSize > 0) {
this.element = new Object[initSize];
} else if (initSize == 0) {
this.element = emptyElement;
} else {
this.element = emptyElement;
logger.warn("init size must >0");
}
}
public AlanList(Collection<? extends T> collection) {
element = collection.toArray();
if ((length = element.length) != 0) {
if (element.getClass() != Object[].class)
element = Arrays.copyOf(element, length, Object[].class);
} else {
this.element = emptyElement;
}
}
public AlanList() {
this.element = new Object[maxLength];
}
private synchronized void checkSize(int size) {
if (size <= maxLength) {
return;
}
maxLength += Math.max(size - length, Math.min(maxLength * 2, MAX_ADD_SIZE));
element = Arrays.copyOf(element, maxLength);
}
@Override
public int size() {
return length;
}
@Override
public boolean isEmpty() {
return length == 0;
}
@Override
public boolean contains(Object o) {
return indexOf(o) != -1;
}
@Override
protected Object clone() {
try {
AlanList<?> v = (AlanList<?>) super.clone();
v.element = Arrays.copyOf(element, length);
return v;
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
@Override
public Iterator<T> iterator() {
LinkedList<T> linkedList = new LinkedList<T>();
for (int i = 0; i < length; i++) {
linkedList.add((T) element[i]);
}
return linkedList.listIterator();
}
@Override
public Object[] toArray() {
return Arrays.copyOf(element, length);
}
@Override
public <T1> T1[] toArray(T1[] a) {
if (a.length < length) return (T1[]) Arrays.copyOf(element, length, a.getClass());
System.arraycopy(element, 0, a, 0, length);
if (a.length > length)
a[length] = null;
return a;
}
@Override
public boolean add(T t) {
modCount++;
checkSize(length + 1);
element[length++] = t;
return true;
}
@Override
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < length; index++)
if (element[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < length; index++)
if (o.equals(element[index])) {
fastRemove(index);
return true;
}
}
return false;
}
/**
* 替换法快速运算
*
* @param index
*/
private void fastRemove(int index) {
modCount++;
int numMoved = length - index - 1;
if (numMoved > 0)
System.arraycopy(element, index + 1, element, index,
numMoved);
element[--length] = null;
}
@Override
public boolean containsAll(Collection<?> c) {
for (Object o : c) {
if (!contains(o)) return false;
}
return true;
}
@Override
public boolean addAll(Collection<? extends T> c) {
Object[] a = c.toArray();
int numNew = a.length;
checkSize(length + numNew);
System.arraycopy(a, 0, element, length, numNew);
length += numNew;
modCount++;
return numNew != 0;
}
@Override
public boolean addAll(int index, Collection<? extends T> c) {
if (index > length || index < 0) {
logger.warn("index should <= 0; index:{}", index);
index = 0;
}
Object[] a = c.toArray();
int numNew = a.length;
checkSize(length + numNew); // Increments modCount
int numMoved = length - index;
if (numMoved > 0)
System.arraycopy(element, index, element, index + numNew,
numMoved);
System.arraycopy(a, 0, element, index, numNew);
length += numNew;
modCount++;
return numNew != 0;
}
@Override
public boolean removeAll(Collection<?> c) {
if (c == null || c.size() == 0) {
return false;
}
return batchRemove(c, false);
}
@Override
public boolean retainAll(Collection<?> c) {
if (c == null || c.size() == 0) {
return false;
}
return batchRemove(c, true);
}
@Override
public void clear() {
for (int i = 0; i < length; i++)
element[i] = null;
length = 0;
}
@Override
public T get(int index) {
if (index >= length) return null;
return (T) element[index];
}
@Override
public T set(int index, T element) {
T oldValue = elementData(index);
this.element[index] = element;
modCount++;
return oldValue;
}
private T elementData(int index) {
return (T) element[index];
}
@Override
public void add(int index, T element) {
if (index < 0 || index > length) {
logger.warn("index should > 0");
return;
}
checkSize(index + 1); // Increments modCount!!
System.arraycopy(element, index, element, index + 1,
length - index);
this.element[index] = element;
length++;
modCount++;
}
@Override
public T remove(int index) {
if (index < 0 || index >= length) {
return null;
}
T oldValue = elementData(index);
int numMoved = length - index - 1;
if (numMoved > 0)
System.arraycopy(element, index + 1, element, index,
numMoved);
element[--length] = null;
modCount++;
return oldValue;
}
@Override
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < length; i++)
if (element[i] == null)
return i;
} else {
for (int i = 0; i < length; i++)
if (((T) element[i]).equals(o))
return i;
}
return -1;
}
@Override
public int lastIndexOf(Object o) {
if (o == null) {
for (int i = length - 1; i >= 0; i--)
if (element[i] == null)
return i;
} else {
for (int i = length - 1; i >= 0; i--)
if (o.equals(element[i]))
return i;
}
return -1;
}
@Override
public ListIterator<T> listIterator() {
LinkedList linkedList = new LinkedList<T>();
for (int i = 0; i < length; i++) {
linkedList.add((T) element);
}
return linkedList.listIterator();
}
@Override
public ListIterator<T> listIterator(int index) {
LinkedList linkedList = new LinkedList<T>();
for (int i = 0; i < length; i++) {
linkedList.add((T) element);
}
return linkedList.listIterator(index);
}
static void subListRangeCheck(int var0, int var1, int var2) {
if (var0 < 0) {
throw new IndexOutOfBoundsException("fromIndex = " + var0);
} else if (var1 > var2) {
throw new IndexOutOfBoundsException("toIndex = " + var1);
} else if (var0 > var1) {
throw new IllegalArgumentException("fromIndex(" + var0 + ") > toIndex(" + var1 + ")");
}
}
// @Override
// public List<T> subList(int fromIndex, int toIndex) {
//
// }
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.element;
int r = 0, w = 0;
boolean modified = false;
try {
for (; r < length; r++)
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
if (r != length) {
System.arraycopy(elementData, r,
elementData, w,
length - r);
w += length - r;
}
if (w != length) {
for (int i = w; i < length; i++)
elementData[i] = null;
modCount += length - w;
length = w;
modified = true;
}
}
return modified;
}
@Override
public String toString() {
if (length == 0) {
return null;
}
Object[] newObj = new Object[length];
int i = 0;
for (Object obj : element) {
if (obj == null) continue;
newObj[i++] = obj;
}
return JSON.toJSONString(newObj);
}
}
| 412 | 0.925801 | 1 | 0.925801 | game-dev | MEDIA | 0.204024 | game-dev | 0.983944 | 1 | 0.983944 |
SuperNewRoles/SuperNewRoles | 1,752 | SuperNewRoles/Roles/Ability/KnowOtherAbility.cs | using System;
using UnityEngine;
using SuperNewRoles.Modules;
using SuperNewRoles.Modules.Events.Bases;
using SuperNewRoles.Events;
namespace SuperNewRoles.Roles.Ability;
public class KnowOtherAbility : AbilityBase
{
public Func<ExPlayerControl, bool> CanKnowOther { get; }
public Func<bool> IsShowRole { get; }
public Func<ExPlayerControl, Color32>? Color { get; }
private EventListener<NameTextUpdateEventData> _nameTextUpdateEvent;
private EventListener<NameTextUpdateVisiableEventData> _nameTextUpdateVisiableEvent;
public KnowOtherAbility(Func<ExPlayerControl, bool> canKnowOther, Func<bool> isShowRole, Func<ExPlayerControl, Color32>? color = null)
{
CanKnowOther = canKnowOther;
IsShowRole = isShowRole;
Color = color;
}
public override void AttachToLocalPlayer()
{
_nameTextUpdateEvent = NameTextUpdateEvent.Instance.AddListener(OnNameTextUpdate);
_nameTextUpdateVisiableEvent = NameTextUpdateVisiableEvent.Instance.AddListener(OnNameTextUpdateVisiable);
}
private void OnNameTextUpdate(NameTextUpdateEventData data)
{
if (!CanKnowOther(data.Player)) return;
Color32 color = Color?.Invoke(data.Player) ?? data.Player.roleBase.RoleColor;
NameText.SetNameTextColor(data.Player, color);
}
private void OnNameTextUpdateVisiable(NameTextUpdateVisiableEventData data)
{
if (!CanKnowOther(data.Player)) return;
if (IsShowRole())
NameText.UpdateVisible(data.Player, data.Visiable);
}
public override void DetachToLocalPlayer()
{
base.DetachToLocalPlayer();
_nameTextUpdateEvent?.RemoveListener();
_nameTextUpdateVisiableEvent?.RemoveListener();
}
}
| 412 | 0.71976 | 1 | 0.71976 | game-dev | MEDIA | 0.860853 | game-dev | 0.827405 | 1 | 0.827405 |
Patcher0/ThePitUltimate | 1,368 | core/src/main/java/net/mizukilab/pit/enchantment/type/normal/RespawnAbsorptionEnchant.java | package net.mizukilab.pit.enchantment.type.normal;
import net.mizukilab.pit.enchantment.AbstractEnchantment;
import net.mizukilab.pit.enchantment.param.item.ArmorOnly;
import net.mizukilab.pit.enchantment.rarity.EnchantmentRarity;
import net.mizukilab.pit.parm.listener.IPlayerRespawn;
import net.mizukilab.pit.util.cooldown.Cooldown;
import nya.Skip;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer;
import org.bukkit.entity.Player;
/**
* @Author: Misoryan
* @Created_In: 2021/2/24 18:58
*/
@Skip
@ArmorOnly
public class RespawnAbsorptionEnchant extends AbstractEnchantment implements IPlayerRespawn {
@Override
public String getEnchantName() {
return "复生: 生命吸收";
}
@Override
public int getMaxEnchantLevel() {
return 3;
}
@Override
public String getNbtName() {
return "respawn_absorption";
}
@Override
public EnchantmentRarity getRarity() {
return EnchantmentRarity.NORMAL;
}
@Override
public Cooldown getCooldown() {
return null;
}
@Override
public String getUsefulnessLore(int enchantLevel) {
return "&7每次死亡后复活立刻获得 &6" + (enchantLevel * 5) + "❤ 伤害吸收";
}
@Override
public void handleRespawn(int enchantLevel, Player myself) {
((CraftPlayer) myself).getHandle().setAbsorptionHearts(enchantLevel * 10);
}
}
| 412 | 0.841712 | 1 | 0.841712 | game-dev | MEDIA | 0.979239 | game-dev | 0.922474 | 1 | 0.922474 |
feakin/fklang | 2,169 | fkl_ext_loader/src/lib.rs | use libloading::{Library, Symbol};
use thiserror::Error;
use fkl_ext_api::custom_runner::{CreateRunner, CustomRunner};
/// Errors that can occur when loading a dynamic ext
#[derive(Debug, Error)]
pub enum ExtLoadError {
#[error("cannot load library: {0}")]
Library(libloading::Error),
#[error("dynamic library does not contain a valid dynamic ext")]
Plugin(libloading::Error),
}
/// links a ext at the given path.
pub unsafe fn dynamically_load_ext(
path: &str,
) -> Result<(Library, Box<dyn CustomRunner>), ExtLoadError> {
// 1. load the dynamic library
let lib = Library::new(path).map_err(ExtLoadError::Library)?;
// 2. get and check the function pointer
let func: Symbol<CreateRunner> = lib
.get(b"_fkl_create_runner")
.map_err(ExtLoadError::Plugin)?;
// 3. call the function pointer
let plugin = Box::from_raw(func());
Ok((lib, plugin))
}
#[cfg(target_os = "macos")]
pub fn ext_path(plugin_name: &str, for_production: bool) -> String {
if for_production {
format!("plugins/lib{}.dylib", plugin_name)
} else {
format!("target/debug/lib{}.dylib", plugin_name)
}
}
#[cfg(target_os = "linux")]
pub fn ext_path(plugin_name: &str, for_production: bool) -> String {
if for_production {
format!("plugins/lib{}.so", plugin_name)
} else {
format!("target/debug/lib{}.so", plugin_name)
}
}
#[cfg(target_os = "windows")]
pub fn ext_path(plugin_name: &str, for_production: bool) -> String {
if for_production {
format!("plugins\\{}.dll", plugin_name)
} else {
format!("target\\debug\\{}.dll", plugin_name)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
use fkl_mir::{ContextMap, CustomEnv};
#[tokio::test]
async fn test_load_ext() {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.parent().unwrap()
.join(ext_path("ext_hello_world", false));
unsafe {
let (lib, ext) = dynamically_load_ext(path.to_str().unwrap()).unwrap();
std::mem::forget(lib); // Ensure that the library is not automatically unloaded
// println!("ext: {:?}", ext);
ext.execute(&ContextMap::default(), &CustomEnv::default()).await;
}
}
}
| 412 | 0.963142 | 1 | 0.963142 | game-dev | MEDIA | 0.551745 | game-dev,desktop-app | 0.872158 | 1 | 0.872158 |
FireEmblemUniverse/fireemblem8u | 5,855 | src/menuitempanel.c | #include "global.h"
#include "bmunit.h"
#include "fontgrp.h"
#include "bmbattle.h"
#include "uimenu.h"
#include "icon.h"
#include "bmitem.h"
#include "proc.h"
#include "hardware.h"
#include "uiutils.h"
#include "bm.h"
#include "menuitempanel.h"
#include "functions.h"
void MenuItemPanelProcIdle(struct MenuItemPanelProc * proc);
struct ProcCmd CONST_DATA gProcCmd_MenuItemPanel[] = {
PROC_15,
PROC_REPEAT(MenuItemPanelProcIdle),
PROC_END,
};
void MenuItemPanelProcIdle(struct MenuItemPanelProc * proc)
{
if (0 == proc->draw_arrow)
return;
if (proc->ItemSlotIndex < 0)
return;
/* atk */
if (gBattleActor.battleAttack > gBattleTarget.battleAttack)
UpdateStatArrowSprites(proc->x * 8 + 0x33, (proc->y + 3) * 8, 0);
if (gBattleActor.battleAttack < gBattleTarget.battleAttack)
UpdateStatArrowSprites(proc->x * 8 + 0x33, (proc->y + 3) * 8, 1);
/* hit */
if (gBattleActor.battleHitRate > gBattleTarget.battleHitRate)
UpdateStatArrowSprites(proc->x * 8 + 0x33, (proc->y + 5) * 8, 0);
if (gBattleActor.battleHitRate < gBattleTarget.battleHitRate)
UpdateStatArrowSprites(proc->x * 8 + 0x33, (proc->y + 5) * 8, 1);
/* crit */
if (gBattleActor.battleCritRate > gBattleTarget.battleCritRate)
UpdateStatArrowSprites(proc->x * 8 + 0x63, (proc->y + 3) * 8, 0);
if (gBattleActor.battleCritRate < gBattleTarget.battleCritRate)
UpdateStatArrowSprites(proc->x * 8 + 0x63, (proc->y + 3) * 8, 1);
/* avoid */
if (gBattleActor.battleAvoidRate > gBattleTarget.battleAvoidRate)
UpdateStatArrowSprites(proc->x * 8 + 0x63, (proc->y + 5) * 8, 0);
if (gBattleActor.battleAvoidRate < gBattleTarget.battleAvoidRate)
UpdateStatArrowSprites(proc->x * 8 + 0x63, (proc->y + 5) * 8, 1);
}
void ForceMenuItemPanel(ProcPtr _menu_proc, struct Unit * unit, int x, int y)
{
struct MenuProc *menu_proc = _menu_proc;
struct MenuItemPanelProc * proc;
if (NULL == Proc_Find(gProcCmd_MenuItemPanel)) {
proc = Proc_Start(gProcCmd_MenuItemPanel, menu_proc);
proc->unit = unit;
proc->x = x;
proc->y = y;
proc->IconPalIndex = 3;
proc->ItemSlotIndex = GetUnitEquippedWeaponSlot(unit);
proc->draw_arrow = TRUE;
InitTextDb(&proc->text[0], 0xC);
InitTextDb(&proc->text[1], 0xC);
InitTextDb(&proc->text[2], 0xC);
LoadIconPalette(1, proc->IconPalIndex);
BattleGenerateUiStats(proc->unit, BU_ISLOT_AUTO);
gBattleTarget.battleAttack = gBattleActor.battleAttack;
gBattleTarget.battleHitRate = gBattleActor.battleHitRate;
gBattleTarget.battleCritRate = gBattleActor.battleCritRate;
gBattleTarget.battleAvoidRate = gBattleActor.battleAvoidRate;
}
}
void UpdateMenuItemPanel(int slot_or_item)
{
struct MenuItemPanelProc * proc = Proc_Find(gProcCmd_MenuItemPanel);
u16 * bg_base = BG_GetMapBuffer(0) + proc->x + 0x20 * proc->y;
struct Text * texts = &proc->text[0];
struct Unit * unit = proc->unit;
int i, item, color, icon_pal = proc->IconPalIndex;
char * str;
ClearText(&proc->text[0]);
ClearText(&proc->text[1]);
ClearText(&proc->text[2]);
DrawUiFrame2(proc->x, proc->y, 0xE, 0x8, 0x0);
switch (slot_or_item) {
case 0:
case 1:
case 2:
case 3:
case 4:
item = unit->items[slot_or_item];
break;
case BU_ISLOT_5:
item = gBmSt.um_tmp_item;
break;
default:
item = slot_or_item;
slot_or_item = BU_ISLOT_BALLISTA;
break;
} /* switch slot */
switch (GetItemType(item)) {
case ITYPE_STAFF:
case ITYPE_ITEM:
case ITYPE_11:
case ITYPE_12:
str = GetStringFromIndex(GetItemUseDescId(item));
i = 0;
while (1) {
Text_InsertDrawString(&texts[i], 0, TEXT_COLOR_SYSTEM_WHITE, str);
str = GetStringLineEnd(str);
if (0 == *str)
break;
str++;
i++;
}
gBattleActor.battleAttack = gBattleTarget.battleAttack;
gBattleActor.battleHitRate = gBattleTarget.battleHitRate;
gBattleActor.battleCritRate = gBattleTarget.battleCritRate;
gBattleActor.battleAvoidRate = gBattleTarget.battleAvoidRate;
PutText(&texts[0], TILEMAP_LOCATED(bg_base, 1, 1));
PutText(&texts[1], TILEMAP_LOCATED(bg_base, 1, 3));
PutText(&texts[2], TILEMAP_LOCATED(bg_base, 1, 5));
break;
default:
BattleGenerateUiStats(unit, slot_or_item);
if (BU_ISLOT_BALLISTA == slot_or_item) {
gBattleTarget.battleAttack = gBattleActor.battleAttack;
gBattleTarget.battleHitRate = gBattleActor.battleHitRate;
gBattleTarget.battleCritRate = gBattleActor.battleCritRate;
gBattleTarget.battleAvoidRate = gBattleActor.battleAvoidRate;
}
color = CanUnitUseWeapon(unit, gBattleActor.weapon) ? TEXT_COLOR_SYSTEM_BLUE : TEXT_COLOR_SYSTEM_GRAY;
Text_InsertDrawString(&texts[0], 0x1C, TEXT_COLOR_SYSTEM_WHITE, GetStringFromIndex(0x4F1));
Text_InsertDrawString(&texts[1], 0x02, TEXT_COLOR_SYSTEM_WHITE, GetStringFromIndex(0x4F3));
Text_InsertDrawString(&texts[2], 0x02, TEXT_COLOR_SYSTEM_WHITE, GetStringFromIndex(0x4F4));
Text_InsertDrawString(&texts[1], 0x32, TEXT_COLOR_SYSTEM_WHITE, GetStringFromIndex(0x501));
Text_InsertDrawString(&texts[2], 0x32, TEXT_COLOR_SYSTEM_WHITE, GetStringFromIndex(0x4F5));
Text_InsertDrawNumberOrBlank(&texts[1], 0x24, color, gBattleActor.battleAttack);
Text_InsertDrawNumberOrBlank(&texts[2], 0x24, color, gBattleActor.battleHitRate);
Text_InsertDrawNumberOrBlank(&texts[1], 0x54, color, gBattleActor.battleCritRate);
Text_InsertDrawNumberOrBlank(&texts[2], 0x54, color, gBattleActor.battleAvoidRate);
PutText(&proc->text[0], TILEMAP_LOCATED(gBG0TilemapBuffer, proc->x + 1, proc->y + 0x1));
PutText(&proc->text[1], TILEMAP_LOCATED(gBG0TilemapBuffer, proc->x + 1, proc->y + 0x3));
PutText(&proc->text[2], TILEMAP_LOCATED(gBG0TilemapBuffer, proc->x + 1, proc->y + 0x5));
DrawIcon(
TILEMAP_LOCATED(bg_base, 8, 1),
GetItemType(gBattleActor.weapon) + 0x70,
icon_pal << 0xC);
break;
} /* switch item type */
BG_EnableSyncByMask(BG0_SYNC_BIT);
}
void EndMenuItemPanel()
{
Proc_EndEach(gProcCmd_MenuItemPanel);
}
| 412 | 0.917189 | 1 | 0.917189 | game-dev | MEDIA | 0.768659 | game-dev | 0.953185 | 1 | 0.953185 |
dreamhead/moco | 1,088 | moco-core/src/main/java/com/github/dreamhead/moco/recorder/RecorderIdentifier.java | package com.github.dreamhead.moco.recorder;
import com.github.dreamhead.moco.ConfigApplier;
import com.github.dreamhead.moco.HttpRequest;
import com.github.dreamhead.moco.MocoConfig;
import com.github.dreamhead.moco.resource.ContentResource;
import com.github.dreamhead.moco.resource.Resource;
public class RecorderIdentifier implements RecorderConfig, ConfigApplier<RecorderIdentifier> {
private final ContentResource resource;
public RecorderIdentifier(final ContentResource resource) {
this.resource = resource;
}
public final String getIdentifier(final HttpRequest httpRequest) {
return this.resource.readFor(httpRequest).toString();
}
@Override
public final boolean isFor(final String name) {
return IDENTIFIER.equalsIgnoreCase(name);
}
@Override
public final RecorderIdentifier apply(final MocoConfig config) {
Resource applied = resource.apply(config);
if (applied != this.resource) {
return new RecorderIdentifier((ContentResource) applied);
}
return this;
}
}
| 412 | 0.862126 | 1 | 0.862126 | game-dev | MEDIA | 0.856355 | game-dev | 0.687289 | 1 | 0.687289 |
giacomogroppi/writernote-qt | 1,481 | src/touch/object_finder/ObjectFinder.h | #pragma once
#include "utils/WCommonScript.h"
#include "touch/dataTouch/Point.h"
#include "Scheduler/WObject.h"
#include "Scheduler/WTimer.h"
/*
class ObjectFinder : public WObject
{
public:
explicit ObjectFinder(WObject *parent, Fn<void()> callUpdate);
~ObjectFinder() override = default;
void move(const PointF &point);
void endMoving();
void reset();
private:
Fn<void()> _callUpdate;
[[nodiscard]] bool isActive() const;
PointSettable _point;
static constexpr auto debug = false;
static constexpr auto time = 1 * 500;
WTimer *_timer;
DEFINE_LISTENER(endTimer());
};
force_inline void ObjectFinder::endMoving()
{
return this->reset();
}
force_inline void ObjectFinder::move(const PointF& point)
{
WDebug(debug, "ObjectFinder");
if(_point.isSet()){
// if the point is equal we don't have to stop the timer
if(un(WUtils::is_near(_point, point, 1.))){
return;
}
// if the point is differente we neet to write it and restart the timer
_point = point;
}else{
_point.set(true);
_point = point;
}
if(_timer->isActive()){
_timer->stop();
}
_timer->start(time);
}
force_inline void ObjectFinder::reset()
{
_point.set(false);
WDebug(debug, "ObjectFinder" << __FUNCTION__);
if(isActive()){
_timer->stop();
}
}
force_inline bool ObjectFinder::isActive() const
{
return _timer->isActive();
}
*/
| 412 | 0.966956 | 1 | 0.966956 | game-dev | MEDIA | 0.778953 | game-dev | 0.977 | 1 | 0.977 |
Parrot-Developers/openflight-ios | 5,662 | OpenFlight/OpenFlight/Modules/Occupancy/OGSpeedometer.swift | // Copyright (C) 2019 Parrot Drones SAS
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
// * Neither the name of the Parrot Company nor the names
// of its contributors may be used to endorse or promote products
// derived from this software without specific prior written
// permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// PARROT COMPANY 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.
// FIXME: Occupancy / WIP
import Foundation
import simd
public class OGSpeedometer {
private let averageNumber = Occupancy.framesUsedForSpeed
private var historySpeed = [simd_float3]()
private var lastEntryTime: Date?
private let accessQueue = DispatchQueue(label: "OGSpeedometer.access", qos: .userInteractive)
public var speed: simd_float3 {
let oneFrameTime = Float32(1) / Float32(Occupancy.framesPerSec)
var retValue: simd_float3?
accessQueue.sync {
let atAtime = Date()
if let lastEntryTime = self.lastEntryTime {
let elapsedTime = Float(atAtime.timeIntervalSince(lastEntryTime))
if elapsedTime > 2 * oneFrameTime && !self.historySpeed.isEmpty {
// the array was not refresh -> drop the oldest value
self.historySpeed.removeFirst()
}
}
let nbcount = self.historySpeed.count
if nbcount > 0 {
let averageCoef = Float32(1) / Float32(nbcount)
retValue = historySpeed.reduce(simd_float3(), +) * simd_float3(averageCoef, averageCoef, averageCoef)
}
}
return retValue ?? simd_float3()
}
public func setNewSpeed(_ speed: simd_float3) {
accessQueue.async {
self.lastEntryTime = Date()
self.historySpeed.append(speed)
if self.historySpeed.count > self.averageNumber {
self.historySpeed.removeFirst()
}
}
}
init() {
}
}
public class OGRotatiometer {
private let averageNumber = Occupancy.framesUsedForRotation
private var history = [simd_float3]()
private var lastEntry: simd_float3?
private var lastEntryTime: Date?
private let accessQueue = DispatchQueue(label: "OGRotatiometer.access", qos: .userInteractive)
public var average: simd_float3 {
let oneFrameTime = Float32(1) / Float32(Occupancy.framesPerSec)
var retValue: simd_float3?
accessQueue.sync {
let atAtime = Date()
if let lastEntryTime = self.lastEntryTime {
let elapsedTime = Float(atAtime.timeIntervalSince(lastEntryTime))
if elapsedTime > 2*oneFrameTime && !self.history.isEmpty {
// the array was not refresh -> drop the oldest value
self.history.removeFirst()
}
}
let nbcount = self.history.count
if nbcount > 0 {
let averageCoef = Float32(1) / Float32(nbcount)
retValue = history.reduce(simd_float3(), +) * simd_float3(averageCoef, averageCoef, averageCoef)
}
}
return retValue ?? simd_float3()
}
public func setNewRotation(_ eulerRotation: simd_float3) {
let atAtime = Date()
accessQueue.async {
if let lastEntry = self.lastEntry, let lastEntryTime = self.lastEntryTime {
var deltaRotation = eulerRotation - lastEntry
if deltaRotation.y > 2*Float.pi {
deltaRotation.y -= 2*Float.pi
} else if deltaRotation.y < -2*Float.pi {
deltaRotation.y += 2*Float.pi
}
if deltaRotation.y > Float.pi {
deltaRotation.y -= (2 * Float.pi)
} else if deltaRotation.y < -Float.pi {
deltaRotation.y = 2 * Float.pi + deltaRotation.y
}
let elapsedTime = Float(atAtime.timeIntervalSince(lastEntryTime))
let eulerRotationPerSecond = elapsedTime != 0 ? deltaRotation / elapsedTime : simd_float3(repeating: 3)
self.history.append(eulerRotationPerSecond)
if self.history.count > self.averageNumber {
self.history.removeFirst()
}
}
self.lastEntry = eulerRotation
self.lastEntryTime = atAtime
}
}
init() {
}
}
| 412 | 0.947461 | 1 | 0.947461 | game-dev | MEDIA | 0.361015 | game-dev | 0.881056 | 1 | 0.881056 |
Unity-Technologies/PhysicsExamples2D | 1,686 | LowLevel/Projects/Sandbox/Assets/Scenes/Shapes/Bounciness/BouncinessMenu.uxml | <ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" editor-extension-mode="False">
<Style src="project://database/Assets/Sandbox/UI/Styling/SandboxStyleOverrides.uss?fileID=7433441132597879392&guid=e140b35909eadcf48959626f553b2145&type=3#SandboxStyleOverrides"/>
<ui:VisualElement name="VisualElement" picking-mode="Ignore" style="width: 100%; height: 100%; align-items: flex-start; justify-content: flex-end; align-content: auto; padding-left: 8px; padding-bottom: 8px;">
<ui:VisualElement name="menu-region" style="width: 18%; height: auto; margin-top: 2px; margin-right: 2px; margin-bottom: 2px; margin-left: 2px; align-items: auto;">
<ui:TabView tabindex="0" style="width: 100%; height: 100%;">
<ui:Tab label="Bounciness Options" tabindex="0" name="Tab">
<ui:EnumField label="Object Type" value="Center" type="Bounciness+ObjectType, Assembly-CSharp" name="object-type" focusable="false"/>
<ui:Slider label="Gravity Scale" high-value="10" name="gravity-scale" fill="true" show-input-field="true" focusable="false" value="1" low-value="1"/>
</ui:Tab>
</ui:TabView>
<ui:VisualElement name="description" style="flex-grow: 1; flex-shrink: 0; color: rgba(210, 210, 210, 0.5); -unity-text-align: middle-left; align-self: stretch;">
<ui:Label text="..." name="scene-description" style="flex-wrap: nowrap; flex-grow: 1; flex-direction: column; white-space: normal; text-overflow: clip; -unity-text-align: upper-center;"/>
</ui:VisualElement>
</ui:VisualElement>
</ui:VisualElement>
</ui:UXML>
| 412 | 0.839637 | 1 | 0.839637 | game-dev | MEDIA | 0.621326 | game-dev,web-frontend | 0.63614 | 1 | 0.63614 |
drewdru/ponyTown | 22,115 | src/ts/common/pony.ts | import { PONY_WIDTH, PONY_HEIGHT, BLINK_FRAMES, canFly } from '../client/ponyUtils';
import { stand, sneeze, defaultHeadAnimation, defaultBodyFrame, defaultHeadFrame } from '../client/ponyAnimations';
import {
PaletteSpriteBatch, Pony, BodyAnimation, EntityState, SpriteBatch, ExpressionExtra, HeadAnimation, Palette,
PaletteManager, DrawOptions, Rect, EntityFlags, IMap, Entity, DoAction, Muzzle, Expression, isEyeSleeping,
Iris, EntityPlayerState,
} from './interfaces';
import { hasFlag, setFlag } from './utils';
import { blinkFps, PONY_TYPE } from './constants';
import { releasePalettes } from './ponyInfo';
import { createAnEntity, boopSplashRight, boopSplashLeft } from './entities';
import {
createAnimationPlayer, isAnimationPlaying, drawAnimation, playAnimation, updateAnimation, playOneOfAnimations
} from './animationPlayer';
import { blushColor, WHITE, MAGIC_ALPHA, HEARTS_COLOR } from './colors';
import { encodeExpression, decodeExpression } from './encoders/expressionEncoder';
import { toScreenX, toWorldX, toWorldY, toScreenYWithZ } from './positionUtils';
import { getPonyAnimationFrame, getHeadY, drawPony, getPonyHeadPosition, createHeadTransform } from '../client/ponyDraw';
import {
isPonySitting, isPonyFlying, isPonyLying, isPonyStanding, isPonyLandedOrCanLand, isIdle, isIdleAnimation,
isFacingRight, releaseEntity
} from './entityUtils';
import {
getAnimation, getAnimationFrame, setAnimatorState, updateAnimator, createAnimator, AnimatorState,
resetAnimatorState
} from './animator';
import {
trotting, flying, hovering, toBoopState, isFlyingUpOrDown, isFlyingDown, isSittingDown, isSittingUp, swinging,
standing, sitting, lying, swimming, isSwimmingState, swimmingToFlying,
} from '../client/ponyStates';
import { decodePonyInfo } from './compressPony';
import { defaultPonyState, defaultDrawPonyOptions, isStateEqual } from '../client/ponyHelpers';
import {
sneezeAnimation, holdPoofAnimation, heartsAnimation, tearsAnimation, cryAnimation, zzzAnimations, magicAnimation
} from '../client/spriteAnimations';
import { rect } from './rect';
import { addOrRemoveFromEntityList } from './worldMap';
import { hasDrawLight, hasLightSprite } from '../client/draw';
import { ponyColliders, ponyCollidersBounds } from './mixins';
import { PonyTownGame } from '../client/game';
import { playEffect } from '../client/handlers';
import * as sprites from '../generated/sprites';
import { withAlpha } from './color';
const flyY = 15;
const lightExtentX = 100;
const lightExtentY = 70;
const emptyBounds = rect(0, 0, 0, 0);
const bounds = rect(-PONY_WIDTH / 2, -PONY_HEIGHT, PONY_WIDTH, PONY_HEIGHT + 5);
const boundsFly = rect(bounds.x, bounds.y - flyY, bounds.w, bounds.h + flyY);
const lightBounds = makeLightBounds(bounds);
const lightBoundsFly = makeLightBounds(boundsFly);
const interactBounds = rect(-20, -50, 40, 50);
const interactBoundsFly = rect(interactBounds.x, interactBounds.y - flyY, interactBounds.w, interactBounds.h);
const defaultExpr = encodeExpression(undefined);
export function createPony(
id: number, state: EntityState, info: string | Uint8Array | undefined, defaultPalette: Palette,
paletteManager: PaletteManager
): Pony {
const pony: Pony = {
id,
state,
playerState: EntityPlayerState.None,
type: PONY_TYPE,
flags: EntityFlags.Movable | EntityFlags.CanCollide | EntityFlags.Interactive,
expr: defaultExpr,
ponyState: defaultPonyState(),
x: 0,
y: 0,
z: 0,
vx: 0,
vy: 0,
info,
order: 0,
timestamp: 0,
colliders: ponyColliders,
collidersBounds: ponyCollidersBounds,
selected: false,
extra: false,
toy: 0,
swimming: false,
ex: false, // extended data indicator, sent in extended option
inTheAirDelay: 0,
name: undefined,
tag: undefined,
site: undefined,
modInfo: undefined,
hold: 0,
palettePonyInfo: undefined,
headAnimation: undefined,
batch: undefined,
discardBatch: false,
headTime: Math.random() * 5,
blinkTime: 0,
nextBlink: Math.random() * 5,
currentExpression: defaultExpr,
drawingOptions: { ...defaultDrawPonyOptions(), shadow: true, bounce: BETA },
zzzEffect: createAnimationPlayer(defaultPalette),
cryEffect: createAnimationPlayer(defaultPalette),
sneezeEffect: createAnimationPlayer(defaultPalette),
holdPoofEffect: createAnimationPlayer(defaultPalette),
heartsEffect: createAnimationPlayer(defaultPalette),
magicEffect: createAnimationPlayer(paletteManager.addArray(sprites.magic2.palette)),
animator: createAnimator<BodyAnimation>(),
lastX: 0,
lastY: 0,
lastRight: false,
lastState: defaultPonyState(),
initialized: false,
doAction: DoAction.None,
bounds: bounds,
interactBounds: interactBounds,
chatBounds: interactBounds,
lightBounds: emptyBounds,
lightSpriteBounds: emptyBounds,
paletteManager,
lastBoopSplash: 0,
magicColor: 0,
};
pony.ponyState.drawFaceExtra = batch => drawFaceExtra(batch, pony);
return pony;
}
export function isPony(entity: Entity): entity is Pony {
return entity.type === PONY_TYPE;
}
export function isPonyOnTheGround(pony: Pony) {
return !isPonyFlying(pony) && !isFlyingUpOrDown(pony.animator.state);
}
export function getPaletteInfo(pony: Pony) {
return ensurePonyInfoDecoded(pony);
}
export function releasePony(pony: Pony) {
if (pony.ponyState.holding) {
releaseEntity(pony.ponyState.holding);
}
releasePalettePonyInfo(pony);
}
export function canPonyFly(pony: Pony) {
return !!pony.palettePonyInfo && canFly(pony.palettePonyInfo);
}
export function canPonyLie<T>(pony: Pony, map: IMap<T>) {
return !isPonyLying(pony) && (isIdle(pony) || isSittingDown(pony.animator.state) || isFlyingDown(pony.animator.state)) &&
isPonyLandedOrCanLand(pony, map);
}
export function canPonySit<T>(pony: Pony, map: IMap<T>) {
return !isPonySitting(pony) && (isIdle(pony) || isFlyingDown(pony.animator.state)) &&
isPonyLandedOrCanLand(pony, map);
}
export function canPonyStand<T>(pony: Pony, map: IMap<T>) {
return !isPonyStanding(pony) && (isIdleAnimation(pony.ponyState.animation) || isSittingUp(pony.animator.state)) &&
isPonyLandedOrCanLand(pony, map);
}
export function canPonyFlyUp(pony: Pony) {
return !isPonyFlying(pony) && canPonyFly(pony) && !isFlyingUpOrDown(pony.animator.state);
}
export function getPonyChatHeight(pony: Pony) {
const baseHeight = 2;
const state = pony.ponyState;
if (pony.animator.state === trotting) {
return baseHeight;
} else if (pony.animator.state === flying || pony.animator.state === hovering) {
return baseHeight - 16;
} else {
const frame = getPonyAnimationFrame(state.animation, state.animationFrame, defaultBodyFrame);
const animation = state.headAnimation || defaultHeadAnimation;
const headFrame = getPonyAnimationFrame(animation, state.headAnimationFrame, defaultHeadFrame);
return baseHeight + getHeadY(frame, headFrame);
}
}
export function updatePonyInfo(pony: Pony, info: string | Uint8Array, apply: () => void) {
pony.info = info;
if (pony.palettePonyInfo !== undefined) {
releasePalettePonyInfo(pony);
ensurePonyInfoDecoded(pony);
pony.discardBatch = true;
if (isPonyFlying(pony) && !canPonyFly(pony)) {
DEVELOPMENT && console.warn('Force land');
pony.state = setFlag(pony.state, EntityState.PonyFlying, false);
resetAnimatorState(pony.animator);
}
apply();
}
}
export function ensurePonyInfoDecoded(pony: Pony) {
if (pony.info !== undefined && pony.palettePonyInfo === undefined) {
pony.palettePonyInfo = decodePonyInfo(pony.info, pony.paletteManager);
const wingType = pony.palettePonyInfo.wings && pony.palettePonyInfo.wings.type || 0;
pony.animator.variant = wingType === 4 ? 'bug' : '';
pony.ponyState.blushColor = blushColor(pony.palettePonyInfo.coatPalette.colors[1]);
pony.magicColor = withAlpha(pony.palettePonyInfo.magicColorValue, MAGIC_ALPHA);
}
return pony.palettePonyInfo!;
}
export function invalidatePalettesForPony(pony: Pony) {
pony.discardBatch = true;
}
export function doBoopPonyAction(game: PonyTownGame, pony: Pony) {
doPonyAction(pony, DoAction.Boop);
if (pony.swimming && pony.lastBoopSplash < performance.now()) {
if (isFacingRight(pony)) {
playEffect(game, pony, boopSplashRight.type);
} else {
playEffect(game, pony, boopSplashLeft.type);
}
pony.lastBoopSplash = performance.now() + 800;
}
}
export function doPonyAction(pony: Pony, action: DoAction) {
pony.doAction = action;
}
export function setPonyExpression(pony: Pony, expr: number) {
pony.expr = expr;
}
export function hasExtendedInfo(pony: Pony) {
return pony.ex;
}
export function hasHeadAnimation(pony: Pony) {
return pony.headAnimation !== undefined;
}
export function setHeadAnimation(pony: Pony, headAnimation: HeadAnimation | undefined) {
if (pony.headAnimation !== headAnimation) {
pony.headTime = 0;
pony.headAnimation = headAnimation;
}
}
export function drawPonyEntity(batch: PaletteSpriteBatch, pony: Pony, drawOptions: DrawOptions) {
if (pony.discardBatch && pony.batch !== undefined) {
batch.releaseBatch(pony.batch);
pony.batch = undefined;
pony.discardBatch = false;
}
if (pony.batch !== undefined) {
batch.drawBatch(pony.batch);
} else if (pony.palettePonyInfo !== undefined) {
let swimming = false;
if (isSwimmingState(pony.animator.state)) {
if (pony.animator.state === swimmingToFlying) {
swimming = pony.animator.time < 0.4;
} else {
swimming = true;
}
}
const createBatch = pony.vx === 0 && pony.vy === 0 && !swimming;
const right = isFacingRight(pony);
if (createBatch) {
batch.startBatch();
}
batch.save();
transformBatch(batch, pony);
const options = pony.drawingOptions;
options.flipped = right;
options.selected = pony.selected === true;
options.extra = pony.extra;
options.toy = pony.toy;
options.swimming = swimming;
options.shadow = !pony.swimming;
options.gameTime = drawOptions.gameTime + pony.id * 0.1;
options.shadowColor = drawOptions.shadowColor;
const ponyState = pony.ponyState;
drawPony(batch, pony.palettePonyInfo, ponyState, 0, 0, options);
if (
isAnimationPlaying(pony.zzzEffect) || isAnimationPlaying(pony.sneezeEffect) ||
isAnimationPlaying(pony.holdPoofEffect) || isAnimationPlaying(pony.heartsEffect) ||
isAnimationPlaying(pony.magicEffect)
) {
const { x, y } = getPonyHeadPosition(pony.ponyState, 0, 0);
const right = isFacingRight(pony);
const flip = right ? !ponyState.headTurned : ponyState.headTurned;
batch.multiplyTransform(createHeadTransform(undefined, x, y, ponyState));
drawAnimation(batch, pony.zzzEffect, 0, 0, WHITE, flip);
drawAnimation(batch, pony.sneezeEffect, 0, 0, WHITE, flip);
drawAnimation(batch, pony.holdPoofEffect, 0, 0, WHITE, flip);
drawAnimation(batch, pony.heartsEffect, 0, 0, HEARTS_COLOR, flip);
if (pony.magicEffect.currentAnimation !== undefined) {
drawAnimation(batch, pony.magicEffect, 0, 0, pony.magicColor, flip);
const sprite = sprites.magic3.frames[pony.magicEffect.frame];
sprite && batch.drawSprite(sprite, WHITE, pony.heartsEffect.palette, 0, 0);
}
}
batch.restore();
if (createBatch) {
pony.batch = batch.finishBatch();
pony.lastX = toScreenX(pony.x);
pony.lastY = toScreenYWithZ(pony.y, pony.z);
pony.lastRight = right;
pony.zzzEffect.dirty = false;
pony.cryEffect.dirty = false;
pony.sneezeEffect.dirty = false;
pony.holdPoofEffect.dirty = false;
pony.heartsEffect.dirty = false;
pony.magicEffect.dirty = false;
Object.assign(pony.lastState, ponyState);
}
}
}
const magickLightSizes = [
0, 1.02, // fade-in
0.97, 0.94, 0.91, 0.94, 0.97, 1.00, // loop
0.97, 0.94, 0.91, // fade-out
];
export function drawPonyEntityLight(batch: SpriteBatch, pony: Pony, options: DrawOptions) {
const ponyState = pony.ponyState;
const holding = ponyState.holding;
const drawHolding = holding !== undefined && holding.drawLight !== undefined;
const drawMagic = pony.magicEffect.currentAnimation !== undefined;
const draw = drawHolding || drawMagic;
if (draw) {
batch.save();
transformBatch(batch, pony);
const { x, y } = getPonyHeadPosition(ponyState, 0, 0);
batch.multiplyTransform(createHeadTransform(undefined, x, y, ponyState));
if (drawHolding) {
holding!.x = toWorldX(holding!.pickableX!);
holding!.y = toWorldY(holding!.pickableY!);
holding!.drawLight!(batch, options);
}
if (drawMagic) {
const size = 200 * (magickLightSizes[pony.magicEffect.frame] || 0);
batch.drawImage(WHITE, -1, -1, 2, 2, 30 - size / 2, 27 - size / 2, size, size);
}
batch.restore();
}
}
export function drawPonyEntityLightSprite(batch: SpriteBatch, pony: Pony, options: DrawOptions) {
const ponyState = pony.ponyState;
const holding = ponyState.holding;
const drawHolding = holding !== undefined && holding.drawLightSprite !== undefined;
// const drawMagic = pony.magicEffect.currentAnimation !== undefined;
const draw = drawHolding; // || drawMagic;
if (draw) {
batch.save();
transformBatch(batch, pony);
const { x, y } = getPonyHeadPosition(ponyState, 0, 0);
batch.multiplyTransform(createHeadTransform(undefined, x, y, ponyState));
if (drawHolding) {
holding!.x = toWorldX(holding!.pickableX!);
holding!.y = toWorldY(holding!.pickableY!);
holding!.drawLightSprite!(batch, options);
}
// if (drawMagic) {
// const frame = pony.magicEffect.frame;
// const sprite = sprites.magic2_light.frames[frame];
// batch.drawSprite(sprite, WHITE, 0, 0);
// }
batch.restore();
}
}
export function flagsToState(state: EntityState, moving: boolean, isSwimming: boolean): AnimatorState<BodyAnimation> {
const ponyState = state & EntityState.PonyStateMask;
if (isSwimming) {
return swimming;
} else if (moving) {
if (ponyState === EntityState.PonyFlying) {
return flying;
} else {
return trotting;
}
} else {
switch (ponyState) {
case EntityState.PonyStanding: return standing;
case EntityState.PonyWalking: return trotting;
case EntityState.PonyTrotting: return trotting;
case EntityState.PonySitting: return sitting;
case EntityState.PonyLying: return lying;
case EntityState.PonyFlying: return hovering;
default:
throw new Error(`Invalid pony state (${ponyState})`);
}
}
}
export function updatePonyEntity(pony: Pony, delta: number, gameTime: number, safe: boolean) {
// update state
const state = pony.ponyState;
const walking = pony.vx !== 0 || pony.vy !== 0;
const animationState = flagsToState(pony.state, walking, pony.swimming);
if (pony.inTheAirDelay > 0) {
pony.inTheAirDelay -= delta;
}
if (pony.doAction !== DoAction.None) {
switch (pony.doAction) {
case DoAction.Boop:
setAnimatorState(pony.animator, toBoopState(animationState) || animationState);
break;
case DoAction.Swing:
setAnimatorState(pony.animator, swinging);
break;
case DoAction.HoldPoof:
playAnimation(pony.holdPoofEffect, holdPoofAnimation);
break;
default:
if (DEVELOPMENT) {
console.error(`Invalid DoAction: ${pony.doAction}`);
}
}
pony.doAction = DoAction.None;
} else {
setAnimatorState(pony.animator, animationState);
}
// head
pony.headTime += delta;
if (pony.headAnimation !== undefined) {
const frame = Math.floor(pony.headTime * pony.headAnimation.fps);
if (frame >= pony.headAnimation.frames.length && !pony.headAnimation.loop) {
pony.headAnimation = undefined;
state.headAnimationFrame = 0;
} else {
state.headAnimationFrame = frame % pony.headAnimation.frames.length;
}
}
if (state.headAnimation !== pony.headAnimation) {
state.headAnimation = pony.headAnimation;
if (pony.headAnimation === sneeze) {
playAnimation(pony.sneezeEffect, sneezeAnimation);
}
}
// effects / expressions
if (pony.currentExpression !== pony.expr) {
updatePonyExpression(pony, pony.expr, safe);
}
if ((pony.state & EntityState.Magic) !== 0) {
playAnimation(pony.magicEffect, magicAnimation);
} else {
playAnimation(pony.magicEffect, undefined);
}
updateAnimation(pony.zzzEffect, delta);
updateAnimation(pony.cryEffect, delta);
updateAnimation(pony.sneezeEffect, delta);
updateAnimation(pony.holdPoofEffect, delta);
updateAnimation(pony.heartsEffect, delta);
updateAnimation(pony.magicEffect, delta);
// holding
const holdingUpdated =
state.holding !== undefined &&
state.holding.update !== undefined &&
state.holding.update(delta, gameTime);
// blink
pony.blinkTime += delta;
if ((pony.blinkTime - pony.nextBlink) > 1) {
pony.nextBlink = pony.blinkTime + Math.random() * 2 + 3;
}
// update animator
updateAnimator(pony.animator, delta);
// update state
const blinkFrame = Math.floor((pony.blinkTime - pony.nextBlink) * blinkFps);
state.blinkFrame = blinkFrame < BLINK_FRAMES.length ? BLINK_FRAMES[blinkFrame] : 1;
state.headTurned = (pony.state & EntityState.HeadTurned) !== 0;
state.animation = getAnimation(pony.animator) || stand;
state.animationFrame = getAnimationFrame(pony.animator);
// randomize animator time at startup
if (!pony.initialized) {
pony.initialized = true;
updateAnimator(pony.animator, Math.random() * 2);
}
// discard batch if outdated
if (pony.batch !== undefined) {
const options = pony.drawingOptions;
const right = isFacingRight(pony);
if (
holdingUpdated ||
toScreenX(pony.x) !== pony.lastX || toScreenYWithZ(pony.y, pony.z) !== pony.lastY ||
pony.lastRight !== right ||
pony.zzzEffect.dirty || pony.cryEffect.dirty || pony.sneezeEffect.dirty || pony.holdPoofEffect.dirty ||
pony.heartsEffect.dirty || pony.magicEffect.dirty ||
options.flipped !== right || options.selected !== pony.selected || options.extra !== pony.extra ||
options.toy !== pony.toy ||
!isStateEqual(pony.lastState, state)
) {
pony.discardBatch = true;
}
}
// update bounds
const flying = isPonyFlying(pony);
const flyingUpOrDown = isFlyingUpOrDown(pony.animator.state);
const flyingOrFlyingUpOrDown = flying || flyingUpOrDown;
pony.bounds = flyingOrFlyingUpOrDown ? boundsFly : bounds;
pony.interactBounds = flying ? interactBoundsFly : interactBounds;
pony.lightBounds = flyingOrFlyingUpOrDown ? lightBoundsFly : lightBounds;
pony.lightSpriteBounds = flyingOrFlyingUpOrDown ? lightBoundsFly : lightBounds;
}
export function updatePonyHold(pony: Pony, game: PonyTownGame) {
const ponyState = pony.ponyState;
const hadLight = hasDrawLight(pony);
const hadLightSprite = hasLightSprite(pony);
if (pony.hold !== 0) {
if (ponyState.holding === undefined) {
ponyState.holding = createAnEntity(pony.hold, 0, 0, 0, {}, pony.paletteManager, game);
} else if (ponyState.holding.type !== pony.hold) {
releaseEntity(ponyState.holding);
ponyState.holding = createAnEntity(pony.hold, 0, 0, 0, {}, pony.paletteManager, game);
}
} else if (ponyState.holding !== undefined) {
releaseEntity(ponyState.holding);
ponyState.holding = undefined;
}
const hasLight = hasDrawLight(pony);
const hasLightSprite1 = hasLightSprite(pony);
addOrRemoveFromEntityList(game.map.entitiesLight, pony, hadLight, hasLight);
addOrRemoveFromEntityList(game.map.entitiesLightSprite, pony, hadLightSprite, hasLightSprite1);
}
function filterExpression(expression: Expression) {
const extra = expression.extra;
const blush = hasFlag(extra, ExpressionExtra.Blush);
if (
blush ||
hasFlag(extra, ExpressionExtra.Hearts) ||
hasFlag(extra, ExpressionExtra.Cry) ||
isEyeSleeping(expression.left) ||
isEyeSleeping(expression.right)
) {
if (expression.muzzle === Muzzle.SmilePant || expression.muzzle === Muzzle.NeutralPant) {
expression.muzzle = Muzzle.Neutral;
}
}
if (
blush ||
expression.muzzle === Muzzle.SmilePant ||
expression.muzzle === Muzzle.NeutralPant
) {
if (expression.leftIris === Iris.Up || expression.rightIris === Iris.Up) {
expression.leftIris = Iris.Forward;
expression.rightIris = Iris.Forward;
}
if (expression.muzzle === Muzzle.SmilePant) {
expression.muzzle = Muzzle.SmileOpen;
} else if (expression.muzzle === Muzzle.NeutralPant) {
expression.muzzle = Muzzle.NeutralOpen2;
}
}
if (blush) {
if (expression.muzzle === Muzzle.SmileOpen2) {
expression.muzzle = Muzzle.SmileOpen;
} else if (expression.muzzle === Muzzle.FrownOpen) {
expression.muzzle = Muzzle.ConcernedOpen;
} else if (expression.muzzle === Muzzle.NeutralOpen2) {
expression.muzzle = Muzzle.Oh;
}
}
}
function updatePonyExpression(pony: Pony, expr: number, safe: boolean) {
const expression = decodeExpression(expr);
pony.currentExpression = pony.expr;
pony.ponyState.expression = expression;
if (expression && safe) {
filterExpression(expression);
}
const extra = (expression && expression.extra) || 0;
if (hasFlag(extra, ExpressionExtra.Cry)) {
playAnimation(pony.cryEffect, cryAnimation);
} else if (hasFlag(extra, ExpressionExtra.Tears)) {
playAnimation(pony.cryEffect, tearsAnimation);
} else {
playAnimation(pony.cryEffect, undefined);
}
if (hasFlag(extra, ExpressionExtra.Zzz)) {
playOneOfAnimations(pony.zzzEffect, zzzAnimations);
} else {
playAnimation(pony.zzzEffect, undefined);
}
if (hasFlag(extra, ExpressionExtra.Hearts)) {
playAnimation(pony.heartsEffect, heartsAnimation);
} else {
playAnimation(pony.heartsEffect, undefined);
}
}
function transformBatch(batch: SpriteBatch | PaletteSpriteBatch, entity: Entity) {
batch.translate(toScreenX(entity.x), toScreenYWithZ(entity.y, entity.z));
batch.scale(isFacingRight(entity) ? -1 : 1, 1);
}
function releasePalettePonyInfo(pony: Pony) {
if (pony.palettePonyInfo !== undefined) {
releasePalettes(pony.palettePonyInfo);
pony.palettePonyInfo = undefined;
}
}
function makeLightBounds({ x, y, w, h }: Rect) {
return rect(x - lightExtentX, y - lightExtentY, w + lightExtentX * 2, h + lightExtentY * 2);
}
function drawFaceExtra(batch: PaletteSpriteBatch, pony: Pony) {
if (isAnimationPlaying(pony.cryEffect)) {
const flip = isFacingRight(pony) ? !pony.ponyState.headTurned : pony.ponyState.headTurned;
const maxY = isPonyLying(pony) ? 62 : (isPonySitting(pony) ? 65 : 0);
drawAnimation(batch, pony.cryEffect, 0, 0, WHITE, flip, maxY);
}
}
| 412 | 0.857217 | 1 | 0.857217 | game-dev | MEDIA | 0.934645 | game-dev | 0.517991 | 1 | 0.517991 |
ServUO/ServUO | 11,292 | Scripts/Services/Seasonal Events/TreasuresOfSorceresDungeon/Spawner.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Server;
using Server.Mobiles;
using Server.Items;
using Server.Commands;
using Server.Gumps;
namespace Server.Engines.SorcerersDungeon
{
public class TOSDSpawner
{
public static void Initialize()
{
CommandSystem.Register("TOSDSpawner", AccessLevel.Administrator, e =>
{
if (e.Mobile is PlayerMobile)
{
if (Instance != null)
{
BaseGump.SendGump(new TOSDSpawnerGump((PlayerMobile)e.Mobile));
}
else
{
e.Mobile.SendMessage("This spawner is not set up at this time. Enabled Treasures of Sorcerer's Dungeon to enable the spawner.");
}
}
});
if (Instance != null)
{
Instance.BeginTimer();
}
}
public static TOSDSpawner Instance { get; set; }
public BaseCreature Boss { get; set; }
public int Index { get; set; }
public int KillCount { get; set; }
public List<BaseCreature> Spawn { get; set; }
public bool Spawning { get; set; }
public Timer Timer { get; set; }
public List<TOSDSpawnEntry> Entries { get; set; }
public TOSDSpawner()
{
Instance = this;
Entries = new List<TOSDSpawnEntry>();
Spawn = new List<BaseCreature>();
BuildEntries();
Activate();
}
private void Activate()
{
foreach (var rec in Entries.Select(e => e.SpawnArea))
{
IPooledEnumerable eable = Map.Ilshenar.GetItemsInBounds(rec);
foreach (Item item in eable)
{
if (item is XmlSpawner)
{
((XmlSpawner)item).DoReset = true;
}
}
}
}
public void Deactivate()
{
foreach (var rec in Entries.Select(e => e.SpawnArea))
{
IPooledEnumerable eable = Map.Ilshenar.GetItemsInBounds(rec);
foreach (Item item in eable)
{
if (item is XmlSpawner)
{
((XmlSpawner)item).DoRespawn = true;
}
}
}
EndTimer();
foreach (var bc in Spawn)
{
bc.Delete();
}
Instance = null;
}
public void BeginTimer()
{
EndTimer();
Timer = Timer.DelayCall(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), OnTick);
Timer.Start();
}
public void EndTimer()
{
if (Timer != null)
{
Timer.Stop();
Timer = null;
}
}
private void OnTick()
{
if (Spawning)
{
return;
}
if (Boss != null && Boss.Deleted)
{
if (Index == Entries.Count - 1)
{
Index = 0;
}
else
{
Index++;
}
Reset();
}
else if (Boss == null && KillCount >= Entries[Index].ToKill)
{
DoSpawn(Entries[Index].Boss, true);
}
else if (Spawn.Count < Entries[Index].MaxSpawn && (Boss == null || Entries[Index].SpawnArea.Contains(Boss)))
{
Spawning = true;
Timer.DelayCall(TimeSpan.FromSeconds(Utility.RandomMinMax(3, 8)), () =>
{
DoSpawn(Entries[Index].Spawn[Utility.Random(Entries[Index].Spawn.Length)], false);
Spawning = false;
});
}
}
public void DoSpawn(Type t, bool boss)
{
var spawn = Activator.CreateInstance(t) as BaseCreature;
for (int i = 0; i < 20; i++)
{
var p = Map.Ilshenar.GetRandomSpawnPoint(Entries[Index].SpawnArea);
if (Map.Ilshenar.CanSpawnMobile(p))
{
spawn.MoveToWorld(p, Map.Ilshenar);
if (boss)
{
Boss = spawn;
}
else
{
AddSpawn(spawn);
}
return;
}
}
spawn.Delete();
}
public void AddSpawn(BaseCreature bc)
{
Spawn.Add(bc);
}
public void OnCreatureDeath(BaseCreature bc)
{
if (Spawn.Contains(bc))
{
Spawn.Remove(bc);
KillCount++;
}
}
public void Reset()
{
ColUtility.Free(Spawn);
Boss = null;
Spawning = false;
KillCount = 0;
EndTimer();
Timer.DelayCall(TimeSpan.FromMinutes(Utility.RandomMinMax(1, 3)), () =>
{
BeginTimer();
});
}
public void Serialize(GenericWriter writer)
{
writer.Write(0);
writer.Write(Boss);
writer.Write(KillCount);
writer.Write(Index);
writer.Write(Spawn.Count);
foreach (var bc in Spawn)
{
writer.Write(bc);
}
}
public void Deserialize(GenericReader reader)
{
reader.ReadInt(); // version
Boss = reader.ReadMobile() as BaseCreature;
KillCount = reader.ReadInt();
Index = reader.ReadInt();
int count = reader.ReadInt();
for(int i = 0; i < count; i++)
{
var bc = reader.ReadMobile() as BaseCreature;
if(bc != null)
{
AddSpawn(bc);
}
}
}
public void BuildEntries()
{
Entries.Add(new TOSDSpawnEntry(typeof(NightmareFairy), new Type[] { typeof(Zombie), typeof(Skeleton), typeof(Gargoyle), typeof(Lich), typeof(LichLord) }, new Rectangle2D(327, 26, 29, 32), 80, 15));
Entries.Add(new TOSDSpawnEntry(typeof(JackInTheBox), new Type[] { typeof(Zombie), typeof(Skeleton), typeof(Gargoyle), typeof(Lich), typeof(LichLord) }, new Rectangle2D(296, 10, 17, 26), 80, 15));
Entries.Add(new TOSDSpawnEntry(typeof(HeadlessElf), new Type[] { typeof(Zombie), typeof(Skeleton), typeof(Gargoyle), typeof(Lich), typeof(LichLord) }, new Rectangle2D(271, 4, 20, 33), 80, 15));
Entries.Add(new TOSDSpawnEntry(typeof(AbominableSnowman), new Type[] { typeof(Zombie), typeof(Skeleton), typeof(Gargoyle), typeof(Lich), typeof(LichLord) }, new Rectangle2D(227, 39, 21, 19), 80, 15));
Entries.Add(new TOSDSpawnEntry(typeof(TwistedHolidayTree), new Type[] { typeof(Zombie), typeof(Skeleton), typeof(Gargoyle), typeof(Lich), typeof(LichLord) }, new Rectangle2D(251, 68, 25, 32), 80, 15));
Entries.Add(new TOSDSpawnEntry(typeof(RabidReindeer), new Type[] { typeof(Zombie), typeof(Skeleton), typeof(Gargoyle), typeof(Lich), typeof(LichLord) }, new Rectangle2D(144, 5, 23, 19), 80, 15));
Entries.Add(new TOSDSpawnEntry(typeof(GarishGingerman), new Type[] { typeof(Zombie), typeof(Skeleton), typeof(Gargoyle), typeof(Lich), typeof(LichLord) }, new Rectangle2D(60, 53, 13, 34), 80, 15));
Entries.Add(new TOSDSpawnEntry(typeof(StockingSerpent), new Type[] { typeof(Zombie), typeof(Skeleton), typeof(Gargoyle), typeof(Lich), typeof(LichLord) }, new Rectangle2D(152, 48, 16, 23), 80, 15));
Entries.Add(new TOSDSpawnEntry(typeof(JackThePumpkinKing), new Type[] { typeof(Zombie), typeof(Skeleton), typeof(Gargoyle), typeof(Lich), typeof(LichLord) }, new Rectangle2D(291, 73, 37, 36), 80, 15));
}
}
public class TOSDSpawnEntry
{
public Type Boss { get; set; }
public Type[] Spawn { get; set; }
public Rectangle2D SpawnArea { get; set; }
public int ToKill { get; set; }
public int MaxSpawn { get; set; }
public TOSDSpawnEntry(Type boss, Type[] spawn, Rectangle2D area, int toKill, int maxSpawn)
{
Boss = boss;
Spawn = spawn;
SpawnArea = area;
ToKill = toKill;
MaxSpawn = maxSpawn;
}
}
public class TOSDSpawnerGump : BaseGump
{
public TOSDSpawnerGump(PlayerMobile pm)
: base(pm, 50, 50)
{
}
public override void AddGumpLayout()
{
AddBackground(0, 0, 500, 300, 9300);
AddHtml(0, 10, 500, 20, Center("Treasures of Sorcerer's Dungeon Spawner"), false, false);
var spawner = TOSDSpawner.Instance;
if (spawner == null)
{
AddHtml(10, 40, 150, 20, "Spawner Disabled", false, false);
}
else
{
int y = 60;
AddLabel(10, 40, 0, "Go");
AddLabel(40, 40, 0, "Boss");
AddLabel(240, 40, 0, "Current");
AddLabel(320, 40, 0, "Max");
AddLabel(400, 40, 0, "Killed");
for (int i = 0; i < spawner.Entries.Count; i++)
{
var entry = spawner.Entries[i];
var hue = i == spawner.Index ? "green" : "red";
AddButton(7, y, 1531, 1532, i + 100, GumpButtonType.Reply, 0);
AddHtml(40, y, 200, 20, Color(hue, entry.Boss.Name), false, false);
AddHtml(320, y, 80, 20, Color(hue, entry.MaxSpawn.ToString()), false, false);
if (hue == "green")
{
AddHtml(240, y, 80, 20, Color(hue, spawner.Spawn.Count.ToString()), false, false);
AddHtml(400, y, 80, 20, Color(hue, spawner.KillCount.ToString()), false, false);
}
else
{
AddHtml(240, y, 80, 20, Color(hue, "0"), false, false);
AddHtml(400, y, 80, 20, Color(hue, "0"), false, false);
}
y += 22;
}
}
}
public override void OnResponse(RelayInfo info)
{
if (info.ButtonID > 0)
{
int id = info.ButtonID - 100;
var spawner = TOSDSpawner.Instance;
if (spawner != null && id >= 0 && id < spawner.Entries.Count)
{
var entry = spawner.Entries[id];
do
{
var p = Map.Ilshenar.GetRandomSpawnPoint(entry.SpawnArea);
if (Map.Ilshenar.CanSpawnMobile(p))
{
User.MoveToWorld(p, Map.Ilshenar);
Refresh();
break;
}
}
while (true);
}
}
}
}
}
| 412 | 0.947775 | 1 | 0.947775 | game-dev | MEDIA | 0.974823 | game-dev | 0.855688 | 1 | 0.855688 |
JoeyDeVries/Lucid | 3,483 | Includes/Box2D/Collision/Shapes/b2PolygonShape.h | /*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef B2_POLYGON_SHAPE_H
#define B2_POLYGON_SHAPE_H
#include <Box2D/Collision/Shapes/b2Shape.h>
/// A convex polygon. It is assumed that the interior of the polygon is to
/// the left of each edge.
/// Polygons have a maximum number of vertices equal to b2_maxPolygonVertices.
/// In most cases you should not need many vertices for a convex polygon.
class b2PolygonShape : public b2Shape
{
public:
b2PolygonShape();
/// Implement b2Shape.
b2Shape* Clone(b2BlockAllocator* allocator) const;
/// @see b2Shape::GetChildCount
int32 GetChildCount() const;
/// Create a convex hull from the given array of local points.
/// The count must be in the range [3, b2_maxPolygonVertices].
/// @warning the points may be re-ordered, even if they form a convex polygon
/// @warning collinear points are handled but not removed. Collinear points
/// may lead to poor stacking behavior.
void Set(const b2Vec2* points, int32 count);
/// Build vertices to represent an axis-aligned box centered on the local origin.
/// @param hx the half-width.
/// @param hy the half-height.
void SetAsBox(float32 hx, float32 hy);
/// Build vertices to represent an oriented box.
/// @param hx the half-width.
/// @param hy the half-height.
/// @param center the center of the box in local coordinates.
/// @param angle the rotation of the box in local coordinates.
void SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle);
/// @see b2Shape::TestPoint
bool TestPoint(const b2Transform& transform, const b2Vec2& p) const;
/// Implement b2Shape.
bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
const b2Transform& transform, int32 childIndex) const;
/// @see b2Shape::ComputeAABB
void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const;
/// @see b2Shape::ComputeMass
void ComputeMass(b2MassData* massData, float32 density) const;
/// Get the vertex count.
int32 GetVertexCount() const { return m_count; }
/// Get a vertex by index.
const b2Vec2& GetVertex(int32 index) const;
/// Validate convexity. This is a very time consuming operation.
/// @returns true if valid
bool Validate() const;
b2Vec2 m_centroid;
b2Vec2 m_vertices[b2_maxPolygonVertices];
b2Vec2 m_normals[b2_maxPolygonVertices];
int32 m_count;
};
inline b2PolygonShape::b2PolygonShape()
{
m_type = e_polygon;
m_radius = b2_polygonRadius;
m_count = 0;
m_centroid.SetZero();
}
inline const b2Vec2& b2PolygonShape::GetVertex(int32 index) const
{
b2Assert(0 <= index && index < m_count);
return m_vertices[index];
}
#endif
| 412 | 0.946264 | 1 | 0.946264 | game-dev | MEDIA | 0.930118 | game-dev | 0.934426 | 1 | 0.934426 |
David-Durst/csknow | 12,231 | analytics/src/lib/queries/moments/engagement.cpp | //
// Created by durst on 9/11/22.
//
#include "queries/moments/engagement.h"
#include "queries/lookback.h"
#include "indices/build_indexes.h"
#include <omp.h>
#include "queries/parser_constants.h"
struct EngagementPlayers {
int64_t attacker, victim;
bool operator<(const EngagementPlayers & other) const {
return attacker < other.attacker ||
(attacker == other.attacker && victim < other.victim);
}
};
struct EngagementData {
int64_t startTick = INVALID_ID, endTick = INVALID_ID;
vector<int64_t> hurtTickIds, hurtIds;
};
void finishEngagement(const Rounds &rounds, const Ticks &ticks,
vector<vector<int64_t>> & tmpStartTickId, vector<vector<int64_t>> & tmpEndTickId,
vector<vector<int64_t>> & tmpLength, vector<vector<vector<int64_t>>> & tmpPlayerId,
vector<vector<vector<EngagementRole>>> & tmpRole,
vector<vector<vector<int64_t>>> & tmpHurtTickIds, vector<vector<vector<int64_t>>> & tmpHurtIds,
int threadNum, const TickRates &tickRates,
const EngagementPlayers &curPair, const EngagementData &eData) {
// use pre and post periods to track behavior around engagement
int64_t preEngagementStart = getLookbackDemoTick(rounds, ticks,
eData.startTick, tickRates,
PRE_ENGAGEMENT_SECONDS);
int64_t postEngagementEnd = getLookforwardDemoTick(rounds, ticks,
eData.endTick, tickRates,
POST_ENGAGEMENT_SECONDS);
tmpStartTickId[threadNum].push_back(preEngagementStart);
tmpEndTickId[threadNum].push_back(postEngagementEnd);
tmpLength[threadNum].push_back(postEngagementEnd - preEngagementStart + 1);
tmpPlayerId[threadNum].push_back({curPair.attacker, curPair.victim});
tmpRole[threadNum].push_back({EngagementRole::Attacker, EngagementRole::Victim});
tmpHurtTickIds[threadNum].push_back(eData.hurtTickIds);
tmpHurtIds[threadNum].push_back(eData.hurtIds);
}
EngagementResult queryEngagementResult(const Games & games, const Rounds & rounds, const Ticks & ticks, const Hurt & hurt) {
int numThreads = omp_get_max_threads();
vector<vector<int64_t>> tmpRoundIds(numThreads);
vector<vector<int64_t>> tmpRoundStarts(numThreads);
vector<vector<int64_t>> tmpRoundSizes(numThreads);
vector<vector<int64_t>> tmpStartTickId(numThreads);
vector<vector<int64_t>> tmpEndTickId(numThreads);
vector<vector<int64_t>> tmpLength(numThreads);
vector<vector<vector<int64_t>>> tmpPlayerId(numThreads);
vector<vector<vector<EngagementRole>>> tmpRole(numThreads);
vector<vector<vector<int64_t>>> tmpHurtTickIds(numThreads);
vector<vector<vector<int64_t>>> tmpHurtIds(numThreads);
// for each round
// track events for each pairs of player.
// start a new event for a pair when hurt event with no prior one or far away prior one
// clear out all hurt events on end of round
//#pragma omp parallel for
for (int64_t roundIndex = 0; roundIndex < rounds.size; roundIndex++) {
int threadNum = omp_get_thread_num();
tmpRoundIds[threadNum].push_back(roundIndex);
tmpRoundStarts[threadNum].push_back(static_cast<int64_t>(tmpStartTickId[threadNum].size()));
TickRates tickRates = computeTickRates(games, rounds, roundIndex);
map<EngagementPlayers, EngagementData> curEngagements;
for (int64_t tickIndex = rounds.ticksPerRound[roundIndex].minId;
tickIndex <= rounds.ticksPerRound[roundIndex].maxId; tickIndex++) {
for (const auto & [_0, _1, hurtIndex] :
ticks.hurtPerTick.intervalToEvent.findOverlapping(tickIndex, tickIndex)) {
if (!isDemoEquipmentAGun(hurt.weapon[hurtIndex])) {
continue;
}
EngagementPlayers curPair{hurt.attacker[hurtIndex], hurt.victim[hurtIndex]};
// start new engagement if none present
if (curEngagements.find(curPair) == curEngagements.end()) {
curEngagements[curPair] = {tickIndex, tickIndex,
{tickIndex}, {hurtIndex}};
}
else {
EngagementData & eData = curEngagements[curPair];
// if current engagement hasn't ended, extend it
// since new event will get PRE_ENGAGEMENT_SECONDS buffer and old event will get
// POST_ENGAGEMENT_BUFFER, must consider entire region as restart time to prevent
// overlapping event
if (secondsBetweenTicks(ticks, tickRates, eData.endTick, tickIndex)
<= PRE_ENGAGEMENT_SECONDS + POST_ENGAGEMENT_SECONDS) {
eData.endTick = tickIndex;
eData.hurtTickIds.push_back(tickIndex);
eData.hurtIds.push_back(hurtIndex);
}
// if current engagement ended, finish it and start new one
else {
finishEngagement(rounds, ticks, tmpStartTickId, tmpEndTickId,
tmpLength, tmpPlayerId, tmpRole,
tmpHurtTickIds, tmpHurtIds, threadNum, tickRates,
curPair, eData);
eData = {tickIndex, tickIndex,
{tickIndex}, {hurtIndex}};
}
}
}
}
// at end of round, clear all engagements
for (const auto & engagement : curEngagements) {
finishEngagement(rounds, ticks, tmpStartTickId, tmpEndTickId,
tmpLength, tmpPlayerId, tmpRole,
tmpHurtTickIds, tmpHurtIds, threadNum, tickRates,
engagement.first, engagement.second);
}
tmpRoundSizes[threadNum].push_back(static_cast<int64_t>(tmpStartTickId[threadNum].size()) - tmpRoundStarts[threadNum].back());
}
EngagementResult result;
mergeThreadResults(numThreads, result.rowIndicesPerRound, tmpRoundIds, tmpRoundStarts, tmpRoundSizes,
result.startTickId, result.size,
[&](int64_t minThreadId, int64_t tmpRowId) {
result.startTickId.push_back(tmpStartTickId[minThreadId][tmpRowId]);
result.endTickId.push_back(tmpEndTickId[minThreadId][tmpRowId]);
result.tickLength.push_back(tmpLength[minThreadId][tmpRowId]);
result.playerId.push_back(tmpPlayerId[minThreadId][tmpRowId]);
result.role.push_back(tmpRole[minThreadId][tmpRowId]);
result.hurtTickIds.push_back(tmpHurtTickIds[minThreadId][tmpRowId]);
result.hurtIds.push_back(tmpHurtIds[minThreadId][tmpRowId]);
});
vector<std::reference_wrapper<const vector<int64_t>>> foreignKeyCols{result.startTickId, result.endTickId};
result.engagementsPerTick = buildIntervalIndex(foreignKeyCols, result.size);
return result;
}
void EngagementResult::computePercentMatchNearestCrosshair(const Rounds & rounds, const Ticks & ticks,
const PlayerAtTick & playerAtTick,
const csknow::feature_store::FeatureStoreResult & featureStoreResult) {
map<int64_t, int64_t> engagementToNumCorrectTicksCurTick, engagementToNumCorrectTicks500ms, engagementToNumCorrectTicks1s, engagementToNumCorrectTicks2s;
for (int64_t roundIndex = 0; roundIndex < rounds.size; roundIndex++) {
for (int64_t tickIndex = rounds.ticksPerRound[roundIndex].minId;
tickIndex <= rounds.ticksPerRound[roundIndex].maxId; tickIndex++) {
map<int64_t, int64_t> playerToVictimCurTick;
map<int64_t, int64_t> playerToEngagementCurTick;
for (const auto & [_0, _1, engagementIndex] :
engagementsPerTick.intervalToEvent.findOverlapping(tickIndex, tickIndex)) {
playerToVictimCurTick[playerId[engagementIndex][0]] = playerId[engagementIndex][1];
playerToEngagementCurTick[playerId[engagementIndex][0]] = engagementIndex;
if (engagementToNumCorrectTicks2s.find(engagementIndex) == engagementToNumCorrectTicks2s.end()) {
engagementToNumCorrectTicksCurTick[engagementIndex] = 0;
engagementToNumCorrectTicks500ms[engagementIndex] = 0;
engagementToNumCorrectTicks1s[engagementIndex] = 0;
engagementToNumCorrectTicks2s[engagementIndex] = 0;
}
}
for (int64_t patIndex = ticks.patPerTick[tickIndex].minId;
patIndex <= ticks.patPerTick[tickIndex].maxId; patIndex++) {
int64_t attackerId = playerAtTick.playerId[patIndex];
if (playerToVictimCurTick.find(attackerId) != playerToVictimCurTick.end()) {
/*
if (ticks.demoTickNumber[tickIndex] == 5117 && attackerId == 2) {
std::cout << "tick index " << tickIndex << " attacker id " << attackerId
<< " victim id " << playerToVictimCurTick[attackerId] << " nearest crosshair enemy 2s "
<< featureStoreResult.nearestCrosshairEnemy2s[patIndex] << std::endl;
}
*/
int nearestEnemyIndexCurTick = featureStoreResult.nearestCrosshairCurTick[patIndex];
if (featureStoreResult.columnEnemyData[nearestEnemyIndexCurTick].playerId[patIndex] == playerToVictimCurTick[attackerId]) {
engagementToNumCorrectTicksCurTick[playerToEngagementCurTick[attackerId]]++;
}
int nearestEnemyIndex500ms = featureStoreResult.nearestCrosshairEnemy500ms[patIndex];
if (featureStoreResult.columnEnemyData[nearestEnemyIndex500ms].playerId[patIndex] == playerToVictimCurTick[attackerId]) {
engagementToNumCorrectTicks500ms[playerToEngagementCurTick[attackerId]]++;
}
int nearestEnemyIndex1s = featureStoreResult.nearestCrosshairEnemy1s[patIndex];
if (featureStoreResult.columnEnemyData[nearestEnemyIndex1s].playerId[patIndex] == playerToVictimCurTick[attackerId]) {
engagementToNumCorrectTicks1s[playerToEngagementCurTick[attackerId]]++;
}
int nearestEnemyIndex2s = featureStoreResult.nearestCrosshairEnemy2s[patIndex];
if (featureStoreResult.columnEnemyData[nearestEnemyIndex2s].playerId[patIndex] == playerToVictimCurTick[attackerId]) {
engagementToNumCorrectTicks2s[playerToEngagementCurTick[attackerId]]++;
}
}
}
}
}
for (int64_t engagementIndex = 0; engagementIndex < size; engagementIndex++) {
percentMatchNearestCrosshairEnemyCurTick.push_back(
static_cast<double>(engagementToNumCorrectTicksCurTick[engagementIndex]) /
static_cast<double>(tickLength[engagementIndex]));
percentMatchNearestCrosshairEnemy500ms.push_back(
static_cast<double>(engagementToNumCorrectTicks500ms[engagementIndex]) /
static_cast<double>(tickLength[engagementIndex]));
percentMatchNearestCrosshairEnemy1s.push_back(
static_cast<double>(engagementToNumCorrectTicks1s[engagementIndex]) /
static_cast<double>(tickLength[engagementIndex]));
percentMatchNearestCrosshairEnemy2s.push_back(
static_cast<double>(engagementToNumCorrectTicks2s[engagementIndex]) /
static_cast<double>(tickLength[engagementIndex]));
}
} | 412 | 0.756858 | 1 | 0.756858 | game-dev | MEDIA | 0.847501 | game-dev | 0.921408 | 1 | 0.921408 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.