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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
magefree/mage | 1,353 | Mage.Sets/src/mage/cards/w/WaterveilCavern.java |
package mage.cards.w;
import java.util.UUID;
import mage.abilities.Ability;
import mage.abilities.effects.common.DontUntapInControllersNextUntapStepSourceEffect;
import mage.abilities.mana.BlackManaAbility;
import mage.abilities.mana.BlueManaAbility;
import mage.abilities.mana.ColorlessManaAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
/**
*
* @author Loki
*/
public final class WaterveilCavern extends CardImpl {
public WaterveilCavern(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.LAND},"");
// Tap: Add 1.
this.addAbility(new ColorlessManaAbility());
// Tap: Add Blue or Black. Waterveil Cavern doesn't untap during your next untap step.
Ability blueManaAbility = new BlueManaAbility();
blueManaAbility.addEffect(new DontUntapInControllersNextUntapStepSourceEffect());
this.addAbility(blueManaAbility);
Ability blackManaAbility = new BlackManaAbility();
blackManaAbility.addEffect(new DontUntapInControllersNextUntapStepSourceEffect());
this.addAbility(blackManaAbility);
}
private WaterveilCavern(final WaterveilCavern card) {
super(card);
}
@Override
public WaterveilCavern copy() {
return new WaterveilCavern(this);
}
}
| 412 | 0.970361 | 1 | 0.970361 | game-dev | MEDIA | 0.94528 | game-dev | 0.981878 | 1 | 0.981878 |
magefree/mage | 2,664 | Mage.Sets/src/mage/cards/a/AngelicSellSword.java | package mage.cards.a;
import mage.MageInt;
import mage.MageObject;
import mage.abilities.Ability;
import mage.abilities.common.AttacksTriggeredAbility;
import mage.abilities.common.EntersBattlefieldThisOrAnotherTriggeredAbility;
import mage.abilities.condition.Condition;
import mage.abilities.effects.common.CreateTokenEffect;
import mage.abilities.effects.common.DrawCardSourceControllerEffect;
import mage.abilities.keyword.FlyingAbility;
import mage.abilities.keyword.VigilanceAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.filter.StaticFilters;
import mage.game.Game;
import mage.game.permanent.token.MercenaryToken;
import java.util.Optional;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class AngelicSellSword extends CardImpl {
public AngelicSellSword(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{4}{W}");
this.subtype.add(SubType.ANGEL);
this.subtype.add(SubType.MERCENARY);
this.power = new MageInt(4);
this.toughness = new MageInt(4);
// Flying
this.addAbility(FlyingAbility.getInstance());
// Vigilance
this.addAbility(VigilanceAbility.getInstance());
// Whenever Angelic Sell-Sword or another nontoken creature you control enters, create a 1/1 red Mercenary creature token with "{T}: Target creature you control gets +1/+0 until end of turn. Activate only as a sorcery."
this.addAbility(new EntersBattlefieldThisOrAnotherTriggeredAbility(
new CreateTokenEffect(new MercenaryToken()),
StaticFilters.FILTER_CREATURE_NON_TOKEN, false, true
));
// Whenever Angelic Sell-Sword attacks, if its power is 6 or greater, draw a card.
this.addAbility(new AttacksTriggeredAbility(new DrawCardSourceControllerEffect(1))
.withInterveningIf(AngelicSellSwordCondition.instance));
}
private AngelicSellSword(final AngelicSellSword card) {
super(card);
}
@Override
public AngelicSellSword copy() {
return new AngelicSellSword(this);
}
}
enum AngelicSellSwordCondition implements Condition {
instance;
@Override
public boolean apply(Game game, Ability source) {
return Optional
.ofNullable(source.getSourcePermanentOrLKI(game))
.map(MageObject::getPower)
.map(MageInt::getValue)
.orElse(0) >= 6;
}
@Override
public String toString() {
return "its power is 6 or greater";
}
}
| 412 | 0.900004 | 1 | 0.900004 | game-dev | MEDIA | 0.913137 | game-dev | 0.994153 | 1 | 0.994153 |
danbarua/NEventSocket | 2,500 | src/NEventSocket.Examples/CommandLineTaskRunner.cs | namespace NEventSocket.Examples
{
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Autofac;
using Net.Autofac.CommandLine;
using NEventSocket.Logging;
using Serilog;
using Serilog.Debugging;
using Serilog.Enrichers;
using Serilog.Events;
public class CommandLineTaskRunner : IDisposable
{
private CancellationTokenSource cancellationTokenSource;
private IContainer container;
private Task Run(CancellationToken cancellationToken)
{
return container.Resolve<DisplayCommandLineTasks>().Run(cancellationToken);
}
public int Run()
{
var builder = CreateContainerBuilder();
SetupLogging(builder);
container = builder.Build();
var cancellationToken = CreateCancellationToken();
Task.WaitAll(Run(cancellationToken));
return 0;
}
private static ContainerBuilder CreateContainerBuilder()
{
var assembliesToScan = new[] { typeof(Program).Assembly, typeof(DisplayCommandLineTasks).Assembly };
var builder = new ContainerBuilder();
builder.RegisterAssemblyTypes(assembliesToScan).AsImplementedInterfaces().AsSelf();
return builder;
}
private static void SetupLogging(ContainerBuilder builder)
{
SelfLog.Out = Console.Out;
Log.Logger = new LoggerConfiguration()
.Enrich.With(new ThreadIdEnricher())
.WriteTo.ColoredConsole(LogEventLevel.Debug)
.CreateLogger();
builder.RegisterInstance(Log.Logger);
}
private CancellationToken CreateCancellationToken()
{
Console.CancelKeyPress += (sender, args) =>
{
cancellationTokenSource.Cancel();
args.Cancel = true;
};
cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
//cancellationToken.Register(() => container.Resolve<ILogger>().Warning("Canceling"));
return cancellationToken;
}
public void Dispose()
{
try
{
container.Dispose();
}
catch (Exception e)
{
Debug.WriteLine(e);
}
}
}
} | 412 | 0.859466 | 1 | 0.859466 | game-dev | MEDIA | 0.58971 | game-dev | 0.927063 | 1 | 0.927063 |
trixon/mapton | 3,443 | modules-butterfly/structural_crack/src/main/java/org/mapton/butterfly_structural/crack/CrackPropertiesBuilder.java | /*
* Copyright 2023 Patrik Karlström.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mapton.butterfly_structural.crack;
import java.time.temporal.ChronoUnit;
import java.util.LinkedHashMap;
import org.mapton.butterfly_core.api.AlarmHelper;
import org.mapton.butterfly_core.api.BPropertiesBuilder;
import org.mapton.butterfly_format.types.BComponent;
import org.mapton.butterfly_format.types.structural.BStructuralCrackPoint;
import org.mapton.butterfly_format.types.topo.BTopoControlPoint;
/**
*
* @author Patrik Karlström
*/
public class CrackPropertiesBuilder extends BPropertiesBuilder<BStructuralCrackPoint> {
@Override
public Object build(BStructuralCrackPoint p) {
if (p == null) {
return p;
}
var propertyMap = new LinkedHashMap<String, Object>();
//******************************************************************************
var basicParams = new BPropertiesBuilder.BasicParams();
propertyMap.putAll(populateBasics(p, basicParams));
//******************************************************************************
Double azimuth = null;
try {
var o = p.ext().getObservationsTimeFiltered().getLast();
azimuth = o.ext().getBearing();
} catch (Exception e) {
}
var measParams = new BPropertiesBuilder.MeasParams<BTopoControlPoint>(
azimuth,
p.ext().getMeasurementUntilNext(ChronoUnit.DAYS),
p.ext().getMeasurementAge(ChronoUnit.DAYS),
p.ext().getNumOfObservationsFiltered(),
p.ext().getNumOfObservations(),
p.ext().firstIsZero(),
p.ext().getObservationsAllRaw().stream().filter(obs -> obs.isReplacementMeasurement()).count(),
AlarmHelper.getInstance().getLimitsAsString(BComponent.HEIGHT, p),
AlarmHelper.getInstance().getLimitsAsString(BComponent.PLANE, p),
p.ext().getAlarmPercentString(p.ext()),
p.ext().getAlarmLevelAge(),
p.ext().deltaRolling().getDelta(3),
p.ext().deltaZero().getDelta(3),
p.ext().deltaFirst().getDelta(3)
);
propertyMap.putAll(populateMeas(p, measParams));
//******************************************************************************
var dateParams = new BPropertiesBuilder.DateParams(
p.ext().getObservationRawFirstDate(),
p.ext().getObservationFilteredFirstDate(),
p.ext().getObservationRawLastDate(),
p.ext().getObservationFilteredLastDate(),
p.ext().getObservationRawNextDate()
);
propertyMap.putAll(populateDates(p, dateParams));
//******************************************************************************
propertyMap.putAll(populateDatabase(p));
return propertyMap;
}
}
| 412 | 0.948101 | 1 | 0.948101 | game-dev | MEDIA | 0.381766 | game-dev | 0.956626 | 1 | 0.956626 |
BluezoneGlobal/bluezone-app | 1,771 | app/main/components/HomeScreen/components/Radar/Dot.js | /**
* Copyright 2016-present, Bkav, Cop.
* All rights reserved.
*
* This source code is licensed under the Bkav license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @author phucnhb@bkav.com on 11/09/2020.
*
* History:
* @modifier abc@bkav.com on xx/xx/xxxx đã chỉnh sửa abcxyx (Chỉ các thay đổi quan trọng mới cần ghi lại note này)
*/
'use strict';
import React from 'react';
import LottieView from 'lottie-react-native';
class Dot extends React.Component {
constructor(props) {
super(props);
this.play = this.play.bind(this);
this.stop = this.stop.bind(this);
this.setRef = this.setRef.bind(this);
this.onAnimationFinish = this.onAnimationFinish.bind(this);
this.isPlaying = false;
this.playAgain = false;
}
play() {
const {dot} = this.props;
if (!this.isPlaying) {
this.isPlaying = true;
this.playAgain = false;
this.ref && this.ref.play(dot.firstBeginFrame, dot.firstEndFrame);
} else {
this.playAgain = true;
}
}
stop() {}
onAnimationFinish() {
const {dot} = this.props;
if (this.playAgain) {
this.isPlaying = true;
this.playAgain = false;
this.ref && this.ref.play(dot.otherBeginFrame, dot.otherEndFrame);
return;
}
this.isPlaying = false;
}
setRef(ref) {
this.ref = ref;
}
render() {
const {dot, key, dotIndex, ref, ...other} = this.props;
return (
<LottieView
ref={this.setRef}
source={dot}
loop={false}
onAnimationFinish={this.onAnimationFinish}
renderMode="HARDWARE"
{...other}
/>
);
}
}
export default Dot;
| 412 | 0.847601 | 1 | 0.847601 | game-dev | MEDIA | 0.602077 | game-dev | 0.521835 | 1 | 0.521835 |
fantom-lang/fantom | 5,490 | src/sys/java/fanx/util/StrUtil.java | //
// Copyright (c) 2006, Brian Frank and Andy Frank
// Licensed under the Academic Free License version 3.0
//
// History:
// 15 Sep 05 Brian Frank Creation
//
package fanx.util;
import java.io.*;
import java.net.*;
import java.text.*;
import java.util.*;
import fanx.fcode.*;
/**
* StrUtil provides helpful methods for string manipulation.
*/
public class StrUtil
{
/**
* Return a new string replacing all occurrences
* of match with replace in s
*/
public static String replace(String s, String match, String replace)
{
if (match.length() == 0) return s;
StringBuilder b = new StringBuilder();
int mlen = match.length();
int last = 0;
int curr = s.indexOf(match);
while (curr != -1)
{
b.append(s.substring(last, curr));
b.append(replace);
last = curr + mlen;
curr = s.indexOf(match, last);
}
if (last < s.length())
b.append(s.substring(last));
return b.toString();
}
/**
* Translate the specified string as it would appear in
* code as a string literal. For example all newlines
* appear as \n.
*/
public static String asCode(String s)
{
StringBuilder b = new StringBuilder();
for (int i=0; i<s.length(); ++i)
{
char c = s.charAt(i);
switch (c)
{
case '\0': b.append("\\0"); break;
case '\t': b.append("\\t"); break;
case '\n': b.append("\\n"); break;
case '\r': b.append("\\r"); break;
case '\\': b.append("\\\\"); break;
default: b.append(c); break;
}
}
return b.toString();
}
/**
* Get a string containing the specified number of spaces.
*/
public static String getSpaces(int len)
{
// do an array lookup for reasonable length
// strings since that is the common case
try { return spaces[len]; } catch (ArrayIndexOutOfBoundsException e) {}
// otherwise we build a new one
StringBuilder s = new StringBuilder(spaces[spaces.length-1]);
for (int i=spaces.length-1; i<len; ++i)
s.append(' ');
return s.toString();
}
static String[] spaces = new String[20];
static
{
StringBuilder s = new StringBuilder();
for (int i=0; i<spaces.length; ++i)
{
spaces[i] = s.toString();
s.append(' ');
}
}
/**
* Pad to the left to ensure string is specified length.
* If s.length already greater than len, do nothing.
*/
public static String padl(String s, int len)
{
if (s.length() >= len) return s;
return getSpaces(len-s.length()) + s;
}
/**
* Pad to the right to ensure string is specified length.
* If s.length already greater than len, do nothing.
*/
public static String padr(String s, int len)
{
if (s.length() >= len) return s;
return s + getSpaces(len-s.length());
}
/**
* Get current hostname.
*/
public static String hostname()
{
if (hostname == null)
{
try
{
hostname = InetAddress.getLocalHost().getHostName();
}
catch (Exception e)
{
hostname = "Unknown";
}
}
return hostname;
}
static String hostname = null;
/**
* Get a timestamp string for current time.
*/
public static String timestamp()
{
return new SimpleDateFormat("d-MMM-yyyy HH:mm:ss zzz").format(new Date());
}
/**
* Get simple class name from specified class.
*/
public static String getName(Class cls)
{
String name = cls.getName();
int dot = name.lastIndexOf('.');
if (dot < 0) return name;
return name.substring(dot+1);
}
/**
* Write the stack trace to a string.
*/
public static String traceToString(Throwable e)
{
StringWriter out = new StringWriter();
e.printStackTrace(new PrintWriter(out));
return out.toString();
}
/**
* Return a zero based index as "first", "second", etc.
*/
public static String toOrder(int index)
{
switch (index)
{
case 0: return "first";
case 1: return "second";
case 2: return "third";
case 3: return "fourth";
case 4: return "fifth";
case 5: return "sixth";
case 6: return "seventh";
case 7: return "eighth";
case 8: return "ninth";
case 9: return "tenth";
default: return (index+1) + "th";
}
}
/**
* Convert FConst flags to a string.
*/
public static String flagsToString(int flags)
{
StringBuilder s = new StringBuilder();
if ((flags & FConst.Public) != 0) s.append("public ");
if ((flags & FConst.Protected) != 0) s.append("protected ");
if ((flags & FConst.Private) != 0) s.append("private ");
if ((flags & FConst.Internal) != 0) s.append("internal ");
if ((flags & FConst.Native) != 0) s.append("native ");
if ((flags & FConst.Enum) != 0) s.append("enum ");
if ((flags & FConst.Mixin) != 0) s.append("mixin ");
if ((flags & FConst.Final) != 0) s.append("final ");
if ((flags & FConst.Ctor) != 0) s.append("new ");
if ((flags & FConst.Override) != 0) s.append("override ");
if ((flags & FConst.Abstract) != 0) s.append("abstract ");
if ((flags & FConst.Static) != 0) s.append("static ");
if ((flags & FConst.Virtual) != 0) s.append("virtual ");
return s.toString();
}
public static Comparator comparator = new Comparator()
{
public int compare(Object a, Object b)
{
return String.valueOf(a).compareTo(String.valueOf(b));
}
};
} | 412 | 0.749039 | 1 | 0.749039 | game-dev | MEDIA | 0.145058 | game-dev | 0.944631 | 1 | 0.944631 |
Signalsmith-Audio/wasm-clap-browserhost | 2,208 | clap-host/generate-forwarding-wasm.mjs | export default function generateForwardingModuleWasm(methodSignatures) {
let typeCodes = {
b: 0x7F, // bool (32-bit in wasm32)
p: 0x7F, // pointer
s: 0x7F, // size
i: 0x7F, // i32
I: 0x7E, // i64
f: 0x7D, // f32
F: 0x7C // f64
};
function encodeUint(arr, v) {
while (v >= 0x80) {
arr.push(0x80 | (v&0x7F));
v >>= 7;
}
arr.push(v);
return arr;
}
function encodeName(arr, str) {
encodeUint(arr, str.length);
for (let i = 0; i < str.length; ++i) {
arr.push(str.charCodeAt(i)%0x7F);
}
}
let typeCount = 0;
let typeWasm = [], importWasm = [], exportWasm = [];
let typeMap = {};
let methodNames = Object.keys(methodSignatures);
methodNames.forEach((key, fIndex) => {
let sig = methodSignatures[key]; // code using the four basic types
let typeIndex;
if (sig in typeMap) {
// reuse existing type
typeIndex = methodSignatures[key] = typeMap[sig];
} else {
// Add an entry to the type section
typeIndex = typeMap[sig] = typeCount++;
typeWasm.push(0x60); // function type
encodeUint(typeWasm, sig.length - 1); // argument count
for (let i = 1; i < sig.length; ++i) {
typeWasm.push(typeCodes[sig[i]]);
}
if (sig[0] == 'v') {
typeWasm.push(0); // no result (void)
} else {
typeWasm.push(0x01);
typeWasm.push(typeCodes[sig[0]]);
}
}
encodeName(importWasm, "proxy");
encodeName(importWasm, key);
importWasm.push(0x00); // function import
encodeUint(importWasm, typeIndex); // type index
encodeName(exportWasm, key);
exportWasm.push(0x00); // function export
encodeUint(exportWasm, fIndex);
});
// Each section starts with the number of entries
typeWasm = encodeUint([], typeCount).concat(typeWasm);
let methodCount = encodeUint([], methodNames.length);
importWasm = methodCount.concat(importWasm);
exportWasm = methodCount.concat(exportWasm);
return new Uint8Array([
0x00, 0x61, 0x73, 0x6D, // magic: \0asm
0x01, 0x00, 0x00, 0x00, // v1
0x01, // type section
encodeUint([], typeWasm.length),
typeWasm,
0x02, // import section
encodeUint([], importWasm.length),
importWasm,
0x07, // export section
encodeUint([], exportWasm.length),
exportWasm
].flat());
};
| 412 | 0.534193 | 1 | 0.534193 | game-dev | MEDIA | 0.17513 | game-dev | 0.672771 | 1 | 0.672771 |
Xiao-MoMi/Custom-Fishing | 5,866 | core/src/main/java/net/momirealms/customfishing/bukkit/command/feature/GiveItemByUUIDCommand.java | /*
* Copyright (C) <2024> <XiaoMoMi>
*
* 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
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.bukkit.command.feature;
import net.kyori.adventure.text.Component;
import net.momirealms.customfishing.api.BukkitCustomFishingPlugin;
import net.momirealms.customfishing.api.mechanic.context.Context;
import net.momirealms.customfishing.api.mechanic.context.ContextKeys;
import net.momirealms.customfishing.api.util.PlayerUtils;
import net.momirealms.customfishing.bukkit.command.BukkitCommandFeature;
import net.momirealms.customfishing.common.command.CustomFishingCommandManager;
import net.momirealms.customfishing.common.locale.MessageConstants;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.incendo.cloud.Command;
import org.incendo.cloud.CommandManager;
import org.incendo.cloud.context.CommandContext;
import org.incendo.cloud.context.CommandInput;
import org.incendo.cloud.parser.standard.IntegerParser;
import org.incendo.cloud.parser.standard.StringParser;
import org.incendo.cloud.suggestion.Suggestion;
import org.incendo.cloud.suggestion.SuggestionProvider;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@SuppressWarnings("DuplicatedCode")
public class GiveItemByUUIDCommand extends BukkitCommandFeature<CommandSender> {
public GiveItemByUUIDCommand(CustomFishingCommandManager<CommandSender> commandManager) {
super(commandManager);
}
@Override
public Command.Builder<? extends CommandSender> assembleCommand(CommandManager<CommandSender> manager, Command.Builder<CommandSender> builder) {
return builder
.required("uuid", StringParser.stringComponent().suggestionProvider(new SuggestionProvider<>() {
@Override
public @NonNull CompletableFuture<? extends @NonNull Iterable<? extends @NonNull Suggestion>> suggestionsFuture(@NonNull CommandContext<Object> context, @NonNull CommandInput input) {
return CompletableFuture.completedFuture(Bukkit.getOnlinePlayers().stream().map(it -> Suggestion.suggestion(it.getUniqueId().toString())).toList());
}
}))
.required("id", StringParser.stringComponent().suggestionProvider(new SuggestionProvider<>() {
@Override
public @NonNull CompletableFuture<? extends @NonNull Iterable<? extends @NonNull Suggestion>> suggestionsFuture(@NonNull CommandContext<Object> context, @NonNull CommandInput input) {
return CompletableFuture.completedFuture(BukkitCustomFishingPlugin.getInstance().getItemManager().getItemIDs().stream().map(Suggestion::suggestion).toList());
}
}))
.optional("amount", IntegerParser.integerParser(1, 6400))
.flag(manager.flagBuilder("silent").withAliases("s").build())
.flag(manager.flagBuilder("to-inventory").withAliases("t").build())
.handler(context -> {
final UUID uuid = UUID.fromString(context.get("uuid"));
final Player player = Bukkit.getPlayer(uuid);
if (player == null)
return;
final int amount = context.getOrDefault("amount", 1);
final String id = context.get("id");
boolean toInv = context.flags().hasFlag("to-inventory");
try {
ItemStack itemStack = BukkitCustomFishingPlugin.getInstance().getItemManager().buildInternal(Context.player(player).arg(ContextKeys.ID, id), id);
if (itemStack == null) {
throw new RuntimeException("Unrecognized item id: " + id);
}
int amountToGive = amount;
int maxStack = itemStack.getMaxStackSize();
while (amountToGive > 0) {
int perStackSize = Math.min(maxStack, amountToGive);
amountToGive -= perStackSize;
ItemStack more = itemStack.clone();
more.setAmount(perStackSize);
if (toInv || player.getGameMode() == GameMode.SPECTATOR) {
PlayerUtils.putItemsToInventory(player.getInventory(), more, more.getAmount());
} else {
PlayerUtils.dropItem(player, more, false, true, false);
}
}
handleFeedback(context, MessageConstants.COMMAND_ITEM_GIVE_SUCCESS, Component.text(player.getName()), Component.text(amount), Component.text(id));
} catch (Exception e) {
handleFeedback(context, MessageConstants.COMMAND_ITEM_FAILURE_NOT_EXIST, Component.text(id));
}
});
}
@Override
public String getFeatureID() {
return "give_item_by_uuid";
}
}
| 412 | 0.949213 | 1 | 0.949213 | game-dev | MEDIA | 0.980774 | game-dev | 0.984189 | 1 | 0.984189 |
LandSandBoat/server | 74,664 | src/map/modifier.h | /*
===========================================================================
Copyright (c) 2010-2015 Darkstar Dev Teams
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/
===========================================================================
*/
#ifndef _CMODIFIER_H
#define _CMODIFIER_H
#include "common/cbasetypes.h"
enum class Mod
{
// IF YOU ADD ANY NEW MODIFIER HERE, ADD IT IN scripts/enum/mod.lua ASWELL!
NONE = 0, // Essential, but does nothing :)
// NAME = ID, // Comment
DEF = 1, // Target's Defense
HP = 2, // Target's HP
HPP = 3, // HP Percentage
CONVMPTOHP = 4, // MP -> HP (Cassie Earring)
MP = 5, // MP +/-
MPP = 6, // MP Percentage
CONVHPTOMP = 7, // HP -> MP
WEAKNESS_PCT = 1093, // Weakness HP/MP reduction term, -1 = - 1% HP/MP
CURSE_PCT = 1094, // Curse HP/MP reduction term, -1 = - 1% HP/MP
BASE_HP = 1095, // Base HP bonus (like merits)
BASE_MP = 1096, // Base MP bonus (like merits)
FOOD_HP = 1130, // Food HP (this is added after curse)
FOOD_MP = 1131, // Food MP (this is added after curse)
STR = 8, // Strength
DEX = 9, // Dexterity
VIT = 10, // Vitality
AGI = 11, // Agility
INT = 12, // Intelligence
MND = 13, // Mind
CHR = 14, // Charisma
TWOHAND_STR = 218, // Same as STR, but only active when using a two handed weapon (e.g. Hasso)
// Magic Evasion versus elements
// This has been repeatedly mixed up with SDT - be careful!
FIRE_MEVA = 15, // Fire Magic Evasion
ICE_MEVA = 16, // Ice Magic Evasion
WIND_MEVA = 17, // Wind Magic Evasion
EARTH_MEVA = 18, // Earth Magic Evasion
THUNDER_MEVA = 19, // Thunder Magic Evasion
WATER_MEVA = 20, // Water Magic Evasion
LIGHT_MEVA = 21, // Light Magic Evasion
DARK_MEVA = 22, // Dark Magic Evasion
// Magic Evasion RANK versus elements (resistance ranks)
FIRE_RES_RANK = 192, // Fire Resistance Rank
ICE_RES_RANK = 193, // Ice Resistance Rank
WIND_RES_RANK = 194, // Wind Resistance Rank
EARTH_RES_RANK = 195, // Earth Resistance Rank
THUNDER_RES_RANK = 196, // Thunder Resistance Rank
WATER_RES_RANK = 197, // Water Resistance Rank
LIGHT_RES_RANK = 198, // Light Resistance Rank
DARK_RES_RANK = 199, // Dark Resistance Rank
// Magic Evasion RANK versus status effects (resistance ranks)
PARALYZE_RES_RANK = 1160,
BIND_RES_RANK = 1161,
SILENCE_RES_RANK = 1162,
SLOW_RES_RANK = 1163,
POISON_RES_RANK = 1164,
LIGHT_SLEEP_RES_RANK = 1165,
DARK_SLEEP_RES_RANK = 1166,
BLIND_RES_RANK = 1167,
ATT = 23, // Attack
RATT = 24, // Ranged Attack
ACC = 25, // Accuracy
RACC = 26, // Ranged Accuracy
TWOHAND_ACC = 219, // Same as ACC, but only active when using a two handed weapon (e.g. Hasso)
ENMITY = 27, // Enmity
ENMITY_LOSS_REDUCTION = 427, // Reduces Enmity lost when taking damage
MATT = 28, // Magic Attack
MDEF = 29, // Magic Defense
MACC = 30, // Magic Accuracy - note that this is NOT iLvl "magic accuracy skill" which happens in item_weapon.sql
MEVA = 31, // Magic Evasion
// Magic Accuracy and Elemental Attacks
FIRE_MAB = 32, // Elemental "Magic Attack Bonus" aka "Affinity"
ICE_MAB = 33, // Elemental "Magic Attack Bonus" aka "Affinity"
WIND_MAB = 34, // Elemental "Magic Attack Bonus" aka "Affinity"
EARTH_MAB = 35, // Elemental "Magic Attack Bonus" aka "Affinity"
THUNDER_MAB = 36, // Elemental "Magic Attack Bonus" aka "Affinity"
WATER_MAB = 37, // Elemental "Magic Attack Bonus" aka "Affinity"
LIGHT_MAB = 38, // Elemental "Magic Attack Bonus" aka "Affinity"
DARK_MAB = 39, // Elemental "Magic Attack Bonus" aka "Affinity"
FIRE_MACC = 40, // Fire Accuracy
ICE_MACC = 41, // Ice Accuracy
WIND_MACC = 42, // Wind Accuracy
EARTH_MACC = 43, // Earth Accuracy
THUNDER_MACC = 44, // Thunder Accuracy
WATER_MACC = 45, // Water Accuracy
LIGHT_MACC = 46, // Light Accuracy
DARK_MACC = 47, // Dark Accuracy
// Day/Weather elemental bonuses.
FORCE_FIRE_DWBONUS = 531, // Set to above 0 to force fire day/weather elemental bonuses. Penalties are NOT forced.
FORCE_ICE_DWBONUS = 532, // Set to above 0 to force ice day/weather elemental bonuses. Penalties are NOT forced.
FORCE_WIND_DWBONUS = 533, // Set to above 0 to force wind day/weather elemental bonuses. Penalties are NOT forced.
FORCE_EARTH_DWBONUS = 534, // Set to above 0 to force earth day/weather elemental bonuses. Penalties are NOT forced.
FORCE_LIGHTNING_DWBONUS = 535, // Set to above 0 to force lightning day/weather elemental bonuses. Penalties are NOT forced.
FORCE_WATER_DWBONUS = 536, // Set to above 0 to force water day/weather elemental bonuses. Penalties are NOT forced.
FORCE_LIGHT_DWBONUS = 537, // Set to above 0 to force light day/weather elemental bonuses. Penalties are NOT forced.
FORCE_DARK_DWBONUS = 538, // Set to above 0 to force dark day/weather elemental bonuses. Penalties are NOT forced.
FORCE_DW_BONUS_PENALTY = 1156, // Set to above 0 to force all day/weather elemental bonus AND penalties. This is used by "Hachirin-no-Obi".
WSACC = 48, // Weaponskill Accuracy
ATTP = 62, // % Attack
DEFP = 63, // % Defense
COMBAT_SKILLUP_RATE = 64, // % increase in skillup combat rate
MAGIC_SKILLUP_RATE = 65, // % increase in skillup magic rate
RATTP = 66, // % Ranged Attack
EVA = 68, // Evasion
RDEF = 69, // Ranged Defense
REVA = 70, // Ranged Evasion
MPHEAL = 71, // MP Recovered while healing
HPHEAL = 72, // HP Recovered while healing
STORETP = 73, // Increases the rate at which TP is gained
TACTICAL_PARRY = 486, // Tactical Parry Tp Bonus
INHIBIT_TP = 488, // Inhibits TP Gain (percent)
// Working Skills (weapon combat skills)
// These are NOT item Level skill, they are skill in your status menu. iLvl "skill" happens in item_weapon.sql
HTH = 80, // Hand To Hand Skill
DAGGER = 81, // Dagger Skill
SWORD = 82, // Sword Skill
GSWORD = 83, // Great Sword Skill
AXE = 84, // Axe Skill
GAXE = 85, // Great Axe Skill
SCYTHE = 86, // Scythe Skill
POLEARM = 87, // Polearm Skill
KATANA = 88, // Katana Skill
GKATANA = 89, // Great Katana Skill
CLUB = 90, // Club Skill
STAFF = 91, // Staff Skill
AUTO_MELEE_SKILL = 101, // Automaton Melee Skill -- Do not apply to items in item_mods_pet.sql, apply only to master (it does not work properly on pet mods)
AUTO_RANGED_SKILL = 102, // Automaton Range Skill -- Do not apply to items in item_mods_pet.sql, apply only to master (it does not work properly on pet mods)
AUTO_MAGIC_SKILL = 103, // Automaton Magic Skill -- Do not apply to items in item_mods_pet.sql, apply only to master (it does not work properly on pet mods)
ARCHERY = 104, // Archery Skill
MARKSMAN = 105, // Marksman Skill
THROW = 106, // Throw Skill
GUARD = 107, // Guard Skill
EVASION = 108, // Evasion Skill
SHIELD = 109, // Shield Skill
PARRY = 110, // Parry Skill
// Magic Skills
DIVINE = 111, // Divine Magic Skill
HEALING = 112, // Healing Magic Skill
ENHANCE = 113, // Enhancing Magic Skill
ENFEEBLE = 114, // Enfeebling Magic Skill
ELEM = 115, // Elemental Magic Skill
DARK = 116, // Dark Magic Skill
SUMMONING = 117, // Summoning Magic Skill
NINJUTSU = 118, // Ninjutsu Magic Skill
SINGING = 119, // Singing Magic Skill
STRING = 120, // String Magic Skill
WIND = 121, // Wind Magic Skill
BLUE = 122, // Blue Magic Skill
GEOMANCY = 123, // Geomancy Magic Skill
HANDBELL = 124, // Handbell Magic SKill
// Synthesis Skills
FISH = 127, // Fishing Skill
WOOD = 128, // Woodworking Skill
SMITH = 129, // Smithing Skill
GOLDSMITH = 130, // Goldsmithing Skill
CLOTH = 131, // Clothcraft Skill
LEATHER = 132, // Leathercraft Skill
BONE = 133, // Bonecraft Skill
ALCHEMY = 134, // Alchemy Skill
COOK = 135, // Cooking Skill
SYNERGY = 136, // Synergy Skill
RIDING = 137, // Riding Skill
// Fishing gear modifiers
PENGUIN_RING_EFFECT = 152, // +2 on fishing arrow delay / fish movement for mini - game
ALBATROSS_RING_EFFECT = 153, // adds 30 seconds to mini - game time
PELICAN_RING_EFFECT = 154, // adds extra skillup roll for fishing
FISHING_SKILL_GAIN = 155, // food for fishing skill ups
// Damage - 10000 base, 375 = 3.75%
DMG = 160, // Damage Taken %
DMGPHYS = 161, // Physical Damage Taken %
DMGPHYS_II = 190, // Physical Damage Taken II % (Burtgang)
UDMGPHYS = 387, // Uncapped Damage Multipliers
DMGBREATH = 162, // Breath Damage Taken %
UDMGBREATH = 388, // Used in sentinel, invincible, physical shield etc
DMGMAGIC = 163, // Magic Damage Taken %
DMGMAGIC_II = 831, // Magic Damage Taken II % (Aegis)
UDMGMAGIC = 389,
DMGRANGE = 164, // Range Damage Taken %
UDMGRANGE = 390,
DMG_AOE = 158, // Damage Taken % when not main target of an AoE action. (Ex: Locus Mobs)
RECEIVED_DAMAGE_CAP = 221, // Caps the damage taken recieved by the attacker
RECEIVED_DAMAGE_VARIANT = 222, // The variance that you want the damage cap to changed by. Ex: If you want the damage to be from 90-100 instead of a flat 100 you can set this to 10. It will random the value between 90-100 if the damage is above 100.
// Specific Damage Taken vs physical damage type
SLASH_SDT = 49, // Slash Damage Taken. Base 10000. 100% = 0
PIERCE_SDT = 50, // Piercing Damage Taken. Base 10000. 100% = 0
IMPACT_SDT = 51, // Impact Damage Taken. Base 10000. 100% = 0
HTH_SDT = 52, // Hand-To-Hand Damage Taken. Base 10000. 100% = 0
// Elemental SDT. BASE 10000. This has been repeatedly mixed up with RESISTANCE - be careful!
FIRE_SDT = 54, // Fire Damage Taken
ICE_SDT = 55, // Ice Damage Taken
WIND_SDT = 56, // Wind Damage Taken
EARTH_SDT = 57, // Earth Damage Taken
THUNDER_SDT = 58, // Thunder Damage Taken
WATER_SDT = 59, // Water Damage Taken
LIGHT_SDT = 60, // Light Damage Taken
DARK_SDT = 61, // Dark Damage Taken
// Occasionally annuls damage taken. Modifier value = chance in %
NULL_DAMAGE = 142, // Occasionally annuls all/any damage.
NULL_PHYSICAL_DAMAGE = 416, // Occasionally annuls physical damage.
NULL_BREATH_DAMAGE = 143, // Occasionally annuls breath damage.
NULL_MAGICAL_DAMAGE = 476, // Occasionally annuls magical damage.
NULL_RANGED_DAMAGE = 239, // Occasionally annuls ranged damage.
FIRE_NULL = 467, // Occasionally annuls fire elemental damage.
ICE_NULL = 468, // Occasionally annuls ice elemental damage.
WIND_NULL = 469, // Occasionally annuls wind elemental damage.
EARTH_NULL = 470, // Occasionally annuls earth elemental damage.
LTNG_NULL = 471, // Occasionally annuls thunder elemental damage.
WATER_NULL = 472, // Occasionally annuls water elemental damage.
LIGHT_NULL = 473, // Occasionally annuls light elemental damage.
DARK_NULL = 474, // Occasionally annuls dark elemental damage.
// Occasionally absorbs damage taken. Modifier value = chance in %
ABSORB_DMG_CHANCE = 480, // Occasionally absorbs all/any damage.
PHYS_ABSORB = 512, // Occasionally absorbs physical damage. USED FOR RANGED ASWELL.
MAGIC_ABSORB = 475, // Occasionally absorbs magical damage.
FIRE_ABSORB = 459, // Occasionally absorbs fire elemental damage.
ICE_ABSORB = 460, // Occasionally absorbs ice elemental damage.
WIND_ABSORB = 461, // Occasionally absorbs wind elemental damage.
EARTH_ABSORB = 462, // Occasionally absorbs earth elemental damage.
LTNG_ABSORB = 463, // Occasionally absorbs thunder elemental damage.
WATER_ABSORB = 464, // Occasionally absorbs water elemental damage.
LIGHT_ABSORB = 465, // Occasionally absorbs light elemental damage.
DARK_ABSORB = 466, // Occasionally absorbs dark elemental damage.
// Crit Damage / Delay
CRITHITRATE = 165, // Raises chance to crit
CRITHITRATE_ONLY_WEP = 141, // Raises chance to crit (but only for attacks with the specific weapon that has the mod)
CRIT_DMG_INCREASE = 421, // Raises the damage of critical hit by percent %
RANGED_CRIT_DMG_INCREASE = 964, // Increases ranged critical damage by a percent
CRITICAL_HIT_EVASION = 166, // Modifies chance enemy will crit
CRIT_DEF_BONUS = 908, // Reduces crit hit damage
MAGIC_CRITHITRATE = 562, // Raises chance to magic crit
MAGIC_CRITHITRATE_II = 1168, // Raises chance to add a critical 1.25 magic damage multiplier.
MAGIC_CRIT_DMG_INCREASE = 563, // Raises damage done when criting with magic
FENCER_TP_BONUS = 903, // TP Bonus to weapon skills from Fencer Trait
FENCER_CRITHITRATE = 904, // Increased Crit chance from Fencer Trait
SMITE = 898, // Raises attack when using H2H or 2H weapons (256 scale)
TACTICAL_GUARD = 899, // Tp increase when guarding
GUARD_PERCENT = 976, // Guard Percent
HASTE_MAGIC = 167, // Haste (and Slow) from magic - 10000 base, 375 = 3.75%
HASTE_ABILITY = 383, // Haste (and Slow) from abilities - 10000 base, 375 = 3.75%
HASTE_GEAR = 384, // Haste (and Slow) from equipment - 10000 base, 375 = 3.75%
TWOHAND_HASTE_ABILITY = 217, // Haste (and Slow) from abilities - 10000 base, 375 = 3.75% - Only applies to auto attacks when using two handed weapons, additive to HASTE_ABILITY
SPELLINTERRUPT = 168, // % Spell Interruption Rate
// Movement speed modifiers in use order.
MOUNT_MOVE = 972, // % Mount Movement Speed
MOVE_SPEED_STACKABLE = 75, // Additive modifier. Applied before multipliers. Gear movement speed penalties.
MOVE_SPEED_WEIGHT_PENALTY = 77, // Multiplicative modifier. For Gravity and curse.
MOVE_SPEED_FLEE = 1085, // Multiplicative modifier.
MOVE_SPEED_CHEER = 1087, // Multiplicative modifier from "cheer" type KI's.
MOVE_SPEED_GEAR_BONUS = 76, // Multiplicative modifier. Gear movement speed bonuses. DOES NOT STACK with each other, only highest applies.
MOVE_SPEED_QUICKENING = 78, // Additive modifier. Applied after multipliers. Jig, spreinter shoes, etc. Shares cap with Mazurka.
MOVE_SPEED_MAZURKA = 79, // Additive modifier. Applied after multipliers. Song movement speed. Shares cap with Quickening,
MOVE_SPEED_BOLTERS_ROLL = 1086, // Additive modifier. Applied after multipliers.
MOVE_SPEED_OVERRIDE = 169, // Modifier used to overide regular speed caps. (GM speed and Feast of Swords)
FASTCAST = 170, // Increases Spell Cast Time (TRAIT)
UFASTCAST = 407, // uncapped fast cast
CURE_CAST_TIME = 519, // cure cast time reduction
ELEMENTAL_CELERITY = 901, // Quickens Elemental Magic Casting
DELAY = 171, // Increase/Decrease Delay
RANGED_DELAY = 172, // Increase/Decrease Ranged Delay
MARTIAL_ARTS = 173, // The integer amount of delay to reduce from H2H weapons' base delay. (TRAIT)
SKILLCHAINBONUS = 174, // Damage bonus applied to skill chain damage. Modifier from effects/traits
SKILLCHAINDMG = 175, // Damage bonus applied to skill chain damage. Modifier from gear (multiplicative after effect/traits)
MAX_SWINGS = 978, // Max swings for "Occasionally attacks X times"
ADDITIONAL_SWING_CHANCE = 979, // Chance that allows for an additional swing despite of multiple hits, mostly for Amood weapons
MAGIC_DAMAGE = 311, // Magic damage added directly to the spell's base damage
// FOOD!
FOOD_HPP = 176, //
FOOD_HP_CAP = 177, //
FOOD_MPP = 178, //
FOOD_MP_CAP = 179, //
FOOD_ATTP = 180, //
FOOD_ATT_CAP = 181, //
FOOD_DEFP = 182, //
FOOD_DEF_CAP = 183, //
FOOD_ACCP = 184, //
FOOD_ACC_CAP = 185, //
FOOD_RATTP = 186, //
FOOD_RATT_CAP = 187, //
FOOD_RACCP = 188, //
FOOD_RACC_CAP = 189, //
FOOD_MACCP = 99, // Macc% see https://www.bg-wiki.com/bg/Category:Magic_Accuracy_Food
FOOD_MACC_CAP = 100, // Sets Upper limit for FOOD_MACCP
FOOD_DURATION = 937, // Percentage to increase food duration
// Killer-Effects - (Most by Traits/JobAbility)
VERMIN_KILLER = 224, // Enhances "Vermin Killer" effect
BIRD_KILLER = 225, // Enhances "Bird Killer" effect
AMORPH_KILLER = 226, // Enhances "Amorph Killer" effect
LIZARD_KILLER = 227, // Enhances "Lizard Killer" effect
AQUAN_KILLER = 228, // Enhances "Aquan Killer" effect
PLANTOID_KILLER = 229, // Enhances "Plantiod Killer" effect
BEAST_KILLER = 230, // Enhances "Beast Killer" effect
UNDEAD_KILLER = 231, // Enhances "Undead Killer" effect
ARCANA_KILLER = 232, // Enhances "Arcana Killer" effect
DRAGON_KILLER = 233, // Enhances "Dragon Killer" effect
DEMON_KILLER = 234, // Enhances "Demon Killer" effect
EMPTY_KILLER = 235, // Enhances "Empty Killer" effect
HUMANOID_KILLER = 236, // Enhances "Humanoid Killer" effect
LUMINIAN_KILLER = 237, // Enhances "Luminian Killer" effect
LUMINION_KILLER = 238, // Enhances "Luminion Killer" effect
// Resistances to enfeebles - Job Traits/Job Abilities/Atmas/Items/Gear
SLEEPRES = 240, // Enhances "Resist Sleep" effect
POISONRES = 241, // Enhances "Resist Poison" effect
PARALYZERES = 242, // Enhances "Resist Paralyze" effect
BLINDRES = 243, // Enhances "Resist Blind" effect
SILENCERES = 244, // Enhances "Resist Silence" effect
VIRUSRES = 245, // Enhances "Resist Virus" effect
PETRIFYRES = 246, // Enhances "Resist Petrify" effect
BINDRES = 247, // Enhances "Resist Bind" effect
CURSERES = 248, // Enhances "Resist Curse" effect
GRAVITYRES = 249, // Enhances "Resist Gravity" effect
SLOWRES = 250, // Enhances "Resist Slow" effect
STUNRES = 251, // Enhances "Resist Stun" effect
CHARMRES = 252, // Enhances "Resist Charm" effect
AMNESIARES = 253, // Enhances "Resist Amnesia" effect
LULLABYRES = 254, // Enhances "Resist Lullaby" effect
DEATHRES = 255, // Used by gear and ATMA that give resistance to instance KO
STATUSRES = 958, // "Resistance to All Status Ailments"
// MEVA bonus to enfeebles (Bar-Effect, for example. And modifiers in mobs)
SLEEP_MEVA = 200,
POISON_MEVA = 201,
PARALYZE_MEVA = 202,
BLIND_MEVA = 203,
SILENCE_MEVA = 204,
VIRUS_MEVA = 205,
PETRIFY_MEVA = 206,
BIND_MEVA = 207,
CURSE_MEVA = 208,
GRAVITY_MEVA = 209,
SLOW_MEVA = 210,
STUN_MEVA = 211,
CHARM_MEVA = 212,
AMNESIA_MEVA = 213,
LULLABY_MEVA = 214,
DEATH_MEVA = 215,
STATUS_MEVA = 216,
// Status effect Immunobreak modifiers.
SLEEP_IMMUNOBREAK = 261,
POISON_IMMUNOBREAK = 262,
PARALYZE_IMMUNOBREAK = 263,
BLIND_IMMUNOBREAK = 264,
SILENCE_IMMUNOBREAK = 265,
PETRIFY_IMMUNOBREAK = 266,
BIND_IMMUNOBREAK = 267,
GRAVITY_IMMUNOBREAK = 268,
SLOW_IMMUNOBREAK = 269,
ADDLE_IMMUNOBREAK = 270,
PARALYZE = 257, // Paralyze -- percent chance to proc
MIJIN_RERAISE = 258, // Augments Mijin Gakure
DUAL_WIELD = 259, // Percent reduction in dual wield delay.
// fTP modifiers
FIRE_FTP_BONUS = 544, // Gives bonus fTP when weaponskill has a Fire property. (Elemental beltes and gorgets) /256
ICE_FTP_BONUS = 545, // Gives bonus fTP when weaponskill has a Ice property. (Elemental beltes and gorgets) /256
WIND_FTP_BONUS = 546, // Gives bonus fTP when weaponskill has a Wind property. (Elemental beltes and gorgets) /256
EARTH_FTP_BONUS = 547, // Gives bonus fTP when weaponskill has a Earth property. (Elemental beltes and gorgets) /256
THUNDER_FTP_BONUS = 548, // Gives bonus fTP when weaponskill has a Thunder property. (Elemental beltes and gorgets) /256
WATER_FTP_BONUS = 549, // Gives bonus fTP when weaponskill has a Water property. (Elemental beltes and gorgets) /256
LIGHT_FTP_BONUS = 550, // Gives bonus fTP when weaponskill has a Light property. (Elemental beltes and gorgets) /256
DARK_FTP_BONUS = 551, // Gives bonus fTP when weaponskill has a Dark property. (Elemental beltes and gorgets) /256
ANY_FTP_BONUS = 1144, // Gives bonus fTP when weaponskill has a (any) property. (Fotia Gorget, Fotia Belt) /256
DAY_FTP_BONUS = 1145, // Gives bonus fTP when weaponskill has a property that matches current day. (Mekira Oto, Gavialis helm, etc...) /256
// Warrior
DOUBLE_ATTACK = 288, // Percent chance to proc
DOUBLE_ATTACK_DMG = 1038, // Increases "Double Attack" damage/"Double Attack" damage + (in percents, e.g. +20 = +20% damage)
WARCRY_DURATION = 483, // Warcy duration bonus from gear
BERSERK_POTENCY = 948, // Augments "Berserk"/Enhances "Berserk" effect (Conqueror)
BERSERK_DURATION = 954, // Berserk Duration
AGGRESSOR_DURATION = 955, // Aggressor Duration
DEFENDER_DURATION = 956, // Defender Duration
ENHANCES_RESTRAINT = 1045, // Enhances "Restraint" effect/"Restraint" + (Increases the damage bonus of Restraint by XXX%)
ENHANCES_BLOOD_RAGE = 1046, // Enhances "Blood Rage" effect/"Blood Rage" duration +
// Monk
BOOST_EFFECT = 97, // Boost power in tenths
CHAKRA_MULT = 1026, // Chakra multiplier increase (from gear)
CHAKRA_REMOVAL = 1027, // Extra statuses removed by Chakra
SUBTLE_BLOW = 289, // How much TP to reduce.
COUNTER = 291, // Percent chance to counter
KICK_ATTACK_RATE = 292, // Percent chance to kick
PERFECT_COUNTER_ATT = 428, // TODO: Raises weapon damage by 20 when countering while under the Perfect Counter effect. This also affects Weapon Rank (though
// not if fighting barehanded).
COUNTER_DAMAGE = 1047, // Increases Damage from Counter Attacks (Percent)
FOOTWORK_ATT_BONUS = 429, // Raises the attack bonus of Footwork. (Tantra Gaiters +2 raise 25/256 to 38/256)
COUNTERSTANCE_EFFECT = 543, // Counterstance effect in percents
DODGE_EFFECT = 552, // Dodge effect in percents
FOCUS_EFFECT = 561, // Focus effect in percents
ADDITIVE_GUARD = 1092, // Additive % bonus to final Guard rate (adds after clamp)
AUGMENTS_IMPETUS = 1097, // see https://www.bg-wiki.com/ffxi/Impetus, adds Crit Hit Damage & Accuracy for Impetus
// White Mage
AFFLATUS_SOLACE = 293, // Pool of HP accumulated during Afflatus Solace
AFFLATUS_MISERY = 294, // Pool of HP accumulated during Afflatus Misery
AUSPICE_EFFECT = 484, // Bonus to Auspice Subtle Blow Effect.
AOE_NA = 524, // % to make -na spells/erase always AoE w/ Divine Veil
REGEN_MULTIPLIER = 838, // Multiplier to base regen rate
CURE2MP_PERCENT = 860, // Converts % of "Cure" amount to MP
DIVINE_BENISON = 910, // Adds fast cast and enmity reduction to -Na spells (includes Erase). Enmity reduction is half of the fast cast amount
REGEN_BONUS = 989, // Increases the amount of HP restored by Regen
// Black Mage
CLEAR_MIND = 295, // Used in conjunction with HEALMP to increase amount between tics
CONSERVE_MP = 296, // Percent chance
ELEMENTAL_MAGIC_RECAST = 1146, // Recast time for elemental magic spells (percent, usually negative)
ENHANCES_ELEMENTAL_SEAL = 1149, // Bonus magic damage when using Elemental Seal (percent)
ELEMENTAL_DEBUFF_EFFECT = 1150, // Increase stat reduction by N, and DoT by N/2 HP per tick
// Red Mage
BLINK = 299, // Tracks blink shadows
STONESKIN = 300, // Tracks stoneskin HP pool
PHALANX = 301, // Tracks direct damage reduction
ENF_MAG_POTENCY = 290, // Increases Enfeebling magic potency %
ENF_MAG_DURATION = 1151, // Increases enfeebling magic duration %
ENHANCES_SABOTEUR = 297, // Increases Saboteur Potency %
// Thief
FLEE_DURATION = 93, // Flee duration in seconds
STEAL = 298, // Increase/Decrease THF Steal chance
DESPOIL = 896, // Increases THF Despoil chance
PERFECT_DODGE = 883, // Increases Perfect Dodge duration in seconds
TRIPLE_ATTACK = 302, // Percent chance
TRIPLE_ATTACK_DMG = 1039, // Increases "Triple Attack" damage/"Triple Attack" damage + (in percents, e.g. +20 = +20% damage)
TREASURE_HUNTER = 303, // Percent chance
TREASURE_HUNTER_PROC = 1048, // Increases Treasure Hunter proc rate (percent)
TREASURE_HUNTER_CAP = 1049, // Increases the Treasure Hunter Cap (e.g. THF JP Gift)
SNEAK_ATK_DEX = 830, // % DEX boost to Sneak Attack (if gear mod, needs to be equipped on hit)
TRICK_ATK_AGI = 520, // % AGI boost to Trick Attack (if gear mod, needs to be equipped on hit)
MUG_EFFECT = 835, // Mug effect as multiplier
ACC_COLLAB_EFFECT = 884, // Increases amount of enmity transferred for Accomplice/Collaborator
HIDE_DURATION = 885, // Hide duration increase (percentage based)
GILFINDER = 897, // Gilfinder, duh
// Paladin
HOLY_CIRCLE_DURATION = 857, // Holy Circle extended duration in seconds
HOLY_CIRCLE_POTENCY = 1141, // Increases the potency of the Holy Circle effect (e.g. mod value 2 = +2% Undead Killer)
RAMPART_DURATION = 92, // Rampart duration in seconds
ABSORB_PHYSDMG_TO_MP = 426, // Absorbs a percentage of physical damage taken to MP.
SHIELD_MASTERY_TP = 485, // Shield mastery TP bonus when blocking with a shield
SENTINEL_EFFECT = 837, // Sentinel effect in percents
SHIELD_DEF_BONUS = 905, // Shield Defense Bonus
COVER_TO_MP = 965, // Converts a successful cover's phsyical damage to MP
COVER_MAGIC_AND_RANGED = 966, // Redirects ranged and single target magic attacks to the cover ability user
COVER_DURATION = 967, // Increases Cover Duration
ENHANCES_CHIVALRY = 1061, // Enhances "Chivalry" effect (increases the base TP modifier by the provided value / 100, e.g. mod value 5 = +0.05)
ENHANCES_DIVINE_EMBLEM = 1062, // Enhances "Divine Emblem" effect/"Divine Emblem" + (increases the ability's special enmity bonus by the provided value)
ENHANCES_FEALTY = 1063, // Enhances "Fealty" effect (increases Fealty's duration by 4 seconds per Fealty merit)
ENHANCES_IRON_WILL = 1064, // Enhances "Iron Will" effect (adds +3% Fast Cast per Iron Will merit to Rampart)
ENHANCES_GUARDIAN = 1065, // Enhances "Guardian" effect (increases Sentinel's duration by 2 seconds per Guardian merit)
PALISADE_BLOCK_BONUS = 1066, // Increases base block rate while under the effects of Palisade (additive, not multiplicative)
REPRISAL_BLOCK_BONUS = 1067, // Increases block rate while under the effects of Reprisal (multiplicative, not additive)
REPRISAL_SPIKES_BONUS = 1068, // Increases Reprisal spikes damage by percentage (e.g. mod value 50 = +50% spikes damage)
SHIELD_BARRIER = 1082, // Grants a bonus to Protect spells cast by self while a shield is equipped.
// Dark Knight
ARCANE_CIRCLE_DURATION = 858, // Arcane Circle extended duration in seconds
ARCANE_CIRCLE_POTENCY = 1069, // Increases the potency of the Arcane Circle effect (e.g. mod value 2 = +2% Arcana Killer)
SOULEATER_EFFECT = 96, // Souleater power in percents
SOULEATER_EFFECT_II = 53, // Uncapped additive Souleaterbonus in percents, 10 = .1
DESPERATE_BLOWS = 906, // Adds ability haste to Last Resort
STALWART_SOUL = 907, // Reduces damage taken from Souleater
DREAD_SPIKES_EFFECT = 998, // Percent increase to total HP drain for Dread Spikes
DARK_MAGIC_CAST = 1071, // Reduces Dark Magic Casting Time by percentage (e.g. mod value -10 = -10% cast time)
DARK_MAGIC_DURATION = 1072, // Increases Dark Magic spell durations by percentage (e.g. mod value 10 = +10% duration)
ENHANCES_BLOOD_WEAPON = 1070, // Enhances "Blood Weapon" effect (increases Blood Weapon's duration in seconds)
ENHANCES_DARK_SEAL = 1073, // Enhances "Dark Seal" effect (Increases Dark Magic spell durations by 10% per Dark Seal merit while Dark Seal active)
ENHANCES_DIABOLIC_EYE = 275, // Diabolic Eye duration + "modifier-value" seconds per Diabolic Eye merit.
ENHANCES_NETHER_VOID = 1083, // Enhances "Nether Void" effect (Increases the potency of the next Absorb or Drain Dark Magic by <value>%
ENHANCES_MUTED_SOUL = 1084, // Enhances "Muted Soul" effect (Adds 3% Zanshin rate per MUTED_SOUL merit level)
ENHANCES_ABSORB_EFFECTS = 1136, // Absorb Spell duration +x seconds (Enhances "Absorb" effects)
AUGMENTS_ABSORB = 1137, // Non-Liberator Absorb Spell potency +x% (Augments "Absorb" effects)
ABSORB_EFFECT_DURATION = 1138, // Absorb Spell duration +% ("Absorb" effect duration +x%)
AUGMENTS_ABSORB_TP = 1153, // Increases absorb-TP potency, stacks with AUGMENTS_ABSORB
// Beastmaster
TAME = 304, // Additional percent chance to charm
CHARM_TIME = 360, // extends the charm time only, no effect of charm chance
FAMILIAR_BONUS = 1169, // Bonus minutes of charm and haste when using familiar
REWARD_HP_BONUS = 364, // Percent to add to reward HP healed. (364)
CHARM_CHANCE = 391, // extra chance to charm (light+apollo staff ect)
FERAL_HOWL_DURATION = 503, // +20% duration per merit when wearing augmented Monster Jackcoat +2
JUG_LEVEL_RANGE = 564, // Decreases the level range of spawned jug pets. Maxes out at 2.
CALL_BEAST_DELAY = 273, // Lowers Call Beast recast
SIC_READY_RECAST = 1052, // SIC/Ready recast reduction (seconds)
TANDEM_STRIKE_POWER = 271, // Grants a bonus to your and your pet's accuracy and magic accuracy when you and your pet are attacking the same target.
TANDEM_BLOW_POWER = 272, // Reduces amount of TP gained by enemies when striking them if you and your pet are attacking the same target.
ENHANCES_MONSTER_CORRELATION = 1155, // Grants your pet acc +X and attp +X% against a weaker opposing ecosystem. Typically applied to pet, not owner (item_mods_pet.sql)
ENHANCES_SPUR = 1157, // Increases Store TP bonus by the mod amount when using job ability Spur
// Bard
MINNE_EFFECT = 433, //
MINUET_EFFECT = 434, //
PAEON_EFFECT = 435, //
REQUIEM_EFFECT = 436, //
THRENODY_EFFECT = 437, //
MADRIGAL_EFFECT = 438, //
MAMBO_EFFECT = 439, //
LULLABY_EFFECT = 440, //
ETUDE_EFFECT = 441, //
BALLAD_EFFECT = 442, //
MARCH_EFFECT = 443, //
FINALE_EFFECT = 444, //
CAROL_EFFECT = 445, //
MAZURKA_EFFECT = 446, //
ELEGY_EFFECT = 447, //
PRELUDE_EFFECT = 448, //
HYMNUS_EFFECT = 449, //
VIRELAI_EFFECT = 450, //
SCHERZO_EFFECT = 451, //
ALL_SONGS_EFFECT = 452, //
MAXIMUM_SONGS_BONUS = 453, //
SONG_DURATION_BONUS = 454, //
SONG_SPELLCASTING_TIME = 455, //
SONG_RECAST_DELAY = 833, // Reduces song recast time in seconds.
AUGMENT_SONG_STAT = 1003, // Bonus to Stat of Element of Enhancing Song.
// Ranger
CAMOUFLAGE_DURATION = 98, // Camouflage duration in percents
RECYCLE = 305, // Percent chance to recycle
SNAPSHOT = 365, // Percent reduction to range attack delay
RAPID_SHOT = 359, // Percent chance to proc rapid shot
WIDESCAN = 340, //
BARRAGE_ACC = 420, // Barrage accuracy
BARRAGE_COUNT = 138, // Increases Barrage shots by 1
DOUBLE_SHOT_RATE = 422, // The rate that double shot can proc. Without this, the default is 40%.
VELOCITY_SNAPSHOT_BONUS = 423, // Increases Snapshot whilst Velocity Shot is up.
VELOCITY_RATT_BONUS = 424, // Increases Ranged Attack whilst Velocity Shot is up.
SHADOW_BIND_EXT = 425, // Extends the time of shadowbind
SCAVENGE_EFFECT = 312, //
SHARPSHOT = 314, //
TRUE_SHOT_EFFECT = 1053, // TODO: True Shot Ranged Damage increase (percent)
DEAD_AIM_EFFECT = 1054, // TODO: Dead Aim Critical Damage increase (percent)
BOUNTY_SHOT_TH_BONUS = 826, // Boosts base TH level of bounty shot
// Samurai
WARDING_CIRCLE_DURATION = 95, // Warding Circle extended duration in seconds
WARDING_CIRCLE_POTENCY = 1143, // Increases the potency of the Warding Circle effect (e.g. mod value 2 = +2% Demon Killer)
MEDITATE_DURATION = 94, // Meditate duration in seconds
ZANSHIN = 306, // Zanshin percent chance
THIRD_EYE_COUNTER_RATE = 508, // Adds counter to 3rd eye anticipates & if using Seigan counter rate is increased by 15%
THIRD_EYE_ANTICIPATE_RATE = 839, // Adds anticipate rate in percents
THIRD_EYE_BONUS = 1055, // TODO: Bonus Third Eye Evasion (count)
SENGIKORI_SC_DMG_DEBUFF = 1088, // % Increase to closing skillchain damage. Applied to defender.
SENGIKORI_MB_DMG_DEBUFF = 1089, // % Increase to magic burst damage. Applied to defender.
SENGIKORI_BONUS = 1090, // additive % increase to Sengikori
// Ninja
UTSUSEMI = 307, // Everyone's favorite --tracks shadows.
UTSUSEMI_BONUS = 900, // Extra shadows from gear
NINJA_TOOL = 308, // Percent chance to not use a tool.
NIN_NUKE_BONUS_INNIN = 223, // Ninjutsu damage multiplier from Innin.
NIN_NUKE_BONUS_GEAR = 522, // Ninjutsu damage multiplier from gear.
DAKEN = 911, // chance to throw a shuriken without consuming it
NINJUTSU_DURATION = 1000,
ENHANCES_SANGE = 1091, // 1 = +1 attack for Daken during Sange per Sange merit (i.e. 20 with 5 merits = +100 attack during Sange)
ENHANCES_FUTAE = 1148, // Adds to the +50% bonus damage to elemental ninjutsu provided by Futae (percent)
// Dragoon
ANCIENT_CIRCLE_DURATION = 859, // Ancient Circle extended duration in seconds
ANCIENT_CIRCLE_POTENCY = 1142, // Increases the potency of the Ancient Circle effect (e.g. mod value 2 = +2% Dragon Killer)
JUMP_TP_BONUS = 361, // bonus tp player receives when using jump
JUMP_SPIRIT_TP_BONUS = 285, // bonus tp player receives when using jump for spirit jump only
JUMP_ATT_BONUS = 362, // ATT% bonus for all jumps
JUMP_SOUL_SPIRIT_ATT_BONUS = 286, // ATT% bonus for Soul & Spirit jump only
JUMP_ACC_BONUS = 936, // accuracy bonus for all jumps
JUMP_DOUBLE_ATTACK = 888, // DA% bonus for all jumps
HIGH_JUMP_ENMITY_REDUCTION = 363, // for gear that reduces more enmity from high jump
FORCE_JUMP_CRIT = 828, // Force critical hit for all jumps
WYVERN_EFFECTIVE_BREATH = 829, // Increases the threshold for triggering healing breath/offensive breath more inclined to pick elemental weakness
WYVERN_SUBJOB_TRAITS = 974, // Adds subjob traits to wyvern on spawn
WYVERN_BREATH_MACC = 986, // Increases accuracy of wyvern's breath. adds 10 magic accuracy per merit to the trait Strafe
WYVERN_LVL_BONUS = 1043, // Wyvern: Lv.+ (Increases wyvern's base level above 99)
WYVERN_ATTRIBUTE_DA = 1056, // Adds an amount of Double Attack to Dragoon each time Wyverns Attributes Increase (percent)
DRAGOON_BREATH_RECAST = 1057, // Restoring/Smithing Breath Recast Reduction (seconds)
ENHANCE_DEEP_BREATHING = 283, // Add 5/256 to deep breathing bonus per merit level when calculating healing breath
UNCAPPED_WYVERN_BREATH = 284, // Uncapped wyvern breath boost. Used on retail for augments, normal gear should use WYVERN_BREATH.
ENHANCES_STRAFE = 282, // Strafe merit augment, +50 TP gained per merit level on breath use.
ENHANCES_SPIRIT_LINK = 281, // Adds erase/-na to Spirit Link
// Summoner
AVATAR_PERPETUATION = 371, // stores base cost of current avatar
WEATHER_REDUCTION = 372, // stores perpetuation reduction depending on weather
DAY_REDUCTION = 373, // stores perpetuation reduction depending on day
PERPETUATION_REDUCTION = 346, // stores the MP/tick reduction from gear
BP_DELAY = 357, // stores blood pact delay reduction
ENHANCES_ELEMENTAL_SIPHON = 540, // Bonus Base MP added to Elemental Siphon skill.
BP_DELAY_II = 541, // Blood Pact Delay Reduction II
BP_DAMAGE = 126, // Blood Pact: Rage Damage increase percentage
BLOOD_BOON = 913, // Occasionally cuts down MP cost of Blood Pact abilities. Does not affect abilities that require Astral Flow.
AVATARS_FAVOR_ENHANCE = 1154, // Enhances Avatars Favor Effect by 1 tier per point
AVATAR_LVL_BONUS = 1040, // Avatar: Lv.+ (Increases all avatar's base level above 99)
CARBUNCLE_LVL_BONUS = 1041, // Carbuncle: Lv.+ (Increases Carbuncle's base level above 99)
CAIT_SITH_LVL_BONUS = 1042, // Cait Sith: Lv.+ (Increases Cait Sith's base level above 99)
ENHANCES_MANA_CEDE = 74, // Bonus % to Mana Cede effect, +1 = 1%
SUMMONING_MAGIC_CAST = 1078, // Summoning magic casting time reduction in seconds
SPIRIT_CAST_REDUCTION = 140, // Spirit Pact casting time reduction in seconds
// Blue Mage
BLUE_POINTS = 309, // Tracks extra blue points
BLUE_LEARN_CHANCE = 945, // Additional chance to learn blue magic
BLUE_JOB_TRAIT_BONUS = 1058, // TODO: Increases job traits gained from equipped blue magic (percent)
BLUE_MAGIC_EFFECT = 1059, // TODO: Bonus to Attribute Value of spell (percent)
ENHANCES_BURST_AFFINITY = 1139, // Increases WSC bonus on spells cast with Burst Affinity (percent)
ENHANCES_CHAIN_AFFINITY = 1140, // TODO: Increases WSC bonus on spells cast with Chain Affinity (base damage +)
BLUE_MAGIC_RECAST = 1147, // Recast time for blue magic spells (percent, usually negative)
// Corsair
EXP_BONUS = 382, //
ROLL_RANGE = 528, // Additional range for COR roll abilities.
JOB_BONUS_CHANCE = 542, // Chance to apply job bonus to COR roll without having the job in the party.
RANDOM_DEAL_BONUS = 220, // % chance to reset 2 abilities
TRIPLE_SHOT_RATE = 999, // Percent increase to Triple Shot Rate
QUICK_DRAW_RECAST = 1060, // Quick Draw Charge Reduction (seconds)
DMG_REFLECT = 316, // Tracks totals
ROLL_ROGUES = 317, // Tracks totals
ROLL_GALLANTS = 318, // Tracks totals
ROLL_CHAOS = 319, // Tracks totals
ROLL_BEAST = 320, // Tracks totals
ROLL_CHORAL = 321, // Tracks totals
ROLL_HUNTERS = 322, // Tracks totals
ROLL_SAMURAI = 323, // Tracks totals
ROLL_NINJA = 324, // Tracks totals
ROLL_DRACHEN = 325, // Tracks totals
ROLL_EVOKERS = 326, // Tracks totals
ROLL_MAGUS = 327, // Tracks totals
ROLL_CORSAIRS = 328, // Tracks totals
ROLL_PUPPET = 329, // Tracks totals
ROLL_DANCERS = 330, // Tracks totals
ROLL_SCHOLARS = 331, // Tracks totals
ROLL_BOLTERS = 869, // Tracks totals
ROLL_CASTERS = 870, // Tracks totals
ROLL_COURSERS = 871, // Tracks totals
ROLL_BLITZERS = 872, // Tracks totals
ROLL_TACTICIANS = 873, // Tracks totals
ROLL_ALLIES = 874, // Tracks totals
ROLL_MISERS = 875, // Tracks totals
ROLL_COMPANIONS = 876, // Tracks totals
ROLL_AVENGERS = 877, // Tracks totals
ROLL_NATURALISTS = 878, // Tracks totals
ROLL_RUNEISTS = 879, // Tracks totals
BUST = 332, // # of busts
QUICK_DRAW_DMG = 411, // Flat damage increase to base QD damage
QUICK_DRAW_DMG_PERCENT = 834, // Percentage increase to QD damage
QUICK_DRAW_MACC = 191, // Quick draw magic accuracy
PHANTOM_ROLL = 881, // Phantom Roll+ Effect from SOA Rings.
PHANTOM_DURATION = 882, // Phantom Roll Duration +.
PHANTOM_RECAST = 1076, // Phantom Roll Recast -.
// Puppetmaster
AUTO_MAB_COEFFICIENT = 157, // Applies a MAB multiplier to automatons. This value is the bonus %.
MANEUVER_BONUS = 504, // Maneuver Stat Bonus
OVERLOAD_THRESH = 505, // Overload Threshold Bonus
AUTO_DECISION_DELAY = 842, // Reduces the Automaton's global decision delay
AUTO_SHIELD_BASH_DELAY = 843, // Reduces the Automaton's global shield bash delay
AUTO_MAGIC_DELAY = 844, // Reduces the Automaton's global magic delay
AUTO_HEALING_DELAY = 845, // Reduces the Automaton's global healing delay
AUTO_HEALING_THRESHOLD = 846, // Increases the healing trigger threshold
BURDEN_DECAY = 847, // Increases amount of burden removed per tick
AUTO_SHIELD_BASH_SLOW = 848, // Adds a slow effect to Shield Bash
AUTO_TP_EFFICIENCY = 849, // Causes the Automaton to wait to form a skillchain when its master is > 90% TP
AUTO_SCAN_RESISTS = 850, // Causes the Automaton to scan a target's resistances
REPAIR_EFFECT = 853, // Removes # of status effects from the Automaton
REPAIR_POTENCY = 854, // Note: Only affects amount regenerated by a %, not the instant restore!
PREVENT_OVERLOAD = 855, // Overloading erases a water maneuver (except on water overloads) instead, if there is one
SUPPRESS_OVERLOAD = 125, // Kenkonken "Suppresses Overload" mod. Unclear how this works exactly. Requires testing on retail.
AUTO_STEAM_JACKET = 938, // Causes the Automaton to mitigate damage from successive attacks of the same type
AUTO_STEAM_JACKET_REDUCTION = 939, // Amount of damage reduced with Steam Jacket
AUTO_SCHURZEN = 940, // Prevents fatal damage leaving the automaton at 1HP and consumes an Earth manuever
AUTO_EQUALIZER = 941, // Reduces damage received according to damage taken
AUTO_PERFORMANCE_BOOST = 942, // Increases the performance of other attachments by a percentage
AUTO_ANALYZER = 943, // Causes the Automaton to mitigate damage from a special attack a number of times
AUTO_ELEM_CAPACITY = 987, // Increases the automaton's elemental capacity for attachments
AUTO_RANGED_DELAY = 1001, // Decreases the amount of time between ranged attacks
AUTO_RANGED_DAMAGEP = 1002, // Increase automaton ranged weapon damage by a %
AUTOMATON_LVL_BONUS = 1044, // Automaton: Lv. (Increases automaton's base level above 99)
// Dancer
FINISHING_MOVES = 333, // Tracks # of finishing moves
SAMBA_DURATION = 490, // Samba duration bonus
WALTZ_POTENCY = 491, // Waltz Potency Bonus
JIG_DURATION = 492, // Jig duration bonus in percents
VFLOURISH_MACC = 493, // Violent Flourish accuracy bonus
STEP_FINISH = 494, // Bonus finishing moves from steps
STEP_ACCURACY = 403, // Bonus accuracy for Dancer's steps
WALTZ_DELAY = 497, // Waltz Ability Delay modifier (-1 mod is -1 second)
SAMBA_PDURATION = 498, // Samba percent duration bonus
REVERSE_FLOURISH_EFFECT = 836, // Reverse Flourish effect in tenths of squared term multiplier
MAX_FINISHING_MOVE_BONUS = 988, // Increases the maximum number of finishing moves that may be stored
WALTZ_COST = 139, // Reduce Waltz cost by 5tp (50 post 1000tp scale)
STEP_TP_CONSUMED = 1077, // Modifies the amount of TP consumed when using steps
// Scholar
BLACK_MAGIC_COST = 393, // MP cost for black magic (light/dark arts)
WHITE_MAGIC_COST = 394, // MP cost for white magic (light/dark arts)
BLACK_MAGIC_CAST = 395, // Cast time for black magic (light/dark arts)
WHITE_MAGIC_CAST = 396, // Cast time for black magic (light/dark arts)
BLACK_MAGIC_RECAST = 397, // Recast time for black magic (light/dark arts)
WHITE_MAGIC_RECAST = 398, // Recast time for white magic (light/dark arts)
ALACRITY_CELERITY_EFFECT = 399, // Bonus for celerity/alacrity effect
LIGHT_ARTS_EFFECT = 334, //
DARK_ARTS_EFFECT = 335, //
LIGHT_ARTS_SKILL = 336, //
DARK_ARTS_SKILL = 337, //
LIGHT_ARTS_REGEN = 338, // Regen bonus flat HP amount from Light Arts and Tabula Rasa
REGEN_DURATION = 339, //
HELIX_EFFECT = 478, //
HELIX_DURATION = 477, //
STORMSURGE_EFFECT = 400, //
SUBLIMATION_BONUS = 401, //
GRIMOIRE_SPELLCASTING = 489, // "Grimoire: Reduces spellcasting time" bonus
STRATAGEM_RECAST = 1159, // Recast reduction in seconds
// Geo
CARDINAL_CHANT = 959,
CARDINAL_CHANT_BONUS = 1132, // Geomancy galero
INDI_DURATION = 960,
GEOMANCY_BONUS = 961, // Used to increase potency of "Geomancy +" items (only the highest value is counted)
WIDENED_COMPASS = 962,
MENDING_HALATION = 968, // This mod should never exceed 1 as the multiplier is the merit, this is basicaly just a bool mod
RADIAL_ARCANA = 969,
CURATIVE_RECANTATION = 970,
PRIMEVAL_ZEAL = 971,
FULL_CIRCLE = 1025, // Increases the initial multiplier on MP returned via Full Circle
BOLSTER_EFFECT = 1028, // Adds bonus duration as +N seconds
LIFE_CYCLE_EFFECT = 1029, // Adds bonus HP% returned to the luopan when using Life Cycle
AURA_SIZE = 1030, // Used to extend aura size, the formula is 6.25 + (PEntity->getMod(Mod::AURA_SIZE) / 100) so adding 100 will make this 7.25
ENSPELL = 341, // stores the type of enspell active (0 if nothing)
ENSPELL_DMG = 343, // stores the base damage of the enspell before reductions
ENSPELL_DMG_BONUS = 432, //
ENSPELL_CHANCE = 856, // Chance of enspell activating (0 = 100%, 10 = 10%, 30 = 30%, ...)
SPIKES = 342, // store the type of spike spell active (0 if nothing)
SPIKES_DMG = 344, // stores the base damage of the spikes before reductions
SPIKES_DMG_BONUS = 1079, // Increases Blaze/Ice/Shock spikes damage by percentage (e.g. mod value 50 = +50% spikes damage)
TP_BONUS = 345, //
SAVETP = 880, // SAVETP Effect for Miser's Roll / ATMA / Hagakure.
CONSERVE_TP = 944, // Conserve TP trait, random chance between 10 and 200 TP
// Rune Fencer
INQUARTATA = 963, // Increases parry rate by a flat %.
ENHANCES_BATTUTA = 1004, // Used by RUN merit point cat 2 to add +N% bonus damage to parry spikes during Battuta effect
ENHANCES_ELEMENTAL_SFORZO = 1005, // Bonus duration
ENHANCES_SLEIGHT_OF_SWORD = 1006, // Used by RUN merit point cat 2 to add +N Subtle Blow to Swordplay
ENHANCES_INSPIRATION = 1007, // Used by RUN merit point cat 2 to add +N Fast Cast to Vallation/Valiance
SWORDPLAY = 1008, // Adds bonus starting ticks to Swordplay
LIEMENT = 1009, // Adds bonus duration as +N seconds
VALIANCE_VALLATION_DURATION = 1010, // Adds bonus duration as +N seconds
PFLUG = 1011, // Adds flat additional all-resist rate in +N%
VIVACIOUS_PULSE_POTENCY = 1012, // Adds final HP bonus +N% to calculation of Vivacious Pulse
AUGMENTS_VIVACIOUS_PULSE = 1013, // Adds random erase/-na to Vivacious Pulse
RAYKE_DURATION = 1014, // Adds bonus duration as +N seconds
ODYLLIC_SUBTERFUGE_DURATION = 1015, // Adds bonus duration as +N seconds
SWIPE = 1016, // Adds bonus damage to the Swipe/Lunge magic damage calculation
LIEMENT_DURATION = 1017, // Adds bonus duration as +N seconds
GAMBIT_DURATION = 1018, // Adds bonus duration as +N seconds
EMBOLDEN_DURATION = 1019, // Adds bonus duration as +N seconds
LIEMENT_EXTENDS_TO_AREA = 1020, // Epeolatry's (RUN Ergon weapon) special effect, makes Liement AoE to party instead of self target only.
INSPIRATION_FAST_CAST = 1021, // Inspiration Fast Cast, additive with Fast Cast with a combined cap beyond 80%
PARRY_SPIKES = 1022, // Battuta parry spikes rate
PARRY_SPIKES_DMG = 1023, // Battuta parry spikes damage
SPECIAL_ATTACK_EVASION = 1024, // Foil "Special Attack" evasion
AUGMENTS_SLEIGHT_OF_SWORD = 277, // Enhances bonus "Subtle Blow" per merit.
FIRE_STAFF_BONUS = 347,
ICE_STAFF_BONUS = 348,
WIND_STAFF_BONUS = 349,
EARTH_STAFF_BONUS = 350,
THUNDER_STAFF_BONUS = 351,
WATER_STAFF_BONUS = 352,
LIGHT_STAFF_BONUS = 353,
DARK_STAFF_BONUS = 354,
FIRE_AFFINITY_PERP = 553,
ICE_AFFINITY_PERP = 554,
WIND_AFFINITY_PERP = 555,
EARTH_AFFINITY_PERP = 556,
THUNDER_AFFINITY_PERP = 557,
WATER_AFFINITY_PERP = 558,
LIGHT_AFFINITY_PERP = 559,
DARK_AFFINITY_PERP = 560,
// Special Modifier+
ADDS_WEAPONSKILL = 355, //
ADDS_WEAPONSKILL_DYN = 356, // In Dynamis
STEALTH = 358, //
SNEAK_DURATION = 946, // Additional duration in seconds
INVISIBLE_DURATION = 947, // Additional duration in seconds
DMG_RATING = 287, // adds damage rating to weapon (+DMG augments, maneater/blau dolch etc hidden effects)
MAIN_DMG_RATING = 366, // adds damage rating to mainhand weapon
SUB_DMG_RATING = 367, // adds damage rating to off hand weapon
RANGED_DMG_RATING = 376, // adds damage rating to ranged weapon
MAIN_DMG_RANK = 377, // adds weapon rank to main weapon http://wiki.bluegartr.com/bg/Weapon_Rank
SUB_DMG_RANK = 378, // adds weapon rank to sub weapon
RANGED_DMG_RANK = 379, // adds weapon rank to ranged weapon
REGAIN = 368, // auto regain TP (from items) | this is multiplied by 10 e.g. 20 is 2% TP
REGAIN_DOWN = 406, // plague, reduce tp
REFRESH = 369, // auto refresh from equipment
REFRESH_DOWN = 405, // plague, reduce mp
REGEN = 370, // auto regen from equipment
REGEN_DOWN = 404, // poison
CURE_POTENCY = 374, // % cure potency | bonus from gear is capped at 50
CURE_POTENCY_II = 260, // % cure potency II | bonus from gear is capped at 30
CURE_POTENCY_RCVD = 375, // % potency of received cure | healer's roll, some items have this
CURE_POTENCY_BONUS = 1051, // TODO: Increases amount healed by Cure spells (fixed amount)
DELAYP = 380, // delay addition percent (does not affect tp gain)
RANGED_DELAYP = 381, // ranged delay addition percent (does not affect tp gain)
SHIELD_BASH = 385, //
KICK_DMG = 386, // increases kick attack damage
WEAPON_BASH = 392, //
WYVERN_BREATH = 402, //
// Gear set modifiers
DA_DOUBLE_DMG_RATE = 408, // Double attack's double damage chance %.
TA_TRIPLE_DMG_RATE = 409, // Triple attack's triple damage chance %.
ZANSHIN_DOUBLE_DAMAGE = 410, // Zanshin's double damage chance %.
RAPID_SHOT_DOUBLE_DAMAGE = 479, // Rapid shot's double damage chance %.
EXTRA_DUAL_WIELD_ATTACK = 481, // Chance to land an extra attack when dual wielding
EXTRA_KICK_ATTACK = 482, // Occasionally allows a second Kick Attack during an attack round without the use of Footwork.
SAMBA_DOUBLE_DAMAGE = 415, // Double damage chance when samba is up.
QUICK_DRAW_TRIPLE_DAMAGE = 417, // Chance to do triple damage with quick draw.
BAR_ELEMENT_NULL_CHANCE = 418, // Bar Elemental spells will occasionally NULLify damage of the same element.
GRIMOIRE_INSTANT_CAST = 419, // Spells that match your current Arts will occasionally cast instantly, without recast.
QUAD_ATTACK = 430, // Quadruple attack chance.
// Reraise (Auto Reraise, used by gear)
RERAISE_I = 456, // Reraise.
RERAISE_II = 457, // Reraise II.
RERAISE_III = 458, // Reraise III.
ABSORB_DMG_TO_MP = 516, // Unlike PLD gear mod, works on all damage types (Ethereal Earring)
ITEM_ADDEFFECT_LVADJUST = 278, // level correction factor to use, if any
ITEM_ADDEFFECT_PLACEHLD = 279, // placeholder, want to keep these together and 99% sure we'll use this
ITEM_ADDEFFECT_DSTAT = 280, // value = attacker modifier to use as bonus dmg (mnd, int, etc)
ITEM_ADDEFFECT_TYPE = 431, // see procType table in scripts\globals\additional_effects.lua
ITEM_SUBEFFECT = 499, // Animation ID of Spikes and Additional Effects
ITEM_ADDEFFECT_DMG = 500, // Damage of an items Additional Effect or Spikes
ITEM_ADDEFFECT_CHANCE = 501, // Chance of an items Additional Effect or Spikes
ITEM_ADDEFFECT_ELEMENT = 950, // Element of the Additional Effect or Spikes, for resist purposes
ITEM_ADDEFFECT_STATUS = 951, // Status Effect ID to try to apply via Additional Effect or Spikes
ITEM_ADDEFFECT_POWER = 952, // Base Power for effect in MOD_ITEM_ADDEFFECT_STATUS. Must be used for debuffs/buffs.
ITEM_ADDEFFECT_DURATION = 953, // Base Duration for effect in MOD_ITEM_ADDEFFECT_STATUS
GOV_CLEARS = 496, // 4% bonus per Grounds of Valor Page clear
AFTERMATH = 256, // Aftermath ID
EXTRA_DMG_CHANCE = 506, // Proc rate of OCC_DO_EXTRA_DMG. 111 would be 11.1%
OCC_DO_EXTRA_DMG = 507, // Multiplier for "Occasionally do x times normal damage". 250 would be 2.5 times damage.
REM_OCC_DO_DOUBLE_DMG = 863, // Proc rate for REM Aftermaths that apply "Occasionally do double damage"
REM_OCC_DO_TRIPLE_DMG = 864, // Proc rate for REM Aftermaths that apply "Occasionally do triple damage"
REM_OCC_DO_DOUBLE_DMG_RANGED = 867, // Ranged attack specific
REM_OCC_DO_TRIPLE_DMG_RANGED = 868, // Ranged attack specific
MYTHIC_OCC_ATT_TWICE = 865, // Proc rate for "Occasionally attacks twice"
MYTHIC_OCC_ATT_THRICE = 866, // Proc rate for "Occasionally attacks thrice"
APPRECIATE_GYSAHL_GREENS = 156, // Enhances food effect of Gysahl Greens
EAT_RAW_FISH = 412, // Without this, only Mithra can eat raw fish (item cannot be used)
EAT_RAW_MEAT = 413, // Without this, only Galka can eat raw meat (item cannot be used)
DRINK_DISTILLED = 159, // Without this, Distilled Water cannot be consumed (item can still be used)
EQUIPMENT_ONLY_RACE = 276, // An 8-bit flag that denotes that only a certain race(s) can use this equipment (0 means all races can use)
ENHANCES_CURSNA_RCVD = 67, // Potency of "Cursna" effects received
ENHANCES_CURSNA = 310, // Used by gear with the "Enhances Cursna" or "Cursna+" attribute
ENHANCES_HOLYWATER = 495, // Used by gear with the "Enhances Holy Water" or "Holy Water+" attribute
ENHANCES_PROT_SHELL_RCVD = 977, // Enhances Protect and Shell Effects Received (Binary MOD)
ENHANCES_PROT_RCVD = 1050, // TODO: Enhances Protect Received (Percent)
RETALIATION = 414, // Increases damage of Retaliation hits
CLAMMING_IMPROVED_RESULTS = 509, //
CLAMMING_REDUCED_INCIDENTS = 510, //
CHOCOBO_RIDING_TIME = 511, // Increases chocobo riding time
HARVESTING_RESULT = 513, // Improves harvesting results
LOGGING_RESULT = 514, // Improves logging results
MINING_RESULT = 515, // Improves mining results
EGGHELM = 517,
SHIELDBLOCKRATE = 518, // Affects shield block rate, percent based
DIA_DOT = 313, // Increases the DoT damage of Dia
ENH_DRAIN_ASPIR = 315, // % damage boost to Drain and Aspir
AUGMENTS_ABSORB_LIBERATOR = 521, // Direct Absorb spell increase while Liberator is equipped (percentage based) (Augments "Absorb" spells)
AMMO_SWING = 523, // Follow-up swing rate w/ virtue stone ammo (Jailer weapons). Does nothing for non-players.
AUGMENTS_CONVERT = 525, // Convert HP to MP Ratio Multiplier. Value = MP multiplier rate.
AUGMENTS_SA = 526, // Adds Critical Attack Bonus to Sneak Attack, percentage based.
AUGMENTS_TA = 527, // Adds Critical Attack Bonus to Trick Attack, percentage based.
AUGMENTS_FEINT = 502, // Feint will give another -10 Evasion per merit level
AUGMENTS_ASSASSINS_CHARGE = 886, // Gives Assassin's Charge +1% Critical Hit Rate per merit level
AUGMENTS_AMBUSH = 887, // Gives +1% Triple Attack per merit level when Ambush conditions are met
AUGMENTS_AURA_STEAL = 889, // 20% chance of 2 effects to be dispelled or stolen per merit level
AUGMENTS_CONSPIRATOR = 912, // Applies Conspirator benefits to player at the top of the hate list
ENHANCES_REFRESH = 529, // "Enhances Refresh" adds +1 per modifier to spell's tick result.
NO_SPELL_MP_DEPLETION = 530, // % to not deplete MP on spellcast.
STONESKIN_BONUS_HP = 539, // Bonus "HP" granted to Stoneskin spell.
DAY_NUKE_BONUS = 565, // Bonus damage from "Elemental magic affected by day" (Sorc. Tonban)
IRIDESCENCE = 566, // Iridescence trait (additional weather damage/penalty)
BARSPELL_AMOUNT = 567, // Additional elemental resistance granted by bar- spells
BARSPELL_MDEF_BONUS = 827, // Extra magic defense bonus granted to the bar- spell effect
RAPTURE_AMOUNT = 568, // Bonus amount added to Rapture effect
EBULLIENCE_AMOUNT = 569, // Bonus amount added to Ebullience effect
AQUAVEIL_COUNT = 832, // Modifies the amount of hits that Aquaveil absorbs before being removed
ENH_MAGIC_DURATION = 890, // Enhancing Magic Duration increase %
ENHANCES_COURSERS_ROLL = 891, // Courser's Roll Bonus % chance
ENHANCES_CASTERS_ROLL = 892, // Caster's Roll Bonus % chance
ENHANCES_BLITZERS_ROLL = 893, // Blitzer's Roll Bonus % chance
ENHANCES_ALLIES_ROLL = 894, // Allies' Roll Bonus % chance
ENHANCES_TACTICIANS_ROLL = 895, // Tactician's Roll Bonus % chance
OCCULT_ACUMEN = 902, // Grants bonus TP when dealing damage with elemental or dark magic
QUICK_MAGIC = 909, // Percent chance spells cast instantly (also reduces recast to 0, similar to Chainspell)
// Crafting food effects
SYNTH_SUCCESS_RATE = 851, // Success rate bonus (percent) for all synths except desynths.
SYNTH_SUCCESS_RATE_DESYNTHESIS = 916, // Success rate bonus (percent) for desynths, specifically.
SYNTH_SUCCESS_RATE_WOODWORKING = 1098, // Success rate bonus (percent) for Woodworking, specifically.
SYNTH_SUCCESS_RATE_SMITHING = 1099, // Success rate bonus (percent) for Smithing, specifically.
SYNTH_SUCCESS_RATE_GOLDSMITHING = 1100, // Success rate bonus (percent) for Goldsmithing, specifically.
SYNTH_SUCCESS_RATE_CLOTHCRAFT = 1101, // Success rate bonus (percent) for Clothcraft, specifically.
SYNTH_SUCCESS_RATE_LEATHERCRAFT = 1102, // Success rate bonus (percent) for Leahercraft, specifically.
SYNTH_SUCCESS_RATE_BONECRAFT = 1103, // Success rate bonus (percent) for Bonecraft, specifically.
SYNTH_SUCCESS_RATE_ALCHEMY = 1104, // Success rate bonus (percent) for Alchemy, specifically.
SYNTH_SUCCESS_RATE_COOKING = 1105, // Success rate bonus (percent) for Cooking, specifically.
SYNTH_SKILL_GAIN = 852, // Synthesis skill gain rate
SYNTH_SPEED_WOODWORKING = 1106, // Escutcheon (Phase 3 & 4). Bonus to synth speed (Makes process faster. Assuming miliseconds)
SYNTH_SPEED_SMITHING = 1107, // Escutcheon (Phase 3 & 4). Bonus to synth speed (Makes process faster. Assuming miliseconds)
SYNTH_SPEED_GOLDSMITHING = 1108, // Escutcheon (Phase 3 & 4). Bonus to synth speed (Makes process faster. Assuming miliseconds)
SYNTH_SPEED_CLOTHCRAFT = 1109, // Escutcheon (Phase 3 & 4). Bonus to synth speed (Makes process faster. Assuming miliseconds)
SYNTH_SPEED_LEATHERCRAFT = 1110, // Escutcheon (Phase 3 & 4). Bonus to synth speed (Makes process faster. Assuming miliseconds)
SYNTH_SPEED_BONECRAFT = 1111, // Escutcheon (Phase 3 & 4). Bonus to synth speed (Makes process faster. Assuming miliseconds)
SYNTH_SPEED_ALCHEMY = 1112, // Escutcheon (Phase 3 & 4). Bonus to synth speed (Makes process faster. Assuming miliseconds)
SYNTH_SPEED_COOKING = 1113, // Escutcheon (Phase 3 & 4). Bonus to synth speed (Makes process faster. Assuming miliseconds)
SYNTH_ANTI_NQ_WOODWORKING = 1114, // Escutcheon (Phase 4) "Artisanal Knowledge" Enchantment. Prevents NQ results, making them fails.
SYNTH_ANTI_NQ_SMITHING = 1115, // Escutcheon (Phase 4) "Artisanal Knowledge" Enchantment. Prevents NQ results, making them fails.
SYNTH_ANTI_NQ_GOLDSMITHING = 1116, // Escutcheon (Phase 4) "Artisanal Knowledge" Enchantment. Prevents NQ results, making them fails.
SYNTH_ANTI_NQ_CLOTHCRAFT = 1117, // Escutcheon (Phase 4) "Artisanal Knowledge" Enchantment. Prevents NQ results, making them fails.
SYNTH_ANTI_NQ_LEATHERCRAFT = 1118, // Escutcheon (Phase 4) "Artisanal Knowledge" Enchantment. Prevents NQ results, making them fails.
SYNTH_ANTI_NQ_BONECRAFT = 1119, // Escutcheon (Phase 4) "Artisanal Knowledge" Enchantment. Prevents NQ results, making them fails.
SYNTH_ANTI_NQ_ALCHEMY = 1120, // Escutcheon (Phase 4) "Artisanal Knowledge" Enchantment. Prevents NQ results, making them fails.
SYNTH_ANTI_NQ_COOKING = 1121, // Escutcheon (Phase 4) "Artisanal Knowledge" Enchantment. Prevents NQ results, making them fails.
SYNTH_ANTI_HQ_WOODWORKING = 144, // Craft Rings. They ONLY prevent their associated skill type HQs, even if item description doesn't state it.
SYNTH_ANTI_HQ_SMITHING = 145, // Craft Rings. They ONLY prevent their associated skill type HQs, even if item description doesn't state it.
SYNTH_ANTI_HQ_GOLDSMITHING = 146, // Craft Rings. They ONLY prevent their associated skill type HQs, even if item description doesn't state it.
SYNTH_ANTI_HQ_CLOTHCRAFT = 147, // Craft Rings. They ONLY prevent their associated skill type HQs, even if item description doesn't state it.
SYNTH_ANTI_HQ_LEATHERCRAFT = 148, // Craft Rings. They ONLY prevent their associated skill type HQs, even if item description doesn't state it.
SYNTH_ANTI_HQ_BONECRAFT = 149, // Craft Rings. They ONLY prevent their associated skill type HQs, even if item description doesn't state it.
SYNTH_ANTI_HQ_ALCHEMY = 150, // Craft Rings. They ONLY prevent their associated skill type HQs, even if item description doesn't state it.
SYNTH_ANTI_HQ_COOKING = 151, // Craft Rings. They ONLY prevent their associated skill type HQs, even if item description doesn't state it.
SYNTH_HQ_RATE = 862, // High-quality success rate (not a percent)
SYNTH_HQ_RATE_WOODWORKING = 1122, // High-quality success rate (not a percent) for specific skill. Used by Escutcheon's enchantment.
SYNTH_HQ_RATE_SMITHING = 1123, // High-quality success rate (not a percent) for specific skill. Used by Escutcheon's enchantment.
SYNTH_HQ_RATE_GOLDSMITHING = 1124, // High-quality success rate (not a percent) for specific skill. Used by Escutcheon's enchantment.
SYNTH_HQ_RATE_CLOTHCRAFT = 1125, // High-quality success rate (not a percent) for specific skill. Used by Escutcheon's enchantment.
SYNTH_HQ_RATE_LEATHERCRAFT = 1126, // High-quality success rate (not a percent) for specific skill. Used by Escutcheon's enchantment.
SYNTH_HQ_RATE_BONECRAFT = 1127, // High-quality success rate (not a percent) for specific skill. Used by Escutcheon's enchantment.
SYNTH_HQ_RATE_ALCHEMY = 1128, // High-quality success rate (not a percent) for specific skill. Used by Escutcheon's enchantment.
SYNTH_HQ_RATE_COOKING = 1129, // High-quality success rate (not a percent) for specific skill. Used by Escutcheon's enchantment.
SYNTH_MATERIAL_LOSS = 861, // Material loss rate (percent) for all synths.
SYNTH_MATERIAL_LOSS_WOODWORKING = 925, // Material loss rate (percent) when doing woodworking
SYNTH_MATERIAL_LOSS_SMITHING = 926, // Material loss rate (percent) when doing smithing
SYNTH_MATERIAL_LOSS_GOLDSMITHING = 927, // Material loss rate (percent) when doing goldsmithing
SYNTH_MATERIAL_LOSS_CLOTHCRAFT = 928, // Material loss rate (percent) when doing clothcraft
SYNTH_MATERIAL_LOSS_LEATHERCRAFT = 929, // Material loss rate (percent) when doing leathercraft
SYNTH_MATERIAL_LOSS_BONECRAFT = 930, // Material loss rate (percent) when doing bonecraft
SYNTH_MATERIAL_LOSS_ALCHEMY = 931, // Material loss rate (percent) when doing alchemy
SYNTH_MATERIAL_LOSS_COOKING = 932, // Material loss rate (percent) when doing cooking
SYNTH_MATERIAL_LOSS_FIRE = 917, // Material loss rate (percent) when using a fire crystal (or HQ version)
SYNTH_MATERIAL_LOSS_ICE = 918, // Material loss rate (percent) when using a ice crystal (or HQ version)
SYNTH_MATERIAL_LOSS_WIND = 919, // Material loss rate (percent) when using a wind crystal (or HQ version)
SYNTH_MATERIAL_LOSS_EARTH = 920, // Material loss rate (percent) when using a earth crystal (or HQ version)
SYNTH_MATERIAL_LOSS_THUNDER = 921, // Material loss rate (percent) when using a lightning crystal (or HQ version)
SYNTH_MATERIAL_LOSS_WATER = 922, // Material loss rate (percent) when using a water crystal (or HQ version)
SYNTH_MATERIAL_LOSS_LIGHT = 923, // Material loss rate (percent) when using a light crystal (or HQ version)
SYNTH_MATERIAL_LOSS_DARK = 924, // Material loss rate (percent) when using a dark crystal (or HQ version)
// Weaponskill %damage modifiers
// The following modifier should not ever be set, but %damage modifiers to weaponskills use the next 255 IDs (this modifier + the WSID)
// For example, +10% damage to Chant du Cygne would be ID 570 + 225 (795)
WEAPONSKILL_DAMAGE_BASE = 570,
ALL_WSDMG_ALL_HITS = 840, // Generic (all Weaponskills) damage, on all hits.
// Per https://www.bg-wiki.com/bg/Weapon_Skill_Damage we need all 3..
ALL_WSDMG_FIRST_HIT = 841, // Generic (all Weaponskills) damage, first hit only.
WS_NO_DEPLETE = 949, // % chance a Weaponskill depletes no TP.
WS_STR_BONUS = 980, // % bonus to str_wsc.
WS_DEX_BONUS = 957, // % bonus to dex_wsc.
WS_VIT_BONUS = 981, // % bonus to vit_wsc.
WS_AGI_BONUS = 982, // % bonus to agi_wsc.
WS_INT_BONUS = 983, // % bonus to int_wsc.
WS_MND_BONUS = 984, // % bonus to mnd_wsc.
WS_CHR_BONUS = 985, // % bonus to chr_wsc.
// Pet Modifiers (Job Point Gifts)
PET_ATK_DEF = 990, // Increases pet physical attack, ranged attack, and physical defense
PET_ACC_EVA = 991, // Increases pet physical accuracy, ranged accuracy, and evasion
PET_MAB_MDB = 992, // Increases pet magic attack and magic defense
PET_MACC_MEVA = 993, // Increases pet magic accuracy and evasion
PET_ATTR_BONUS = 994, // Increases pet attributes
PET_TP_BONUS = 995, // Increases pet TP bonus
EXPERIENCE_RETAINED = 914, // Experience points retained upon death (this is a percentage)
CAPACITY_BONUS = 915, // Capacity point bonus granted
CONQUEST_BONUS = 933, // Conquest points bonus granted (percentage)
CONQUEST_REGION_BONUS = 934, // Increases the influence points awarded to the player's nation when receiving conquest points
CAMPAIGN_BONUS = 935, // Increases the evaluation for allied forces by percentage
SUBTLE_BLOW_II = 973, // Subtle Blow II Effect (Cap 50%) Total Effect (SB + SB_II cap 75%)
GARDENING_WILT_BONUS = 975, // Increases the number of Vanadays a plant can survive before it wilts
SUPERIOR_LEVEL = 997, // SU0..5
ONE_HOUR_RECAST = 996, // Decreases the recast time of one-hour abilities by n minutes.
// AF3 Set Bonus Modifiers
AUGMENT_CONSERVE_MP = 1031, // Percent chance to deal extra damage based on Conserve MP Amount (BLM AF3 Sets)
AUGMENT_COMPOSURE = 1032, // Percent Enhancing Duration Extension for Others (RDM AF3 Sets)
AUGMENT_DAMAGE_HP = 1033, // Percent chance to increase damage based on player HP% (DRK AF3 Sets)
AUGMENT_DAMAGE_PET_HP = 1034, // Percent chance to increase damage based on pet HP% (BST/DRG AF3 Sets)
AUGMENT_BLOOD_BOON = 1035, // Percent chance to deal extra damage based on Blood Boon Amount (SMN AF3 Sets)
AUGMENT_BLU_MAGIC = 1036, // Percent chance for BLU magic to receive 3x WSC value for spell (BLU AF3 Sets)
GEOMANCY_MP_NO_DEPLETE = 1037, // Percent chance for Geomancy to cost 0 MP (GEO AF3 Sets)
DIG_BYPASS_FATIGUE = 1074, // Chocobo digging modifier found in "Blue Race Silks". Modifier works as a direct percent.
DIG_RARE_ABILITY = 1133, // Chocobo digging modifier found in "Black Chocobo Suit" and "Denim Pants +1".
BREATH_DMG_DEALT = 1075, // Breath damage dealt
DAMAGE_LIMIT = 1080, // Damage Limit increase, found on some traits. It's a flat value added to max pDIF (maxpDIF + DL/100) https://www.bg-wiki.com/ffxi/Damage_Limit%2B
DAMAGE_LIMITP = 1081, // Damage Limit +% increase, found on some gear. It's a multiplier added after flat Damage Limit ((maxpDIF + DL/100)*(100 + DLP/100)/100) https://www.ffxiah.com/forum/topic/56649/physical-damage-limit/
MAGIC_BURST_BONUS_CAPPED = 487, // Magic Burst Bonus I from gear, Ancient Magic Merits, Innin merits and Atmas. Cap at 40% bonus (1.4 multiplier)
MAGIC_BURST_BONUS_UNCAPPED = 274, // Magic Burst Bonus II from gear, JP Gifts, BLM JPs and Job traits. No known cap.
DESPAWN_TIME_REDUCTION = 1134, // Reduction in seconds. 1 = 1 second less to despawn.
PARRY_HP_RECOVERY = 1135, // Recover <Mod Value> HP on successful parry.
// TODO: These mods are not yet implemented.
REWARD_RECAST = 1152, // TODO: Reward recast time reduction (seconds)
MOGHANCEMENT_GIL_BONUS_P = 1158, // Kill shot gil bonus (yes, really)
// IF YOU ADD ANY NEW MODIFIER HERE, ADD IT IN scripts/enum/mod.lua ASWELL!
// The spares take care of finding the next ID to use so long as we don't forget to list IDs that have been freed up by refactoring.
// 570 through 825 used by WS DMG mods these are not spares.
//
// SPARE IDs: 1170 and onward
};
// temporary workaround for using enum class as unordered_map key until compilers support it
struct EnumClassHash
{
template <typename T>
std::size_t operator()(T t) const
{
return static_cast<std::size_t>(t);
}
};
/************************************************************************
* Modifier Class *
************************************************************************/
class CModifier
{
public:
Mod getModID() const;
int16 getModAmount() const;
void setModAmount(int16 amount);
CModifier(Mod type, int16 amount = 0);
private:
Mod m_id{ Mod::NONE };
int16 m_amount{ 0 };
};
enum class PetModType
{
All = 0,
Avatar = 1,
Wyvern = 2,
Automaton = 3,
Harlequin = 4,
Valoredge = 5,
Sharpshot = 6,
Stormwaker = 7,
Luopan = 8
};
class CPetModifier : public CModifier
{
public:
CPetModifier(Mod type, PetModType pettype, int16 amount = 0);
PetModType getPetModType() const;
private:
PetModType m_pettype{ PetModType::All };
};
#endif
| 412 | 0.954164 | 1 | 0.954164 | game-dev | MEDIA | 0.994033 | game-dev | 0.844195 | 1 | 0.844195 |
LittleEndianLtd/SpectrumWorx | 5,523 | 3rd_party/JUCE/trunk/modules/juce_gui_basics/commands/juce_ApplicationCommandTarget.cpp | /*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE 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.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
class ApplicationCommandTarget::CommandMessage : public MessageManager::MessageBase
{
public:
CommandMessage (ApplicationCommandTarget* const target, const InvocationInfo& inf)
: owner (target), info (inf)
{
}
void messageCallback() override
{
if (ApplicationCommandTarget* const target = owner)
target->tryToInvoke (info, false);
}
private:
WeakReference<ApplicationCommandTarget> owner;
const InvocationInfo info;
JUCE_DECLARE_NON_COPYABLE (CommandMessage)
};
//==============================================================================
ApplicationCommandTarget::ApplicationCommandTarget()
#ifdef LE_PATCHED_JUCE
: masterReference( *this )
#endif // LE_PATCHED_JUCE
{
}
ApplicationCommandTarget::~ApplicationCommandTarget()
{
masterReference.clear();
}
//==============================================================================
bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
{
if (isCommandActive (info.commandID))
{
if (async)
{
(new CommandMessage (this, info))->post();
return true;
}
else
{
const bool success = perform (info);
jassert (success); // Hmm.. your target claimed that it could perform this command, but failed to do so.
// If it can't do it at the moment for some reason, it should clear the 'isActive' flag
// when it returns the command's info.
return success;
}
}
return false;
}
ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
{
if (Component* const c = dynamic_cast <Component*> (this))
return c->findParentComponentOfClass<ApplicationCommandTarget>();
return nullptr;
}
ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
{
ApplicationCommandTarget* target = this;
int depth = 0;
while (target != nullptr)
{
Array <CommandID> commandIDs;
target->getAllCommands (commandIDs);
if (commandIDs.contains (commandID))
return target;
target = target->getNextCommandTarget();
++depth;
jassert (depth < 100); // could be a recursive command chain??
jassert (target != this); // definitely a recursive command chain!
if (depth > 100 || target == this)
break;
}
if (target == nullptr)
{
target = JUCEApplication::getInstance();
if (target != nullptr)
{
Array <CommandID> commandIDs;
target->getAllCommands (commandIDs);
if (commandIDs.contains (commandID))
return target;
}
}
return nullptr;
}
bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
{
ApplicationCommandInfo info (commandID);
info.flags = ApplicationCommandInfo::isDisabled;
getCommandInfo (commandID, info);
return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
}
//==============================================================================
bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
{
ApplicationCommandTarget* target = this;
int depth = 0;
while (target != nullptr)
{
if (target->tryToInvoke (info, async))
return true;
target = target->getNextCommandTarget();
++depth;
jassert (depth < 100); // could be a recursive command chain??
jassert (target != this); // definitely a recursive command chain!
if (depth > 100 || target == this)
break;
}
if (target == nullptr)
{
target = JUCEApplication::getInstance();
if (target != nullptr)
return target->tryToInvoke (info, async);
}
return false;
}
bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
{
ApplicationCommandTarget::InvocationInfo info (commandID);
info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
return invoke (info, asynchronously);
}
//==============================================================================
ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID command)
: commandID (command),
commandFlags (0),
invocationMethod (direct),
originatingComponent (nullptr),
isKeyDown (false),
millisecsSinceKeyPressed (0)
{
}
| 412 | 0.924018 | 1 | 0.924018 | game-dev | MEDIA | 0.345898 | game-dev | 0.970024 | 1 | 0.970024 |
kunitoki/yup | 2,708 | thirdparty/rive/include/rive/generated/assets/file_asset_base.hpp | #ifndef _RIVE_FILE_ASSET_BASE_HPP_
#define _RIVE_FILE_ASSET_BASE_HPP_
#include <string>
#include "rive/assets/asset.hpp"
#include "rive/core/field_types/core_bytes_type.hpp"
#include "rive/core/field_types/core_string_type.hpp"
#include "rive/core/field_types/core_uint_type.hpp"
#include "rive/span.hpp"
namespace rive
{
class FileAssetBase : public Asset
{
protected:
typedef Asset Super;
public:
static const uint16_t typeKey = 103;
/// Helper to quickly determine if a core object extends another without
/// RTTI at runtime.
bool isTypeOf(uint16_t typeKey) const override
{
switch (typeKey)
{
case FileAssetBase::typeKey:
case AssetBase::typeKey:
return true;
default:
return false;
}
}
uint16_t coreType() const override { return typeKey; }
static const uint16_t assetIdPropertyKey = 204;
static const uint16_t cdnUuidPropertyKey = 359;
static const uint16_t cdnBaseUrlPropertyKey = 362;
protected:
uint32_t m_AssetId = 0;
std::string m_CdnBaseUrl = "https://public.rive.app/cdn/uuid";
public:
inline uint32_t assetId() const { return m_AssetId; }
void assetId(uint32_t value)
{
if (m_AssetId == value)
{
return;
}
m_AssetId = value;
assetIdChanged();
}
virtual void decodeCdnUuid(Span<const uint8_t> value) = 0;
virtual void copyCdnUuid(const FileAssetBase& object) = 0;
inline const std::string& cdnBaseUrl() const { return m_CdnBaseUrl; }
void cdnBaseUrl(std::string value)
{
if (m_CdnBaseUrl == value)
{
return;
}
m_CdnBaseUrl = value;
cdnBaseUrlChanged();
}
void copy(const FileAssetBase& object)
{
m_AssetId = object.m_AssetId;
copyCdnUuid(object);
m_CdnBaseUrl = object.m_CdnBaseUrl;
Asset::copy(object);
}
bool deserialize(uint16_t propertyKey, BinaryReader& reader) override
{
switch (propertyKey)
{
case assetIdPropertyKey:
m_AssetId = CoreUintType::deserialize(reader);
return true;
case cdnUuidPropertyKey:
decodeCdnUuid(CoreBytesType::deserialize(reader));
return true;
case cdnBaseUrlPropertyKey:
m_CdnBaseUrl = CoreStringType::deserialize(reader);
return true;
}
return Asset::deserialize(propertyKey, reader);
}
protected:
virtual void assetIdChanged() {}
virtual void cdnUuidChanged() {}
virtual void cdnBaseUrlChanged() {}
};
} // namespace rive
#endif | 412 | 0.882455 | 1 | 0.882455 | game-dev | MEDIA | 0.440463 | game-dev,graphics-rendering | 0.606959 | 1 | 0.606959 |
openremote/openremote | 6,369 | model/src/main/java/org/openremote/model/asset/impl/ElectricityStorageAsset.java | /*
* Copyright 2020, OpenRemote Inc.
*
* See the CONTRIBUTORS.txt file in the distribution for a
* full listing of individual contributors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.openremote.model.asset.impl;
import org.openremote.model.attribute.AttributeExecuteStatus;
import org.openremote.model.attribute.MetaItem;
import org.openremote.model.value.AttributeDescriptor;
import org.openremote.model.value.MetaItemType;
import org.openremote.model.value.ValueConstraint;
import org.openremote.model.value.ValueType;
import java.util.Optional;
import static org.openremote.model.Constants.*;
public abstract class ElectricityStorageAsset extends ElectricityAsset<ElectricityStorageAsset> {
public static final AttributeDescriptor<Boolean> SUPPORTS_EXPORT = new AttributeDescriptor<>("supportsExport", ValueType.BOOLEAN);
public static final AttributeDescriptor<Boolean> SUPPORTS_IMPORT = new AttributeDescriptor<>("supportsImport", ValueType.BOOLEAN);
public static final AttributeDescriptor<Double> ENERGY_LEVEL = new AttributeDescriptor<>("energyLevel", ValueType.POSITIVE_NUMBER,
new MetaItem<>(MetaItemType.READ_ONLY)
).withUnits(UNITS_KILO, UNITS_WATT, UNITS_HOUR);
public static final AttributeDescriptor<Double> ENERGY_CAPACITY = new AttributeDescriptor<>("energyCapacity", ValueType.POSITIVE_NUMBER)
.withUnits(UNITS_KILO, UNITS_WATT, UNITS_HOUR);
public static final AttributeDescriptor<Integer> ENERGY_LEVEL_PERCENTAGE = new AttributeDescriptor<>("energyLevelPercentage", ValueType.POSITIVE_INTEGER,
new MetaItem<>(MetaItemType.READ_ONLY)
).withUnits(UNITS_PERCENTAGE).withConstraints(new ValueConstraint.Min(0), new ValueConstraint.Max(100));
public static final AttributeDescriptor<Integer> ENERGY_LEVEL_PERCENTAGE_MAX = new AttributeDescriptor<>("energyLevelPercentageMax", ValueType.POSITIVE_INTEGER)
.withUnits(UNITS_PERCENTAGE).withConstraints(new ValueConstraint.Min(0), new ValueConstraint.Max(100));
public static final AttributeDescriptor<Integer> ENERGY_LEVEL_PERCENTAGE_MIN = new AttributeDescriptor<>("energyLevelPercentageMin", ValueType.POSITIVE_INTEGER)
.withUnits(UNITS_PERCENTAGE).withConstraints(new ValueConstraint.Min(0), new ValueConstraint.Max(100));
public static final AttributeDescriptor<Integer[][]> ENERGY_LEVEL_SCHEDULE = new AttributeDescriptor<>("energyLevelSchedule", ValueType.POSITIVE_INTEGER.asArray().asArray())
.withOptional(true);
public static final AttributeDescriptor<AttributeExecuteStatus> FORCE_CHARGE = new AttributeDescriptor<>("forceCharge", ValueType.EXECUTION_STATUS);
public static final AttributeDescriptor<Double> POWER_SETPOINT = ElectricityAsset.POWER_SETPOINT.withOptional(false);
public static final AttributeDescriptor<Double> POWER_IMPORT_MIN = ElectricityAsset.POWER_IMPORT_MIN.withOptional(true);
public static final AttributeDescriptor<Double> POWER_EXPORT_MIN = ElectricityAsset.POWER_EXPORT_MIN.withOptional(true);
public static final AttributeDescriptor<Double> CARBON_IMPORT = ElectricitySupplierAsset.CARBON_IMPORT.withOptional(true);
/**
* For use by hydrators (i.e. JPA/Jackson)
*/
protected ElectricityStorageAsset() {
}
public ElectricityStorageAsset(String name) {
super(name);
}
public Optional<Boolean> isSupportsExport() {
return getAttributes().getValue(SUPPORTS_EXPORT);
}
public ElectricityStorageAsset setSupportsExport(Boolean value) {
getAttributes().getOrCreate(SUPPORTS_EXPORT).setValue(value);
return this;
}
public Optional<Boolean> isSupportsImport() {
return getAttributes().getValue(SUPPORTS_IMPORT);
}
public ElectricityStorageAsset setSupportsImport(Boolean value) {
getAttributes().getOrCreate(SUPPORTS_IMPORT).setValue(value);
return this;
}
public Optional<Double> getEnergyCapacity() {
return getAttributes().getValue(ENERGY_CAPACITY);
}
public ElectricityStorageAsset setEnergyCapacity(Double value) {
getAttributes().getOrCreate(ENERGY_CAPACITY).setValue(value);
return this;
}
public Optional<Double> getEnergyLevel() {
return getAttributes().getValue(ENERGY_LEVEL);
}
public ElectricityStorageAsset setEnergyLevel(Double value) {
getAttributes().getOrCreate(ENERGY_LEVEL).setValue(value);
return this;
}
public Optional<Integer> getEnergyLevelPercentage() {
return getAttributes().getValue(ENERGY_LEVEL_PERCENTAGE);
}
public ElectricityStorageAsset setEnergyLevelPercentage(Integer value) {
getAttributes().getOrCreate(ENERGY_LEVEL_PERCENTAGE).setValue(value);
return this;
}
public Optional<Integer> getEnergyLevelPercentageMin() {
return getAttributes().getValue(ENERGY_LEVEL_PERCENTAGE_MIN);
}
public ElectricityStorageAsset setEnergyLevelPercentageMin(Integer value) {
getAttributes().getOrCreate(ENERGY_LEVEL_PERCENTAGE_MIN).setValue(value);
return this;
}
public Optional<Integer> getEnergyLevelPercentageMax() {
return getAttributes().getValue(ENERGY_LEVEL_PERCENTAGE_MAX);
}
public ElectricityStorageAsset setEnergyLevelPercentageMax(Integer value) {
getAttributes().getOrCreate(ENERGY_LEVEL_PERCENTAGE_MAX).setValue(value);
return this;
}
public Optional<Integer[][]> getEnergyLevelSchedule() {
return getAttributes().getValue(ENERGY_LEVEL_SCHEDULE);
}
public ElectricityStorageAsset setEnergyLevelSchedule(Integer[][] value) {
getAttributes().getOrCreate(ENERGY_LEVEL_SCHEDULE).setValue(value);
return this;
}
}
| 412 | 0.670867 | 1 | 0.670867 | game-dev | MEDIA | 0.453459 | game-dev | 0.894919 | 1 | 0.894919 |
JamesMcMahon/monocle-engine | 4,382 | Monocle/Particles/Particle.cs | using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
namespace Monocle
{
public struct Particle
{
public Entity Track;
public ParticleType Type;
public MTexture Source;
public bool Active;
public Color Color;
public Color StartColor;
public Vector2 Position;
public Vector2 Speed;
public float Size;
public float StartSize;
public float Life;
public float StartLife;
public float ColorSwitch;
public float Rotation;
public float Spin;
public bool SimulateFor(float duration)
{
if (duration > Life)
{
Life = 0;
Active = false;
return false;
}
else
{
var dt = Engine.TimeRate * (Engine.Instance.TargetElapsedTime.Milliseconds / 1000f);
if (dt > 0)
for (var t = 0f; t < duration; t += dt)
Update(dt);
return true;
}
}
public void Update(float? delta = null)
{
var dt = 0f;
if (delta.HasValue)
dt = delta.Value;
else
dt = (Type.UseActualDeltaTime ? Engine.RawDeltaTime : Engine.DeltaTime);
var ease = Life / StartLife;
//Life
Life -= dt;
if (Life <= 0)
{
Active = false;
return;
}
//Spin
if (Type.RotationMode == ParticleType.RotationModes.SameAsDirection)
{
if (Speed != Vector2.Zero)
Rotation = Speed.Angle();
}
else
Rotation += Spin * dt;
//Fade
float alpha;
if (Type.FadeMode == ParticleType.FadeModes.Linear)
alpha = ease;
else if (Type.FadeMode == ParticleType.FadeModes.Late)
alpha = Math.Min(1f, ease / .25f);
else if (Type.FadeMode == ParticleType.FadeModes.InAndOut)
{
if (ease > .75f)
alpha = 1 - ((ease - .75f) / .25f);
else if (ease < .25f)
alpha = ease / .25f;
else
alpha = 1f;
}
else
alpha = 1f;
//Color switch with alpha
if (alpha == 0)
Color = Color.Transparent;
else
{
if (Type.ColorMode == ParticleType.ColorModes.Static)
Color = StartColor;
else if (Type.ColorMode == ParticleType.ColorModes.Fade)
Color = Color.Lerp(Type.Color2, StartColor, ease);
else if (Type.ColorMode == ParticleType.ColorModes.Blink)
Color = (Calc.BetweenInterval(Life, .1f) ? StartColor : Type.Color2);
else if (Type.ColorMode == ParticleType.ColorModes.Choose)
Color = StartColor;
if (alpha < 1f)
Color *= alpha;
}
//Speed
Position += Speed * dt;
Speed += Type.Acceleration * dt;
Speed = Calc.Approach(Speed, Vector2.Zero, Type.Friction * dt);
if (Type.SpeedMultiplier != 1)
Speed *= (float)Math.Pow(Type.SpeedMultiplier, dt);
//Scale Out
if (Type.ScaleOut)
Size = StartSize * Ease.CubeOut(ease);
}
public void Render()
{
var renderAt = new Vector2((int)Position.X, (int)Position.Y);
if (Track != null)
renderAt += Track.Position;
Draw.SpriteBatch.Draw(Source.Texture, renderAt, Source.ClipRect, Color, Rotation, Source.Center, Size, SpriteEffects.None, 0);
}
public void Render(float alpha)
{
var renderAt = new Vector2((int)Position.X, (int)Position.Y);
if (Track != null)
renderAt += Track.Position;
Draw.SpriteBatch.Draw(Source.Texture, renderAt, Source.ClipRect, Color * alpha, Rotation, Source.Center, Size, SpriteEffects.None, 0);
}
}
}
| 412 | 0.825182 | 1 | 0.825182 | game-dev | MEDIA | 0.864079 | game-dev,graphics-rendering | 0.963568 | 1 | 0.963568 |
the-OmegaLabs/GoldBounce | 1,701 | src/main/java/net/ccbluex/liquidbounce/features/module/modules/movement/speedmodes/ncp/UNCPHop.kt | /*
* GoldBounce Hacked Client
* A free open source mixin-based injection hacked client for Minecraft using Minecraft Forge.
* https://github.com/bzym2/GoldBounce/
*/
package net.ccbluex.liquidbounce.features.module.modules.movement.speedmodes.ncp
import net.ccbluex.liquidbounce.features.module.modules.movement.speedmodes.SpeedMode
import net.ccbluex.liquidbounce.utils.MovementUtils.strafe
import net.ccbluex.liquidbounce.utils.extensions.isMoving
import net.ccbluex.liquidbounce.utils.extensions.tryJump
import net.minecraft.potion.Potion
object UNCPHop : SpeedMode("UNCPHop") {
private var speed = 0.0f
private var tick = 0
override fun onUpdate() {
val player = mc.thePlayer ?: return
if (player.isInWater || player.isInLava || player.isInWeb || player.isOnLadder) return
if (player.isMoving) {
if (player.onGround) {
speed = if (player.isPotionActive(Potion.moveSpeed)
&& player.getActivePotionEffect(Potion.moveSpeed).amplifier >= 1)
0.4563f else 0.3385f
player.tryJump()
} else {
speed *= 0.98f
}
if (player.isAirBorne && player.fallDistance > 2) {
mc.timer.timerSpeed = 1f
return
}
strafe(speed, false)
if (!player.onGround && ++tick % 3 == 0) {
mc.timer.timerSpeed = 1.0815f
tick = 0
} else {
mc.timer.timerSpeed = 0.9598f
}
} else {
mc.timer.timerSpeed = 1f
}
}
override fun onDisable() {
mc.timer.timerSpeed = 1f
}
} | 412 | 0.714276 | 1 | 0.714276 | game-dev | MEDIA | 0.806788 | game-dev | 0.770395 | 1 | 0.770395 |
GregHib/void | 2,854 | tools/src/main/kotlin/world/gregs/voidps/tools/convert/ConfigRewriter.kt | package world.gregs.voidps.tools.convert
import java.io.File
/**
* Rewrites file(s) with amendments
*/
object ConfigRewriter {
private val excluded = setOf(
"saradomin_flag",
"saradomin_cloak_castle_wars",
"saradomin_team_hood",
"saradomin_team_cape",
"zamorak_flag",
"zamorak_cloak_castle_wars",
"zamorak_team_hood",
"zamorak_team_cape",
)
private val included = mapOf(
"ancient_mace" to "bandos",
"granite_mace" to "bandos",
"unholy_symbol" to "zamorak",
"holy_symbol" to "saradomin",
"ring_of_devotion" to "saradomin",
"staff_of_light" to "saradomin",
"monks_robe_bottom" to "saradomin",
"monks_robe_top" to "saradomin",
)
@JvmStatic
fun main(args: Array<String>) {
val files = File("./data/").walkTopDown().filter { it.isFile && it.name.endsWith("items.toml") }
for (file in files) {
val lines = file.readLines()
val output = StringBuilder()
var block = ""
var different = false
for (i in lines.indices) {
val line = lines[i]
if (line.startsWith('[')) {
block = line.substringBefore(']').removePrefix("[")
}
if (line.startsWith("slot = ")) {
if (included.containsKey(block)) {
output.appendLine("god = \"${included[block]}\"")
different = true
} else if (block.contains("saradomin")) {
if (!excluded.contains(block)) {
output.appendLine("god = \"saradomin\"")
different = true
}
} else if (block.contains("zamorak") || block.contains("dagonhai")) {
if (!excluded.contains(block)) {
output.appendLine("god = \"zamorak\"")
different = true
}
} else if (block.contains("bandos")) {
output.appendLine("god = \"bandos\"")
different = true
} else if (block.contains("armadyl")) {
output.appendLine("god = \"armadyl\"")
different = true
} else if (block.contains("zaryte") || block.contains("torva") || block.contains("pernix") || block.contains("virtus")) {
output.appendLine("god = \"zaros\"")
different = true
}
}
output.appendLine(line)
}
if (different) {
file.writeText(output.toString())
}
}
}
}
| 412 | 0.869185 | 1 | 0.869185 | game-dev | MEDIA | 0.144263 | game-dev | 0.861604 | 1 | 0.861604 |
taniarascia/chip8 | 1,385 | web/web.js | let timer = 0
function cycle() {
timer++
if (timer % 5 === 0) {
cpu.tick()
timer = 0
}
if (!cpu.halted) {
cpu.step()
}
setTimeout(cycle, 3)
}
// Load a new ROM every time a new game is selected
async function loadRom() {
const rom = event.target.value
const response = await fetch(`./roms/${rom}`)
const arrayBuffer = await response.arrayBuffer()
const uint8View = new Uint8Array(arrayBuffer)
const romBuffer = new RomBuffer(uint8View)
cpu.interface.clearDisplay()
cpu.interface.disableSound()
cpu.load(romBuffer)
displayInstructions(rom)
}
function displayInstructions(rom) {
let instructions
switch (rom) {
case 'CONNECT4':
instructions = `Q = go left
E = go right
W = drop a coin
The coin color alternates with each play.
This game has no win detection.
`
break
case 'TETRIS':
instructions = `W = go left
E = go right
R = fall faster
Q = rotate piece`
break
case 'PONG':
instructions = `Player 1:
2 = go up
Q = go down
Player 2:
Z = go up
X = go down`
break
case 'INVADERS':
instructions = `W = start game
W = shoot
Q = go left
E = go right`
break
}
const instructionsDisplay = document.querySelector('.instructions')
instructionsDisplay.textContent = instructions
}
document.querySelector('select').addEventListener('change', loadRom)
cycle()
| 412 | 0.641056 | 1 | 0.641056 | game-dev | MEDIA | 0.523065 | game-dev | 0.844753 | 1 | 0.844753 |
id-Software/Enemy-Territory | 127,090 | src/botlib/be_ai_move.c | /*
===========================================================================
Wolfenstein: Enemy Territory GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Wolfenstein: Enemy Territory GPL Source Code (Wolf ET Source Code).
Wolf ET Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Wolf ET Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wolf ET Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Wolf: ET Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Wolf ET Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
/*****************************************************************************
* name: be_ai_move.c
*
* desc: bot movement AI
*
*
*****************************************************************************/
#include "../game/q_shared.h"
#include "l_memory.h"
#include "l_libvar.h"
#include "l_utils.h"
#include "l_script.h"
#include "l_precomp.h"
#include "l_struct.h"
#include "aasfile.h"
#include "../game/botlib.h"
#include "../game/be_aas.h"
#include "be_aas_funcs.h"
#include "be_interface.h"
#include "../game/be_ea.h"
#include "../game/be_ai_goal.h"
#include "../game/be_ai_move.h"
//#define DEBUG_AI_MOVE
//#define DEBUG_ELEVATOR
//#define DEBUG_GRAPPLE
//movement state
//NOTE: the moveflags MFL_ONGROUND, MFL_TELEPORTED and MFL_WATERJUMP must be set outside the movement code
typedef struct bot_movestate_s
{
//input vars (all set outside the movement code)
vec3_t origin; //origin of the bot
vec3_t velocity; //velocity of the bot
vec3_t viewoffset; //view offset
int entitynum; //entity number of the bot
int client; //client number of the bot
float thinktime; //time the bot thinks
int presencetype; //presencetype of the bot
vec3_t viewangles; //view angles of the bot
//state vars
int areanum; //area the bot is in
int lastareanum; //last area the bot was in
int lastgoalareanum; //last goal area number
int lastreachnum; //last reachability number
vec3_t lastorigin; //origin previous cycle
float lasttime;
int reachareanum; //area number of the reachabilty
int moveflags; //movement flags
int jumpreach; //set when jumped
float grapplevisible_time; //last time the grapple was visible
float lastgrappledist; //last distance to the grapple end
float reachability_time; //time to use current reachability
int avoidreach[MAX_AVOIDREACH]; //reachabilities to avoid
float avoidreachtimes[MAX_AVOIDREACH]; //times to avoid the reachabilities
int avoidreachtries[MAX_AVOIDREACH]; //number of tries before avoiding
} bot_movestate_t;
//used to avoid reachability links for some time after being used
#define AVOIDREACH
#define AVOIDREACH_TIME 4 //avoid links for 6 seconds after use
#define AVOIDREACH_TRIES 4
//prediction times
#define PREDICTIONTIME_JUMP 3 //in seconds
#define PREDICTIONTIME_MOVE 2 //in seconds
//hook commands
#define CMD_HOOKOFF "hookoff"
#define CMD_HOOKON "hookon"
//weapon indexes for weapon jumping
#define WEAPONINDEX_ROCKET_LAUNCHER 5
#define WEAPONINDEX_BFG 9
#define MODELTYPE_FUNC_PLAT 1
#define MODELTYPE_FUNC_BOB 2
float sv_maxstep;
float sv_maxbarrier;
float sv_gravity;
//type of model, func_plat or func_bobbing
int modeltypes[MAX_MODELS];
bot_movestate_t *botmovestates[MAX_CLIENTS + 1];
//========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//========================================================================
int BotAllocMoveState( void ) {
int i;
for ( i = 1; i <= MAX_CLIENTS; i++ )
{
if ( !botmovestates[i] ) {
botmovestates[i] = GetClearedMemory( sizeof( bot_movestate_t ) );
return i;
} //end if
} //end for
return 0;
} //end of the function BotAllocMoveState
//========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//========================================================================
void BotFreeMoveState( int handle ) {
if ( handle <= 0 || handle > MAX_CLIENTS ) {
botimport.Print( PRT_FATAL, "move state handle %d out of range\n", handle );
return;
} //end if
if ( !botmovestates[handle] ) {
botimport.Print( PRT_FATAL, "invalid move state %d\n", handle );
return;
} //end if
FreeMemory( botmovestates[handle] );
botmovestates[handle] = NULL;
} //end of the function BotFreeMoveState
//========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//========================================================================
bot_movestate_t *BotMoveStateFromHandle( int handle ) {
if ( handle <= 0 || handle > MAX_CLIENTS ) {
botimport.Print( PRT_FATAL, "move state handle %d out of range\n", handle );
return NULL;
} //end if
if ( !botmovestates[handle] ) {
botimport.Print( PRT_FATAL, "invalid move state %d\n", handle );
return NULL;
} //end if
return botmovestates[handle];
} //end of the function BotMoveStateFromHandle
// Ridah, provide a means of resetting the avoidreach, so if a bot stops moving, they don't avoid the area they were heading for
//========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//========================================================================
void BotInitAvoidReach( int handle ) {
bot_movestate_t *ms;
ms = BotMoveStateFromHandle( handle );
if ( !ms ) {
return;
}
memset( ms->avoidreach, 0, sizeof( ms->avoidreach ) );
memset( ms->avoidreachtries, 0, sizeof( ms->avoidreachtries ) );
memset( ms->avoidreachtimes, 0, sizeof( ms->avoidreachtimes ) );
}
// done.
//========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//========================================================================
void BotInitMoveState( int handle, bot_initmove_t *initmove ) {
bot_movestate_t *ms;
ms = BotMoveStateFromHandle( handle );
if ( !ms ) {
return;
}
VectorCopy( initmove->origin, ms->origin );
VectorCopy( initmove->velocity, ms->velocity );
VectorCopy( initmove->viewoffset, ms->viewoffset );
ms->entitynum = initmove->entitynum;
ms->client = initmove->client;
ms->thinktime = initmove->thinktime;
ms->presencetype = initmove->presencetype;
ms->areanum = initmove->areanum;
VectorCopy( initmove->viewangles, ms->viewangles );
//
ms->moveflags &= ~MFL_ONGROUND;
if ( initmove->or_moveflags & MFL_ONGROUND ) {
ms->moveflags |= MFL_ONGROUND;
}
ms->moveflags &= ~MFL_TELEPORTED;
if ( initmove->or_moveflags & MFL_TELEPORTED ) {
ms->moveflags |= MFL_TELEPORTED;
}
ms->moveflags &= ~MFL_WATERJUMP;
if ( initmove->or_moveflags & MFL_WATERJUMP ) {
ms->moveflags |= MFL_WATERJUMP;
}
ms->moveflags &= ~MFL_WALK;
if ( initmove->or_moveflags & MFL_WALK ) {
ms->moveflags |= MFL_WALK;
}
} //end of the function BotInitMoveState
//========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//========================================================================
float AngleDiff( float ang1, float ang2 ) {
float diff;
diff = ang1 - ang2;
if ( ang1 > ang2 ) {
if ( diff > 180.0 ) {
diff -= 360.0;
}
} //end if
else
{
if ( diff < -180.0 ) {
diff += 360.0;
}
} //end else
return diff;
} //end of the function AngleDiff
/*
==================
BotFirstReachabilityArea
==================
*/
int BotFirstReachabilityArea( vec3_t origin, int *areas, int numareas, qboolean distCheck ) {
int i, best = 0;
vec3_t center;
float bestDist, dist;
bsp_trace_t tr;
//
bestDist = 999999;
for ( i = 0; i < numareas; i++ ) {
if ( AAS_AreaReachability( areas[i] ) ) {
// make sure this area is visible
if ( !AAS_AreaWaypoint( areas[i], center ) ) {
AAS_AreaCenter( areas[i], center );
}
if ( distCheck ) {
dist = VectorDistance( center, origin );
if ( center[2] > origin[2] ) {
dist += 32 * ( center[2] - origin[2] );
}
if ( dist < bestDist ) {
tr = AAS_Trace( origin, NULL, NULL, center, -1, CONTENTS_SOLID | CONTENTS_PLAYERCLIP );
if ( tr.fraction == 1.0 && !tr.startsolid && !tr.allsolid ) {
best = areas[i];
bestDist = dist;
//if (dist < 128) {
// return best;
//}
}
}
} else {
tr = AAS_Trace( origin, NULL, NULL, center, -1, CONTENTS_SOLID | CONTENTS_PLAYERCLIP );
if ( tr.fraction == 1.0 && !tr.startsolid && !tr.allsolid ) {
best = areas[i];
break;
}
}
}
}
//
return best;
}
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotFuzzyPointReachabilityArea( vec3_t origin ) {
int areanum, numareas, areas[100], bestarea = 0; //, i;
vec3_t end, start /*, ofs*/, mins, maxs;
//float f;
#define BOTAREA_JIGGLE_DIST 256 // 32 // OUCH, hack for MP_BEACH which has lots of voids (mostly in water)
areanum = AAS_PointAreaNum( origin );
if ( !AAS_AreaReachability( areanum ) ) {
areanum = 0;
}
if ( areanum ) {
return areanum;
}
// try a line trace from beneath to above
VectorCopy( origin, start );
VectorCopy( origin, end );
start[2] -= 30;
end[2] += 40;
numareas = AAS_TraceAreas( start, end, areas, NULL, 100 );
if ( numareas > 0 ) {
bestarea = BotFirstReachabilityArea( origin, areas, numareas, qfalse );
}
if ( bestarea ) {
return bestarea;
}
// try a small box around the origin
maxs[0] = 4;
maxs[1] = 4;
maxs[2] = 4;
VectorSubtract( origin, maxs, mins );
VectorAdd( origin, maxs, maxs );
numareas = AAS_BBoxAreas( mins, maxs, areas, 100 );
if ( numareas > 0 ) {
bestarea = BotFirstReachabilityArea( origin, areas, numareas, qtrue );
}
if ( bestarea ) {
return bestarea;
}
AAS_PresenceTypeBoundingBox( PRESENCE_NORMAL, mins, maxs );
VectorAdd( mins, origin, mins );
VectorAdd( maxs, origin, maxs );
numareas = AAS_BBoxAreas( mins, maxs, areas, 100 );
if ( numareas > 0 ) {
bestarea = BotFirstReachabilityArea( origin, areas, numareas, qtrue );
}
if ( bestarea ) {
return bestarea;
}
/*
// try half size first
for (f=0.1; f<=1.0; f+=0.45) {
VectorCopy( origin, end );
end[2]+=80;
VectorCopy( origin, ofs );
ofs[2]-=60;
for (i=0;i<2;i++) end[i]+=BOTAREA_JIGGLE_DIST*f;
for (i=0;i<2;i++) ofs[i]-=BOTAREA_JIGGLE_DIST*f;
numareas = AAS_BBoxAreas(ofs, end, areas, 100);
if (numareas > 0) bestarea = BotFirstReachabilityArea(origin, areas, numareas);
if (bestarea) return bestarea;
}
*/
return 0;
/*
int firstareanum, j, x, y, z;
int areas[10], numareas, areanum, bestareanum;
float dist, bestdist;
vec3_t points[10], v, end;
firstareanum = 0;
areanum = AAS_PointAreaNum(origin);
if (areanum)
{
firstareanum = areanum;
if (AAS_AreaReachability(areanum)) return areanum;
} //end if
VectorCopy(origin, end);
end[2] += 4;
numareas = AAS_TraceAreas(origin, end, areas, points, 10);
for (j = 0; j < numareas; j++)
{
if (AAS_AreaReachability(areas[j])) return areas[j];
} //end for
bestdist = 999999;
bestareanum = 0;
for (z = 1; z >= -1; z -= 1)
{
for (x = 1; x >= -1; x -= 1)
{
for (y = 1; y >= -1; y -= 1)
{
VectorCopy(origin, end);
// Ridah, increased this for Wolf larger bounding boxes
end[0] += x * 16;//8;
end[1] += y * 16;//8;
end[2] += z * 24;//12;
numareas = AAS_TraceAreas(origin, end, areas, points, 10);
for (j = 0; j < numareas; j++)
{
if (AAS_AreaReachability(areas[j]))
{
VectorSubtract(points[j], origin, v);
dist = VectorLength(v);
if (dist < bestdist)
{
bestareanum = areas[j];
bestdist = dist;
} //end if
} //end if
if (!firstareanum) firstareanum = areas[j];
} //end for
} //end for
} //end for
if (bestareanum) return bestareanum;
} //end for
return firstareanum;
*/
} //end of the function BotFuzzyPointReachabilityArea
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotReachabilityArea( vec3_t origin, int client ) {
int modelnum, modeltype, reachnum, areanum;
aas_reachability_t reach;
vec3_t org, end, mins, maxs, up = {0, 0, 1};
bsp_trace_t bsptrace;
aas_trace_t trace;
//check if the bot is standing on something
AAS_PresenceTypeBoundingBox( PRESENCE_CROUCH, mins, maxs );
VectorMA( origin, -3, up, end );
bsptrace = AAS_Trace( origin, mins, maxs, end, client, CONTENTS_SOLID | CONTENTS_PLAYERCLIP );
if ( !bsptrace.startsolid && bsptrace.fraction < 1 && bsptrace.ent != ENTITYNUM_NONE ) {
//if standing on the world the bot should be in a valid area
if ( bsptrace.ent == ENTITYNUM_WORLD ) {
return BotFuzzyPointReachabilityArea( origin );
} //end if
modelnum = AAS_EntityModelindex( bsptrace.ent );
modeltype = modeltypes[modelnum];
//if standing on a func_plat or func_bobbing then the bot is assumed to be
//in the area the reachability points to
if ( modeltype == MODELTYPE_FUNC_PLAT || modeltype == MODELTYPE_FUNC_BOB ) {
reachnum = AAS_NextModelReachability( 0, modelnum );
if ( reachnum ) {
AAS_ReachabilityFromNum( reachnum, &reach );
return reach.areanum;
} //end if
} //end else if
//if the bot is swimming the bot should be in a valid area
if ( AAS_Swimming( origin ) ) {
return BotFuzzyPointReachabilityArea( origin );
} //end if
//
areanum = BotFuzzyPointReachabilityArea( origin );
//if the bot is in an area with reachabilities
if ( areanum && AAS_AreaReachability( areanum ) ) {
return areanum;
}
//trace down till the ground is hit because the bot is standing on some other entity
VectorCopy( origin, org );
VectorCopy( org, end );
end[2] -= 800;
trace = AAS_TraceClientBBox( org, end, PRESENCE_CROUCH, -1 );
if ( !trace.startsolid ) {
VectorCopy( trace.endpos, org );
} //end if
//
return BotFuzzyPointReachabilityArea( org );
} //end if
//
return BotFuzzyPointReachabilityArea( origin );
} //end of the function BotReachabilityArea
//===========================================================================
// returns the reachability area the bot is in
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
/*
int BotReachabilityArea(vec3_t origin, int testground)
{
int firstareanum, i, j, x, y, z;
int areas[10], numareas, areanum, bestareanum;
float dist, bestdist;
vec3_t org, end, points[10], v;
aas_trace_t trace;
firstareanum = 0;
for (i = 0; i < 2; i++)
{
VectorCopy(origin, org);
//if test at the ground (used when bot is standing on an entity)
if (i > 0)
{
VectorCopy(origin, end);
end[2] -= 800;
trace = AAS_TraceClientBBox(origin, end, PRESENCE_CROUCH, -1);
if (!trace.startsolid)
{
VectorCopy(trace.endpos, org);
} //end if
} //end if
firstareanum = 0;
areanum = AAS_PointAreaNum(org);
if (areanum)
{
firstareanum = areanum;
if (AAS_AreaReachability(areanum)) return areanum;
} //end if
bestdist = 999999;
bestareanum = 0;
for (z = 1; z >= -1; z -= 1)
{
for (x = 1; x >= -1; x -= 1)
{
for (y = 1; y >= -1; y -= 1)
{
VectorCopy(org, end);
end[0] += x * 8;
end[1] += y * 8;
end[2] += z * 12;
numareas = AAS_TraceAreas(org, end, areas, points, 10);
for (j = 0; j < numareas; j++)
{
if (AAS_AreaReachability(areas[j]))
{
VectorSubtract(points[j], org, v);
dist = VectorLength(v);
if (dist < bestdist)
{
bestareanum = areas[j];
bestdist = dist;
} //end if
} //end if
} //end for
} //end for
} //end for
if (bestareanum) return bestareanum;
} //end for
if (!testground) break;
} //end for
//#ifdef DEBUG
//botimport.Print(PRT_MESSAGE, "no reachability area\n");
//#endif //DEBUG
return firstareanum;
} //end of the function BotReachabilityArea*/
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotOnMover( vec3_t origin, int entnum, aas_reachability_t *reach ) {
int i, modelnum;
vec3_t mins, maxs, modelorigin, org, end;
vec3_t angles = {0, 0, 0};
vec3_t boxmins = {-16, -16, -8}, boxmaxs = {16, 16, 8};
bsp_trace_t trace;
modelnum = reach->facenum & 0x0000FFFF;
//get some bsp model info
AAS_BSPModelMinsMaxsOrigin( modelnum, angles, mins, maxs, NULL );
//
if ( !AAS_OriginOfEntityWithModelNum( modelnum, modelorigin ) ) {
botimport.Print( PRT_MESSAGE, "no entity with model %d\n", modelnum );
return qfalse;
} //end if
//
for ( i = 0; i < 2; i++ )
{
if ( origin[i] > modelorigin[i] + maxs[i] + 16 ) {
return qfalse;
}
if ( origin[i] < modelorigin[i] + mins[i] - 16 ) {
return qfalse;
}
} //end for
//
VectorCopy( origin, org );
org[2] += 24;
VectorCopy( origin, end );
end[2] -= 48;
//
trace = AAS_Trace( org, boxmins, boxmaxs, end, entnum, CONTENTS_SOLID | CONTENTS_PLAYERCLIP );
if ( !trace.startsolid && !trace.allsolid ) {
//NOTE: the reachability face number is the model number of the elevator
if ( trace.ent != ENTITYNUM_NONE && AAS_EntityModelNum( trace.ent ) == modelnum ) {
return qtrue;
} //end if
} //end if
return qfalse;
} //end of the function BotOnMover
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int MoverDown( aas_reachability_t *reach ) {
int modelnum;
vec3_t mins, maxs, origin;
vec3_t angles = {0, 0, 0};
modelnum = reach->facenum & 0x0000FFFF;
//get some bsp model info
AAS_BSPModelMinsMaxsOrigin( modelnum, angles, mins, maxs, origin );
//
if ( !AAS_OriginOfEntityWithModelNum( modelnum, origin ) ) {
botimport.Print( PRT_MESSAGE, "no entity with model %d\n", modelnum );
return qfalse;
} //end if
//if the top of the plat is below the reachability start point
if ( origin[2] + maxs[2] < reach->start[2] ) {
return qtrue;
}
return qfalse;
} //end of the function MoverDown
//========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//========================================================================
void BotSetBrushModelTypes( void ) {
int ent, modelnum;
char classname[MAX_EPAIRKEY], model[MAX_EPAIRKEY];
memset( modeltypes, 0, MAX_MODELS * sizeof( int ) );
//
for ( ent = AAS_NextBSPEntity( 0 ); ent; ent = AAS_NextBSPEntity( ent ) )
{
if ( !AAS_ValueForBSPEpairKey( ent, "classname", classname, MAX_EPAIRKEY ) ) {
continue;
}
if ( !AAS_ValueForBSPEpairKey( ent, "model", model, MAX_EPAIRKEY ) ) {
continue;
}
if ( model[0] ) {
modelnum = atoi( model + 1 );
} else { modelnum = 0;}
if ( modelnum < 0 || modelnum > MAX_MODELS ) {
botimport.Print( PRT_MESSAGE, "entity %s model number out of range\n", classname );
continue;
} //end if
if ( !strcmp( classname, "func_bobbing" ) ) {
modeltypes[modelnum] = MODELTYPE_FUNC_BOB;
} else if ( !strcmp( classname, "func_plat" ) ) {
modeltypes[modelnum] = MODELTYPE_FUNC_PLAT;
}
} //end for
} //end of the function BotSetBrushModelTypes
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotOnTopOfEntity( bot_movestate_t *ms ) {
vec3_t mins, maxs, end, up = {0, 0, 1};
bsp_trace_t trace;
AAS_PresenceTypeBoundingBox( ms->presencetype, mins, maxs );
VectorMA( ms->origin, -3, up, end );
trace = AAS_Trace( ms->origin, mins, maxs, end, ms->entitynum, CONTENTS_SOLID | CONTENTS_PLAYERCLIP );
if ( !trace.startsolid && ( trace.ent != ENTITYNUM_WORLD && trace.ent != ENTITYNUM_NONE ) ) {
return trace.ent;
} //end if
return -1;
} //end of the function BotOnTopOfEntity
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotValidTravel( vec3_t origin, aas_reachability_t *reach, int travelflags ) {
//if the reachability uses an unwanted travel type
if ( AAS_TravelFlagForType( reach->traveltype ) & ~travelflags ) {
return qfalse;
}
//don't go into areas with bad travel types
if ( AAS_AreaContentsTravelFlag( reach->areanum ) & ~travelflags ) {
return qfalse;
}
return qtrue;
} //end of the function BotValidTravel
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void BotAddToAvoidReach( bot_movestate_t *ms, int number, float avoidtime ) {
int i;
for ( i = 0; i < MAX_AVOIDREACH; i++ )
{
if ( ms->avoidreach[i] == number ) {
if ( ms->avoidreachtimes[i] > AAS_Time() ) {
ms->avoidreachtries[i]++;
} else { ms->avoidreachtries[i] = 1;}
ms->avoidreachtimes[i] = AAS_Time() + avoidtime;
return;
} //end if
} //end for
//add the reachability to the reachabilities to avoid for a while
for ( i = 0; i < MAX_AVOIDREACH; i++ )
{
if ( ms->avoidreachtimes[i] < AAS_Time() ) {
ms->avoidreach[i] = number;
ms->avoidreachtimes[i] = AAS_Time() + avoidtime;
ms->avoidreachtries[i] = 1;
return;
} //end if
} //end for
} //end of the function BotAddToAvoidReach
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
//__inline int AAS_AreaContentsTravelFlag(int areanum);
int BotGetReachabilityToGoal( vec3_t origin, int areanum, int entnum,
int lastgoalareanum, int lastareanum,
int *avoidreach, float *avoidreachtimes, int *avoidreachtries,
bot_goal_t *goal, int travelflags, int movetravelflags ) {
int t, besttime, bestreachnum, reachnum;
aas_reachability_t reach;
qboolean useAvoidPass = qfalse;
again:
//if not in a valid area
if ( !areanum ) {
return 0;
}
//
if ( AAS_AreaDoNotEnter( areanum ) || AAS_AreaDoNotEnter( goal->areanum ) ) {
travelflags |= TFL_DONOTENTER;
movetravelflags |= TFL_DONOTENTER;
} //end if
if ( AAS_AreaDoNotEnterLarge( areanum ) || AAS_AreaDoNotEnterLarge( goal->areanum ) ) {
travelflags |= TFL_DONOTENTER_LARGE;
movetravelflags |= TFL_DONOTENTER_LARGE;
} //end if
//use the routing to find the next area to go to
besttime = 0;
bestreachnum = 0;
//
for ( reachnum = AAS_NextAreaReachability( areanum, 0 ); reachnum;
reachnum = AAS_NextAreaReachability( areanum, reachnum ) )
{
#ifdef AVOIDREACH
int i;
//check if it isn't an reachability to avoid
for ( i = 0; i < MAX_AVOIDREACH; i++ )
{
if ( avoidreach[i] == reachnum && avoidreachtimes[i] >= AAS_Time() ) {
break;
}
} //end for
// RF, if this is a "useAvoidPass" then we should only accept avoidreach reachabilities
if ( ( !useAvoidPass && i != MAX_AVOIDREACH && avoidreachtries[i] > AVOIDREACH_TRIES )
|| ( useAvoidPass && !( i != MAX_AVOIDREACH && avoidreachtries[i] > AVOIDREACH_TRIES ) ) ) {
#ifdef DEBUG
if ( bot_developer ) {
botimport.Print( PRT_MESSAGE, "avoiding reachability %d\n", avoidreach[i] );
} //end if
#endif //DEBUG
continue;
} //end if
#endif //AVOIDREACH
//get the reachability from the number
AAS_ReachabilityFromNum( reachnum, &reach );
//NOTE: do not go back to the previous area if the goal didn't change
//NOTE: is this actually avoidance of local routing minima between two areas???
if ( lastgoalareanum == goal->areanum && reach.areanum == lastareanum ) {
continue;
}
//if (AAS_AreaContentsTravelFlag(reach.areanum) & ~travelflags) continue;
//if the travel isn't valid
if ( !BotValidTravel( origin, &reach, movetravelflags ) ) {
continue;
}
// if the area is disabled
if ( !AAS_AreaReachability( reach.areanum ) ) {
continue;
}
//get the travel time
t = AAS_AreaTravelTimeToGoalArea( reach.areanum, reach.end, goal->areanum, travelflags );
//if the goal area isn't reachable from the reachable area
if ( !t ) {
continue;
}
// Ridah, if this sends us to a looped route, ignore it
// if (AAS_AreaTravelTimeToGoalArea(areanum, reach.start, goal->areanum, travelflags) + reach.traveltime == t)
// continue;
//add the travel time towards the area
// Ridah, not sure why this was disabled, but it causes looped links in the route-cache
//t += reach.traveltime;// + AAS_AreaTravelTime(areanum, origin, reach.start);
t += reach.traveltime + AAS_AreaTravelTime( areanum, origin, reach.start );
// Ridah, if there exists other entities in this area, avoid it
// if (reach.areanum != goal->areanum && AAS_IsEntityInArea( entnum, goal->entitynum, reach.areanum )) {
// t += 50;
// }
//if the travel time is better than the ones already found
if ( !besttime || t < besttime ) {
besttime = t;
bestreachnum = reachnum;
} //end if
} //end for
//
// RF, if we didnt find a route, then try again only looking through avoidreach reachabilities
if ( !bestreachnum && !useAvoidPass ) {
useAvoidPass = qtrue;
goto again;
}
//
return bestreachnum;
} //end of the function BotGetReachabilityToGoal
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotAddToTarget( vec3_t start, vec3_t end, float maxdist, float *dist, vec3_t target ) {
vec3_t dir;
float curdist;
VectorSubtract( end, start, dir );
curdist = VectorNormalize( dir );
if ( *dist + curdist < maxdist ) {
VectorCopy( end, target );
*dist += curdist;
return qfalse;
} //end if
else
{
VectorMA( start, maxdist - *dist, dir, target );
*dist = maxdist;
return qtrue;
} //end else
} //end of the function BotAddToTarget
int BotMovementViewTarget( int movestate, bot_goal_t *goal, int travelflags, float lookahead, vec3_t target ) {
aas_reachability_t reach;
int reachnum, lastareanum;
bot_movestate_t *ms;
vec3_t end;
float dist;
ms = BotMoveStateFromHandle( movestate );
if ( !ms ) {
return qfalse;
}
reachnum = 0;
//if the bot has no goal or no last reachability
if ( !ms->lastreachnum || !goal ) {
return qfalse;
}
reachnum = ms->lastreachnum;
VectorCopy( ms->origin, end );
lastareanum = ms->lastareanum;
dist = 0;
while ( reachnum && dist < lookahead )
{
AAS_ReachabilityFromNum( reachnum, &reach );
if ( BotAddToTarget( end, reach.start, lookahead, &dist, target ) ) {
return qtrue;
}
//never look beyond teleporters
if ( reach.traveltype == TRAVEL_TELEPORT ) {
return qtrue;
}
//don't add jump pad distances
if ( reach.traveltype != TRAVEL_JUMPPAD &&
reach.traveltype != TRAVEL_ELEVATOR &&
reach.traveltype != TRAVEL_FUNCBOB ) {
if ( BotAddToTarget( reach.start, reach.end, lookahead, &dist, target ) ) {
return qtrue;
}
} //end if
reachnum = BotGetReachabilityToGoal( reach.end, reach.areanum, -1,
ms->lastgoalareanum, lastareanum,
ms->avoidreach, ms->avoidreachtimes, ms->avoidreachtries,
goal, travelflags, travelflags );
VectorCopy( reach.end, end );
lastareanum = reach.areanum;
if ( lastareanum == goal->areanum ) {
BotAddToTarget( reach.end, goal->origin, lookahead, &dist, target );
return qtrue;
} //end if
} //end while
//
return qfalse;
} //end of the function BotMovementViewTarget
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotVisible( int ent, vec3_t eye, vec3_t target ) {
bsp_trace_t trace;
trace = AAS_Trace( eye, NULL, NULL, target, ent, CONTENTS_SOLID | CONTENTS_PLAYERCLIP );
if ( trace.fraction >= 1 ) {
return qtrue;
}
return qfalse;
} //end of the function BotVisible
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotPredictVisiblePosition( vec3_t origin, int areanum, bot_goal_t *goal, int travelflags, vec3_t target ) {
aas_reachability_t reach;
int reachnum, lastgoalareanum, lastareanum, i;
int avoidreach[MAX_AVOIDREACH];
float avoidreachtimes[MAX_AVOIDREACH];
int avoidreachtries[MAX_AVOIDREACH];
vec3_t end;
//if the bot has no goal or no last reachability
if ( !goal ) {
return qfalse;
}
//if the areanum is not valid
if ( !areanum ) {
return qfalse;
}
//if the goal areanum is not valid
if ( !goal->areanum ) {
return qfalse;
}
memset( avoidreach, 0, MAX_AVOIDREACH * sizeof( int ) );
lastgoalareanum = goal->areanum;
lastareanum = areanum;
VectorCopy( origin, end );
//only do 20 hops
for ( i = 0; i < 20 && ( areanum != goal->areanum ); i++ )
{
//
reachnum = BotGetReachabilityToGoal( end, areanum, -1,
lastgoalareanum, lastareanum,
avoidreach, avoidreachtimes, avoidreachtries,
goal, travelflags, travelflags );
if ( !reachnum ) {
return qfalse;
}
AAS_ReachabilityFromNum( reachnum, &reach );
//
if ( BotVisible( goal->entitynum, goal->origin, reach.start ) ) {
VectorCopy( reach.start, target );
return qtrue;
} //end if
//
if ( BotVisible( goal->entitynum, goal->origin, reach.end ) ) {
VectorCopy( reach.end, target );
return qtrue;
} //end if
//
if ( reach.areanum == goal->areanum ) {
VectorCopy( reach.end, target );
return qtrue;
} //end if
//
lastareanum = areanum;
areanum = reach.areanum;
VectorCopy( reach.end, end );
//
} //end while
//
return qfalse;
} //end of the function BotPredictVisiblePosition
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void MoverBottomCenter( aas_reachability_t *reach, vec3_t bottomcenter ) {
int modelnum;
vec3_t mins, maxs, origin, mids;
vec3_t angles = {0, 0, 0};
modelnum = reach->facenum & 0x0000FFFF;
//get some bsp model info
AAS_BSPModelMinsMaxsOrigin( modelnum, angles, mins, maxs, origin );
//
if ( !AAS_OriginOfEntityWithModelNum( modelnum, origin ) ) {
botimport.Print( PRT_MESSAGE, "no entity with model %d\n", modelnum );
} //end if
//get a point just above the plat in the bottom position
VectorAdd( mins, maxs, mids );
VectorMA( origin, 0.5, mids, bottomcenter );
bottomcenter[2] = reach->start[2];
} //end of the function MoverBottomCenter
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
float BotGapDistance( vec3_t origin, vec3_t hordir, int entnum ) {
float dist, startz;
vec3_t start, end;
aas_trace_t trace;
//do gap checking
startz = origin[2];
//this enables walking down stairs more fluidly
{
VectorCopy( origin, start );
VectorCopy( origin, end );
end[2] -= 60;
trace = AAS_TraceClientBBox( start, end, PRESENCE_CROUCH, entnum );
if ( trace.fraction >= 1 ) {
return 1;
}
startz = trace.endpos[2] + 1;
}
//
for ( dist = 8; dist <= 100; dist += 8 )
{
VectorMA( origin, dist, hordir, start );
start[2] = startz + 24;
VectorCopy( start, end );
end[2] -= 48 + sv_maxbarrier;
trace = AAS_TraceClientBBox( start, end, PRESENCE_CROUCH, entnum );
//if solid is found the bot can't walk any further and fall into a gap
if ( !trace.startsolid ) {
//if it is a gap
if ( trace.endpos[2] < startz - sv_maxstep - 8 ) {
VectorCopy( trace.endpos, end );
end[2] -= 20;
if ( AAS_PointContents( end ) & ( CONTENTS_WATER | CONTENTS_SLIME ) ) {
break; //----(SA) modified since slime is no longer deadly
}
// if (AAS_PointContents(end) & CONTENTS_WATER) break;
//if a gap is found slow down
//botimport.Print(PRT_MESSAGE, "gap at %f\n", dist);
return dist;
} //end if
startz = trace.endpos[2];
} //end if
} //end for
return 0;
} //end of the function BotGapDistance
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotCheckBarrierJump( bot_movestate_t *ms, vec3_t dir, float speed ) {
vec3_t start, hordir, end;
aas_trace_t trace;
VectorCopy( ms->origin, end );
end[2] += sv_maxbarrier;
//trace right up
trace = AAS_TraceClientBBox( ms->origin, end, PRESENCE_NORMAL, ms->entitynum );
//this shouldn't happen... but we check anyway
if ( trace.startsolid ) {
return qfalse;
}
//if very low ceiling it isn't possible to jump up to a barrier
if ( trace.endpos[2] - ms->origin[2] < sv_maxstep ) {
return qfalse;
}
//
hordir[0] = dir[0];
hordir[1] = dir[1];
hordir[2] = 0;
VectorNormalize( hordir );
VectorMA( ms->origin, ms->thinktime * speed * 0.5, hordir, end );
VectorCopy( trace.endpos, start );
end[2] = trace.endpos[2];
//trace from previous trace end pos horizontally in the move direction
trace = AAS_TraceClientBBox( start, end, PRESENCE_NORMAL, ms->entitynum );
//again this shouldn't happen
if ( trace.startsolid ) {
return qfalse;
}
//
VectorCopy( trace.endpos, start );
VectorCopy( trace.endpos, end );
end[2] = ms->origin[2];
//trace down from the previous trace end pos
trace = AAS_TraceClientBBox( start, end, PRESENCE_NORMAL, ms->entitynum );
//if solid
if ( trace.startsolid ) {
return qfalse;
}
//if no obstacle at all
if ( trace.fraction >= 1.0 ) {
return qfalse;
}
//if less than the maximum step height
if ( trace.endpos[2] - ms->origin[2] < sv_maxstep ) {
return qfalse;
}
//
EA_Jump( ms->client );
EA_Move( ms->client, hordir, speed );
ms->moveflags |= MFL_BARRIERJUMP;
//there is a barrier
return qtrue;
} //end of the function BotCheckBarrierJump
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotSwimInDirection( bot_movestate_t *ms, vec3_t dir, float speed, int type ) {
vec3_t normdir;
VectorCopy( dir, normdir );
VectorNormalize( normdir );
EA_Move( ms->client, normdir, speed );
return qtrue;
} //end of the function BotSwimInDirection
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotWalkInDirection( bot_movestate_t *ms, vec3_t dir, float speed, int type ) {
vec3_t hordir, cmdmove, velocity, tmpdir, origin;
int presencetype, maxframes, cmdframes, stopevent;
aas_clientmove_t move;
float dist;
//if the bot is on the ground
if ( ms->moveflags & MFL_ONGROUND ) {
//if there is a barrier the bot can jump on
if ( BotCheckBarrierJump( ms, dir, speed ) ) {
return qtrue;
}
//remove barrier jump flag
ms->moveflags &= ~MFL_BARRIERJUMP;
//get the presence type for the movement
if ( ( type & MOVE_CROUCH ) && !( type & MOVE_JUMP ) ) {
presencetype = PRESENCE_CROUCH;
} else { presencetype = PRESENCE_NORMAL;}
//horizontal direction
hordir[0] = dir[0];
hordir[1] = dir[1];
hordir[2] = 0;
VectorNormalize( hordir );
//if the bot is not supposed to jump
if ( !( type & MOVE_JUMP ) ) {
//if there is a gap, try to jump over it
if ( BotGapDistance( ms->origin, hordir, ms->entitynum ) > 0 ) {
type |= MOVE_JUMP;
}
} //end if
//get command movement
VectorScale( hordir, speed, cmdmove );
VectorCopy( ms->velocity, velocity );
//
if ( type & MOVE_JUMP ) {
//botimport.Print(PRT_MESSAGE, "trying jump\n");
cmdmove[2] = 400;
maxframes = PREDICTIONTIME_JUMP / 0.1;
cmdframes = 1;
stopevent = SE_HITGROUND | SE_HITGROUNDDAMAGE |
SE_ENTERWATER | SE_ENTERSLIME | SE_ENTERLAVA;
} //end if
else
{
maxframes = 2;
cmdframes = 2;
stopevent = SE_HITGROUNDDAMAGE |
SE_ENTERWATER | SE_ENTERSLIME | SE_ENTERLAVA;
} //end else
//AAS_ClearShownDebugLines();
//
VectorCopy( ms->origin, origin );
origin[2] += 0.5;
AAS_PredictClientMovement( &move, ms->entitynum, origin, presencetype, qtrue,
velocity, cmdmove, cmdframes, maxframes, 0.1,
stopevent, 0, qfalse ); //qtrue);
//if prediction time wasn't enough to fully predict the movement
if ( move.frames >= maxframes && ( type & MOVE_JUMP ) ) {
//botimport.Print(PRT_MESSAGE, "client %d: max prediction frames\n", ms->client);
return qfalse;
} //end if
//don't enter slime or lava and don't fall from too high
if ( move.stopevent & ( SE_ENTERLAVA | SE_HITGROUNDDAMAGE ) ) { //----(SA) modified since slime is no longer deadly
// if (move.stopevent & (SE_ENTERSLIME|SE_ENTERLAVA|SE_HITGROUNDDAMAGE))
//botimport.Print(PRT_MESSAGE, "client %d: would be hurt ", ms->client);
//if (move.stopevent & SE_ENTERSLIME) botimport.Print(PRT_MESSAGE, "slime\n");
//if (move.stopevent & SE_ENTERLAVA) botimport.Print(PRT_MESSAGE, "lava\n");
//if (move.stopevent & SE_HITGROUNDDAMAGE) botimport.Print(PRT_MESSAGE, "hitground\n");
return qfalse;
} //end if
//if ground was hit
if ( move.stopevent & SE_HITGROUND ) {
//check for nearby gap
VectorNormalize2( move.velocity, tmpdir );
dist = BotGapDistance( move.endpos, tmpdir, ms->entitynum );
if ( dist > 0 ) {
return qfalse;
}
//
dist = BotGapDistance( move.endpos, hordir, ms->entitynum );
if ( dist > 0 ) {
return qfalse;
}
} //end if
//get horizontal movement
tmpdir[0] = move.endpos[0] - ms->origin[0];
tmpdir[1] = move.endpos[1] - ms->origin[1];
tmpdir[2] = 0;
//
//AAS_DrawCross(move.endpos, 4, LINECOLOR_BLUE);
//the bot is blocked by something
if ( VectorLength( tmpdir ) < speed * ms->thinktime * 0.5 ) {
return qfalse;
}
//perform the movement
if ( type & MOVE_JUMP ) {
EA_Jump( ms->client );
}
if ( type & MOVE_CROUCH ) {
EA_Crouch( ms->client );
}
EA_Move( ms->client, hordir, speed );
//movement was succesfull
return qtrue;
} //end if
else
{
if ( ms->moveflags & MFL_BARRIERJUMP ) {
//if near the top or going down
if ( ms->velocity[2] < 50 ) {
EA_Move( ms->client, dir, speed );
} //end if
} //end if
//FIXME: do air control to avoid hazards
return qtrue;
} //end else
} //end of the function BotWalkInDirection
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotMoveInDirection( int movestate, vec3_t dir, float speed, int type ) {
bot_movestate_t *ms;
ms = BotMoveStateFromHandle( movestate );
if ( !ms ) {
return qfalse;
}
//if swimming
if ( AAS_Swimming( ms->origin ) ) {
return BotSwimInDirection( ms, dir, speed, type );
} //end if
else
{
return BotWalkInDirection( ms, dir, speed, type );
} //end else
} //end of the function BotMoveInDirection
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int Intersection( vec2_t p1, vec2_t p2, vec2_t p3, vec2_t p4, vec2_t out ) {
float x1, dx1, dy1, x2, dx2, dy2, d;
dx1 = p2[0] - p1[0];
dy1 = p2[1] - p1[1];
dx2 = p4[0] - p3[0];
dy2 = p4[1] - p3[1];
d = dy1 * dx2 - dx1 * dy2;
if ( d != 0 ) {
x1 = p1[1] * dx1 - p1[0] * dy1;
x2 = p3[1] * dx2 - p3[0] * dy2;
out[0] = (int) ( ( dx1 * x2 - dx2 * x1 ) / d );
out[1] = (int) ( ( dy1 * x2 - dy2 * x1 ) / d );
return qtrue;
} //end if
else
{
return qfalse;
} //end else
} //end of the function Intersection
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void BotCheckBlocked( bot_movestate_t *ms, vec3_t dir, int checkbottom, bot_moveresult_t *result ) {
vec3_t mins, maxs, end, up = {0, 0, 1};
bsp_trace_t trace;
//test for entities obstructing the bot's path
AAS_PresenceTypeBoundingBox( ms->presencetype, mins, maxs );
//
if ( Q_fabs( DotProduct( dir, up ) ) < 0.7 ) {
mins[2] += sv_maxstep; //if the bot can step on
maxs[2] -= 10; //a little lower to avoid low ceiling
} //end if
VectorMA( ms->origin, 16, dir, end );
trace = AAS_Trace( ms->origin, mins, maxs, end, ms->entitynum, CONTENTS_SOLID | CONTENTS_PLAYERCLIP | CONTENTS_BODY );
//if not started in solid and not hitting the world entity
if ( !trace.startsolid && ( trace.ent != ENTITYNUM_WORLD && trace.ent != ENTITYNUM_NONE ) ) {
result->blocked = qtrue;
result->blockentity = trace.ent;
#ifdef DEBUG
//botimport.Print(PRT_MESSAGE, "%d: BotCheckBlocked: I'm blocked\n", ms->client);
#endif //DEBUG
} //end if
//if not in an area with reachability
else if ( checkbottom && !AAS_AreaReachability( ms->areanum ) ) {
//check if the bot is standing on something
AAS_PresenceTypeBoundingBox( ms->presencetype, mins, maxs );
VectorMA( ms->origin, -3, up, end );
trace = AAS_Trace( ms->origin, mins, maxs, end, ms->entitynum, CONTENTS_SOLID | CONTENTS_PLAYERCLIP );
if ( !trace.startsolid && ( trace.ent != ENTITYNUM_WORLD && trace.ent != ENTITYNUM_NONE ) ) {
result->blocked = qtrue;
result->blockentity = trace.ent;
result->flags |= MOVERESULT_ONTOPOFOBSTACLE;
#ifdef DEBUG
//botimport.Print(PRT_MESSAGE, "%d: BotCheckBlocked: I'm blocked\n", ms->client);
#endif //DEBUG
} //end if
} //end else
} //end of the function BotCheckBlocked
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void BotClearMoveResult( bot_moveresult_t *moveresult ) {
moveresult->failure = qfalse;
moveresult->type = 0;
moveresult->blocked = qfalse;
moveresult->blockentity = -1;
moveresult->traveltype = 0;
moveresult->flags = 0;
} //end of the function BotClearMoveResult
char *vtosf( const vec3_t v ) {
static int index;
static char str[8][64];
char *s;
// use an array so that multiple vtos won't collide
s = str[index];
index = ( index + 1 ) & 7;
Com_sprintf( s, 64, "(%f %f %f)", v[0], v[1], v[2] );
return s;
}
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotTravel_Walk( bot_movestate_t *ms, aas_reachability_t *reach ) {
float dist, speed;
vec3_t hordir; //, v1, v2, p;
bot_moveresult_t result;
BotClearMoveResult( &result );
//first walk straight to the reachability start
hordir[0] = reach->start[0] - ms->origin[0];
hordir[1] = reach->start[1] - ms->origin[1];
hordir[2] = 0;
dist = VectorNormalize( hordir );
//
BotCheckBlocked( ms, hordir, qtrue, &result );
//
// Ridah, tweaked this
// if (dist < 10)
if ( dist < 32 ) {
//walk straight to the reachability end
hordir[0] = reach->end[0] - ms->origin[0];
hordir[1] = reach->end[1] - ms->origin[1];
hordir[2] = 0;
dist = VectorNormalize( hordir );
/*
// if we are really close to the line, then move towards the center of the reach area
VectorCopy( reach->start, v1 );
VectorCopy( reach->end, v2 );
VectorCopy( ms->origin, p );
v1[2] = 0;
v2[2] = 0;
p[2] = 0;
if (DistanceFromVectorSquared( p, v1, v2 ) < 4) {
if (!AAS_AreaWaypoint( reach->areanum, p ))
AAS_AreaCenter( reach->areanum, p );
if (VectorDistance( ms->origin, p ) > 32) {
VectorSubtract( p, ms->origin, hordir );
hordir[2] = 0;
dist = VectorNormalize(hordir);
}
}
*/
} else {
//botimport.Print(PRT_MESSAGE, "BotTravel_Walk: NOT in range of reach (%i)\n", reach->areanum);
} //end if
//if going towards a crouch area
// Ridah, some areas have a 0 presence (!?!)
// if (!(AAS_AreaPresenceType(reach->areanum) & PRESENCE_NORMAL))
if ( ( AAS_AreaPresenceType( reach->areanum ) & PRESENCE_CROUCH ) &&
!( AAS_AreaPresenceType( reach->areanum ) & PRESENCE_NORMAL ) ) {
//if pretty close to the reachable area
if ( dist < 20 ) {
EA_Crouch( ms->client );
}
} //end if
//
dist = BotGapDistance( ms->origin, hordir, ms->entitynum );
//
if ( ms->moveflags & MFL_WALK ) {
if ( dist > 0 ) {
speed = 200 - ( 180 - 1 * dist );
} else { speed = 200;}
EA_Walk( ms->client );
} //end if
else
{
if ( dist > 0 ) {
speed = 400 - ( 360 - 2 * dist );
} else { speed = 400;}
} //end else
//elemantary action move in direction
EA_Move( ms->client, hordir, speed );
VectorCopy( hordir, result.movedir );
//
//botimport.Print(PRT_MESSAGE, "\nBotTravel_Walk: srcarea %i, rcharea %i, org %s, reachorg %s\n", ms->areanum, reach->areanum, vtosf(ms->origin), vtosf(reach->start) );
//
return result;
} //end of the function BotTravel_Walk
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotFinishTravel_Walk( bot_movestate_t *ms, aas_reachability_t *reach ) {
vec3_t hordir;
float dist, speed;
bot_moveresult_t result;
BotClearMoveResult( &result );
//if not on the ground and changed areas... don't walk back!!
//(doesn't seem to help)
/*
ms->areanum = BotFuzzyPointReachabilityArea(ms->origin);
if (ms->areanum == reach->areanum)
{
#ifdef DEBUG
botimport.Print(PRT_MESSAGE, "BotFinishTravel_Walk: already in reach area\n");
#endif //DEBUG
return result;
} //end if*/
//go straight to the reachability end
hordir[0] = reach->end[0] - ms->origin[0];
hordir[1] = reach->end[1] - ms->origin[1];
hordir[2] = 0;
dist = VectorNormalize( hordir );
//
if ( dist > 100 ) {
dist = 100;
}
speed = 400 - ( 400 - 3 * dist );
//
EA_Move( ms->client, hordir, speed );
VectorCopy( hordir, result.movedir );
//
return result;
} //end of the function BotFinishTravel_Walk
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotTravel_Crouch( bot_movestate_t *ms, aas_reachability_t *reach ) {
float speed;
vec3_t hordir;
bot_moveresult_t result;
BotClearMoveResult( &result );
//
speed = 400;
//walk straight to reachability end
hordir[0] = reach->end[0] - ms->origin[0];
hordir[1] = reach->end[1] - ms->origin[1];
hordir[2] = 0;
VectorNormalize( hordir );
//
BotCheckBlocked( ms, hordir, qtrue, &result );
//elemantary actions
EA_Crouch( ms->client );
EA_Move( ms->client, hordir, speed );
//
VectorCopy( hordir, result.movedir );
//
return result;
} //end of the function BotTravel_Crouch
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotTravel_BarrierJump( bot_movestate_t *ms, aas_reachability_t *reach ) {
float dist, speed;
vec3_t hordir;
bot_moveresult_t result;
BotClearMoveResult( &result );
//walk straight to reachability start
hordir[0] = reach->start[0] - ms->origin[0];
hordir[1] = reach->start[1] - ms->origin[1];
hordir[2] = 0;
dist = VectorNormalize( hordir );
//
BotCheckBlocked( ms, hordir, qtrue, &result );
//if pretty close to the barrier
if ( dist < 12 ) {
EA_Jump( ms->client );
// Ridah, do the movement also, so we have momentum to get onto the barrier
hordir[0] = reach->end[0] - reach->start[0];
hordir[1] = reach->end[1] - reach->start[1];
hordir[2] = 0;
VectorNormalize( hordir );
dist = 90;
speed = 400 - ( 360 - 4 * dist );
EA_Move( ms->client, hordir, speed );
// done.
} //end if
else
{
if ( dist > 90 ) {
dist = 90;
}
speed = 400 - ( 360 - 4 * dist );
EA_Move( ms->client, hordir, speed );
} //end else
VectorCopy( hordir, result.movedir );
//
return result;
} //end of the function BotTravel_BarrierJump
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotFinishTravel_BarrierJump( bot_movestate_t *ms, aas_reachability_t *reach ) {
float dist, speed;
vec3_t hordir;
bot_moveresult_t result;
BotClearMoveResult( &result );
//if near the top or going down
if ( ms->velocity[2] < 250 ) {
// Ridah, extend the end point a bit, so we strive to get over the ledge more
vec3_t end;
VectorSubtract( reach->end, reach->start, end );
end[2] = 0;
VectorNormalize( end );
VectorMA( reach->end, 32, end, end );
hordir[0] = end[0] - ms->origin[0];
hordir[1] = end[1] - ms->origin[1];
// hordir[0] = reach->end[0] - ms->origin[0];
// hordir[1] = reach->end[1] - ms->origin[1];
// done.
hordir[2] = 0;
dist = VectorNormalize( hordir );
//
BotCheckBlocked( ms, hordir, qtrue, &result );
//
if ( dist > 60 ) {
dist = 60;
}
speed = 400 - ( 400 - 6 * dist );
EA_Move( ms->client, hordir, speed );
VectorCopy( hordir, result.movedir );
} else {
// hold crouch in case we are going for a crouch area
if ( AAS_AreaPresenceType( reach->areanum ) & PRESENCE_CROUCH ) {
EA_Crouch( ms->client );
}
}
//
return result;
} //end of the function BotFinishTravel_BarrierJump
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotTravel_Swim( bot_movestate_t *ms, aas_reachability_t *reach ) {
vec3_t dir;
bot_moveresult_t result;
BotClearMoveResult( &result );
//swim straight to reachability end
VectorSubtract( reach->start, ms->origin, dir );
VectorNormalize( dir );
//
BotCheckBlocked( ms, dir, qtrue, &result );
//elemantary actions
EA_Move( ms->client, dir, 400 );
//
VectorCopy( dir, result.movedir );
Vector2Angles( dir, result.ideal_viewangles );
result.flags |= MOVERESULT_SWIMVIEW;
//
return result;
} //end of the function BotTravel_Swim
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotTravel_WaterJump( bot_movestate_t *ms, aas_reachability_t *reach ) {
vec3_t dir, hordir;
float dist;
bot_moveresult_t result;
BotClearMoveResult( &result );
//swim straight to reachability end
VectorSubtract( reach->end, ms->origin, dir );
VectorCopy( dir, hordir );
hordir[2] = 0;
dir[2] += 15 + crandom() * 40;
//botimport.Print(PRT_MESSAGE, "BotTravel_WaterJump: dir[2] = %f\n", dir[2]);
VectorNormalize( dir );
dist = VectorNormalize( hordir );
//elemantary actions
//EA_Move(ms->client, dir, 400);
EA_MoveForward( ms->client );
//move up if close to the actual out of water jump spot
if ( dist < 40 ) {
EA_MoveUp( ms->client );
}
//set the ideal view angles
Vector2Angles( dir, result.ideal_viewangles );
result.flags |= MOVERESULT_MOVEMENTVIEW;
//
VectorCopy( dir, result.movedir );
//
return result;
} //end of the function BotTravel_WaterJump
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotFinishTravel_WaterJump( bot_movestate_t *ms, aas_reachability_t *reach ) {
vec3_t dir, pnt;
float dist;
bot_moveresult_t result;
//botimport.Print(PRT_MESSAGE, "BotFinishTravel_WaterJump\n");
BotClearMoveResult( &result );
//if waterjumping there's nothing to do
if ( ms->moveflags & MFL_WATERJUMP ) {
return result;
}
//if not touching any water anymore don't do anything
//otherwise the bot sometimes keeps jumping?
VectorCopy( ms->origin, pnt );
pnt[2] -= 32; //extra for q2dm4 near red armor/mega health
if ( !( AAS_PointContents( pnt ) & ( CONTENTS_LAVA | CONTENTS_SLIME | CONTENTS_WATER ) ) ) {
return result;
}
//swim straight to reachability end
VectorSubtract( reach->end, ms->origin, dir );
dir[0] += crandom() * 10;
dir[1] += crandom() * 10;
dir[2] += 70 + crandom() * 10;
dist = VectorNormalize( dir );
//elemantary actions
EA_Move( ms->client, dir, 400 );
//set the ideal view angles
Vector2Angles( dir, result.ideal_viewangles );
result.flags |= MOVERESULT_MOVEMENTVIEW;
//
VectorCopy( dir, result.movedir );
//
return result;
} //end of the function BotFinishTravel_WaterJump
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotTravel_WalkOffLedge( bot_movestate_t *ms, aas_reachability_t *reach ) {
vec3_t hordir, dir;
float dist, speed, reachhordist;
bot_moveresult_t result;
BotClearMoveResult( &result );
//check if the bot is blocked by anything
VectorSubtract( reach->start, ms->origin, dir );
VectorNormalize( dir );
BotCheckBlocked( ms, dir, qtrue, &result );
//if the reachability start and end are practially above each other
VectorSubtract( reach->end, reach->start, dir );
dir[2] = 0;
reachhordist = VectorLength( dir );
//walk straight to the reachability start
hordir[0] = reach->start[0] - ms->origin[0];
hordir[1] = reach->start[1] - ms->origin[1];
hordir[2] = 0;
dist = VectorNormalize( hordir );
//if pretty close to the start focus on the reachability end
// Ridah, tweaked this
#if 0
if ( dist < 48 ) {
hordir[0] = reach->end[0] - ms->origin[0];
hordir[1] = reach->end[1] - ms->origin[1];
hordir[2] = 0;
#else
if ( ( dist < 72 ) && ( DotProduct( dir, hordir ) < 0 ) ) { // walk in the direction of start -> end
//hordir[0] = reach->end[0] - ms->origin[0];
//hordir[1] = reach->end[1] - ms->origin[1];
//VectorNormalize( dir );
//VectorMA( hordir, 48, dir, hordir );
//hordir[2] = 0;
VectorCopy( dir, hordir );
#endif
VectorNormalize( hordir );
//
if ( reachhordist < 20 ) {
speed = 100;
} //end if
else if ( !AAS_HorizontalVelocityForJump( 0, reach->start, reach->end, &speed ) ) {
speed = 400;
} //end if
// looks better crouching off a ledge
EA_Crouch( ms->client );
} //end if
else
{
if ( reachhordist < 20 ) {
if ( dist > 64 ) {
dist = 64;
}
speed = 400 - ( 256 - 4 * dist );
} //end if
else
{
speed = 400;
// Ridah, tweaked this
if ( dist < 128 ) {
speed *= ( dist / 128 );
}
} //end else
} //end else
//
BotCheckBlocked( ms, hordir, qtrue, &result );
//elemantary action
EA_Move( ms->client, hordir, speed );
VectorCopy( hordir, result.movedir );
//
return result;
} //end of the function BotTravel_WalkOffLedge
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotAirControl( vec3_t origin, vec3_t velocity, vec3_t goal, vec3_t dir, float *speed ) {
vec3_t org, vel;
float dist;
int i;
VectorCopy( origin, org );
VectorScale( velocity, 0.1, vel );
for ( i = 0; i < 50; i++ )
{
vel[2] -= sv_gravity * 0.01;
//if going down and next position would be below the goal
if ( vel[2] < 0 && org[2] + vel[2] < goal[2] ) {
VectorScale( vel, ( goal[2] - org[2] ) / vel[2], vel );
VectorAdd( org, vel, org );
VectorSubtract( goal, org, dir );
dist = VectorNormalize( dir );
if ( dist > 32 ) {
dist = 32;
}
*speed = 400 - ( 400 - 13 * dist );
return qtrue;
} //end if
else
{
VectorAdd( org, vel, org );
} //end else
} //end for
VectorSet( dir, 0, 0, 0 );
*speed = 400;
return qfalse;
} //end of the function BotAirControl
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotFinishTravel_WalkOffLedge( bot_movestate_t *ms, aas_reachability_t *reach ) {
vec3_t dir, hordir, end, v;
float dist, speed;
bot_moveresult_t result;
BotClearMoveResult( &result );
//
VectorSubtract( reach->end, ms->origin, dir );
BotCheckBlocked( ms, dir, qtrue, &result );
//
VectorSubtract( reach->end, ms->origin, v );
v[2] = 0;
dist = VectorNormalize( v );
if ( dist > 16 ) {
VectorMA( reach->end, 16, v, end );
} else { VectorCopy( reach->end, end );}
//
if ( !BotAirControl( ms->origin, ms->velocity, end, hordir, &speed ) ) {
//go straight to the reachability end
VectorCopy( dir, hordir );
hordir[2] = 0;
//
dist = VectorNormalize( hordir );
speed = 400;
} //end if
//
// looks better crouching off a ledge
EA_Crouch( ms->client );
EA_Move( ms->client, hordir, speed );
VectorCopy( hordir, result.movedir );
//
return result;
} //end of the function BotFinishTravel_WalkOffLedge
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
/*
bot_moveresult_t BotTravel_Jump(bot_movestate_t *ms, aas_reachability_t *reach)
{
vec3_t hordir;
float dist, gapdist, speed, horspeed, sv_jumpvel;
bot_moveresult_t result;
BotClearMoveResult(&result);
//
sv_jumpvel = botlibglobals.sv_jumpvel->value;
//walk straight to the reachability start
hordir[0] = reach->start[0] - ms->origin[0];
hordir[1] = reach->start[1] - ms->origin[1];
hordir[2] = 0;
dist = VectorNormalize(hordir);
//
speed = 350;
//
gapdist = BotGapDistance(ms, hordir, ms->entitynum);
//if pretty close to the start focus on the reachability end
if (dist < 50 || (gapdist && gapdist < 50))
{
//NOTE: using max speed (400) works best
//if (AAS_HorizontalVelocityForJump(sv_jumpvel, ms->origin, reach->end, &horspeed))
//{
// speed = horspeed * 400 / botlibglobals.sv_maxwalkvelocity->value;
//} //end if
hordir[0] = reach->end[0] - ms->origin[0];
hordir[1] = reach->end[1] - ms->origin[1];
VectorNormalize(hordir);
//elemantary action jump
EA_Jump(ms->client);
//
ms->jumpreach = ms->lastreachnum;
speed = 600;
} //end if
else
{
if (AAS_HorizontalVelocityForJump(sv_jumpvel, reach->start, reach->end, &horspeed))
{
speed = horspeed * 400 / botlibglobals.sv_maxwalkvelocity->value;
} //end if
} //end else
//elemantary action
EA_Move(ms->client, hordir, speed);
VectorCopy(hordir, result.movedir);
//
return result;
} //end of the function BotTravel_Jump*/
/*
bot_moveresult_t BotTravel_Jump(bot_movestate_t *ms, aas_reachability_t *reach)
{
vec3_t hordir, dir1, dir2, mins, maxs, start, end;
float dist1, dist2, speed;
bot_moveresult_t result;
bsp_trace_t trace;
BotClearMoveResult(&result);
//
hordir[0] = reach->start[0] - reach->end[0];
hordir[1] = reach->start[1] - reach->end[1];
hordir[2] = 0;
VectorNormalize(hordir);
//
VectorCopy(reach->start, start);
start[2] += 1;
//minus back the bouding box size plus 16
VectorMA(reach->start, 80, hordir, end);
//
AAS_PresenceTypeBoundingBox(PRESENCE_NORMAL, mins, maxs);
//check for solids
trace = AAS_Trace(start, mins, maxs, end, ms->entitynum, MASK_PLAYERSOLID);
if (trace.startsolid) VectorCopy(start, trace.endpos);
//check for a gap
for (dist1 = 0; dist1 < 80; dist1 += 10)
{
VectorMA(start, dist1+10, hordir, end);
end[2] += 1;
if (AAS_PointAreaNum(end) != ms->reachareanum) break;
} //end for
if (dist1 < 80) VectorMA(reach->start, dist1, hordir, trace.endpos);
// dist1 = BotGapDistance(start, hordir, ms->entitynum);
// if (dist1 && dist1 <= trace.fraction * 80) VectorMA(reach->start, dist1-20, hordir, trace.endpos);
//
VectorSubtract(ms->origin, reach->start, dir1);
dir1[2] = 0;
dist1 = VectorNormalize(dir1);
VectorSubtract(ms->origin, trace.endpos, dir2);
dir2[2] = 0;
dist2 = VectorNormalize(dir2);
//if just before the reachability start
if (DotProduct(dir1, dir2) < -0.8 || dist2 < 5)
{
//botimport.Print(PRT_MESSAGE, "between jump start and run to point\n");
hordir[0] = reach->end[0] - ms->origin[0];
hordir[1] = reach->end[1] - ms->origin[1];
hordir[2] = 0;
VectorNormalize(hordir);
//elemantary action jump
if (dist1 < 24) EA_Jump(ms->client);
else if (dist1 < 32) EA_DelayedJump(ms->client);
EA_Move(ms->client, hordir, 600);
//
ms->jumpreach = ms->lastreachnum;
} //end if
else
{
//botimport.Print(PRT_MESSAGE, "going towards run to point\n");
hordir[0] = trace.endpos[0] - ms->origin[0];
hordir[1] = trace.endpos[1] - ms->origin[1];
hordir[2] = 0;
VectorNormalize(hordir);
//
if (dist2 > 80) dist2 = 80;
speed = 400 - (400 - 5 * dist2);
EA_Move(ms->client, hordir, speed);
} //end else
VectorCopy(hordir, result.movedir);
//
return result;
} //end of the function BotTravel_Jump*/
//*
bot_moveresult_t BotTravel_Jump( bot_movestate_t *ms, aas_reachability_t *reach ) {
vec3_t hordir, dir1, dir2, start, end, runstart;
// vec3_t runstart, dir1, dir2, hordir;
float dist1, dist2, speed;
bot_moveresult_t result;
BotClearMoveResult( &result );
//
AAS_JumpReachRunStart( reach, runstart );
//*
hordir[0] = runstart[0] - reach->start[0];
hordir[1] = runstart[1] - reach->start[1];
hordir[2] = 0;
VectorNormalize( hordir );
//
VectorCopy( reach->start, start );
start[2] += 1;
VectorMA( reach->start, 80, hordir, runstart );
//check for a gap
for ( dist1 = 0; dist1 < 80; dist1 += 10 )
{
VectorMA( start, dist1 + 10, hordir, end );
end[2] += 1;
if ( AAS_PointAreaNum( end ) != ms->reachareanum ) {
break;
}
} //end for
if ( dist1 < 80 ) {
VectorMA( reach->start, dist1, hordir, runstart );
}
//
VectorSubtract( ms->origin, reach->start, dir1 );
dir1[2] = 0;
dist1 = VectorNormalize( dir1 );
VectorSubtract( ms->origin, runstart, dir2 );
dir2[2] = 0;
dist2 = VectorNormalize( dir2 );
//if just before the reachability start
if ( DotProduct( dir1, dir2 ) < -0.8 || dist2 < 12 ) {
// botimport.Print(PRT_MESSAGE, "between jump start and run start point\n");
hordir[0] = reach->end[0] - ms->origin[0];
hordir[1] = reach->end[1] - ms->origin[1];
hordir[2] = 0;
VectorNormalize( hordir );
//elemantary action jump
if ( dist1 < 24 ) {
EA_Jump( ms->client );
} else if ( dist1 < 32 ) {
EA_DelayedJump( ms->client );
}
EA_Move( ms->client, hordir, 600 );
//
ms->jumpreach = ms->lastreachnum;
} //end if
else
{
// botimport.Print(PRT_MESSAGE, "going towards run start point\n");
hordir[0] = runstart[0] - ms->origin[0];
hordir[1] = runstart[1] - ms->origin[1];
hordir[2] = 0;
VectorNormalize( hordir );
//
if ( dist2 > 80 ) {
dist2 = 80;
}
speed = 400 - ( 400 - 5 * dist2 );
EA_Move( ms->client, hordir, speed );
} //end else
VectorCopy( hordir, result.movedir );
//
return result;
} //end of the function BotTravel_Jump*/
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotFinishTravel_Jump( bot_movestate_t *ms, aas_reachability_t *reach ) {
vec3_t hordir, hordir2;
float speed, dist;
bot_moveresult_t result;
BotClearMoveResult( &result );
//if not jumped yet
if ( !ms->jumpreach ) {
return result;
}
//go straight to the reachability end
hordir[0] = reach->end[0] - ms->origin[0];
hordir[1] = reach->end[1] - ms->origin[1];
hordir[2] = 0;
dist = VectorNormalize( hordir );
//
hordir2[0] = reach->end[0] - reach->start[0];
hordir2[1] = reach->end[1] - reach->start[1];
hordir2[2] = 0;
VectorNormalize( hordir2 );
//
if ( DotProduct( hordir, hordir2 ) < -0.5 && dist < 24 ) {
return result;
}
//always use max speed when traveling through the air
speed = 800;
//
EA_Move( ms->client, hordir, speed );
VectorCopy( hordir, result.movedir );
//
return result;
} //end of the function BotFinishTravel_Jump
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotTravel_Ladder( bot_movestate_t *ms, aas_reachability_t *reach ) {
//float dist, speed;
vec3_t dir, viewdir, hordir, pos, p, v1, v2, vec, right;
vec3_t origin = {0, 0, 0};
// vec3_t up = {0, 0, 1};
bot_moveresult_t result;
float dist, speed;
// RF, heavily modified, wolf has different ladder movement
BotClearMoveResult( &result );
//
// if it's a descend reachability
if ( reach->start[2] > reach->end[2] ) {
if ( !( ms->moveflags & MFL_ONGROUND ) ) {
//botimport.Print(PRT_MESSAGE, "not on ground\n");
// RF, wolf has different ladder movement
VectorSubtract( reach->end, reach->start, dir );
dir[2] = 0;
dist = VectorNormalize( dir );
//set the ideal view angles, facing the ladder up or down
viewdir[0] = dir[0];
viewdir[1] = dir[1];
viewdir[2] = 0; // straight forward goes up
if ( dist >= 3.1 ) { // vertical ladder -> ladder reachability has length 3, dont inverse in this case
VectorInverse( viewdir );
}
VectorNormalize( viewdir );
Vector2Angles( viewdir, result.ideal_viewangles );
//elemantary action
EA_Move( ms->client, origin, 0 );
// RF, disabled this check, if we're not on ground, then it shouldn't be a problem, and the ladder flag is unreliable
//if (ms->moveflags & MFL_AGAINSTLADDER) {
//botimport.Print(PRT_MESSAGE, "against ladder, descending\n");
EA_MoveBack( ms->client ); // only move back if we are touching the ladder brush
// check for sideways adjustments to stay on the center of the ladder
VectorMA( ms->origin, 18, viewdir, p );
VectorCopy( reach->start, v1 );
v1[2] = ms->origin[2];
VectorCopy( reach->end, v2 );
v2[2] = ms->origin[2];
VectorSubtract( v2, v1, vec );
VectorNormalize( vec );
VectorMA( v1, -32, vec, v1 );
VectorMA( v2, 32, vec, v2 );
ProjectPointOntoVector( p, v1, v2, pos );
VectorSubtract( pos, p, vec );
if ( VectorLength( vec ) > 2 ) {
AngleVectors( result.ideal_viewangles, NULL, right, NULL );
if ( DotProduct( vec, right ) > 0 ) {
EA_MoveRight( ms->client );
} else {
EA_MoveLeft( ms->client );
}
}
//}
//set movement view flag so the AI can see the view is focussed
result.flags |= MOVERESULT_MOVEMENTVIEW;
} //end if
else
{
//botimport.Print(PRT_MESSAGE, "moving towards ladder top\n");
// find a postion back away from the edge of the ladder
VectorSubtract( reach->end, reach->start, hordir );
hordir[2] = 0;
VectorNormalize( hordir );
VectorMA( reach->start, -24, hordir, pos );
VectorCopy( reach->end, v1 );
v1[2] = pos[2];
// project our position onto the vector
ProjectPointOntoVectorBounded( ms->origin, pos, v1, p );
VectorSubtract( p, ms->origin, dir );
//make sure the horizontal movement is large anough
VectorCopy( dir, hordir );
hordir[2] = 0;
dist = VectorNormalize( hordir );
if ( dist < 64 ) { // within range, go for the end
//botimport.Print(PRT_MESSAGE, "found top, moving towards ladder edge\n");
VectorSubtract( reach->end, reach->start, dir );
//make sure the horizontal movement is large anough
dir[2] = 0;
VectorNormalize( dir );
//set the ideal view angles, facing the ladder up or down
viewdir[0] = dir[0];
viewdir[1] = dir[1];
viewdir[2] = 0;
VectorInverse( viewdir );
VectorNormalize( viewdir );
Vector2Angles( viewdir, result.ideal_viewangles );
result.flags |= MOVERESULT_MOVEMENTVIEW;
// if we are still on ground, then start moving backwards until we are in air
if ( ( dist < 4 ) && ( ms->moveflags & MFL_ONGROUND ) ) {
//botimport.Print(PRT_MESSAGE, "close to edge, backing in slowly..\n");
VectorSubtract( reach->end, ms->origin, vec );
vec[2] = 0;
VectorNormalize( vec );
EA_Move( ms->client, vec, 100 );
VectorCopy( vec, result.movedir );
result.ideal_viewangles[PITCH] = 45; // face downwards
return result;
}
}
//
dir[0] = hordir[0];
dir[1] = hordir[1];
dir[2] = 0;
if ( dist > 150 ) {
dist = 150;
}
speed = 400 - ( 300 - 2 * dist );
//botimport.Print(PRT_MESSAGE, "speed = %.0f\n", speed);
EA_Move( ms->client, dir, speed );
} //end else
} else {
if ( ( ms->moveflags & MFL_AGAINSTLADDER )
//NOTE: not a good idea for ladders starting in water
|| !( ms->moveflags & MFL_ONGROUND ) ) {
//botimport.Print(PRT_MESSAGE, "against ladder or not on ground\n");
// RF, wolf has different ladder movement
VectorSubtract( reach->end, reach->start, dir );
VectorNormalize( dir );
//set the ideal view angles, facing the ladder up or down
viewdir[0] = dir[0];
viewdir[1] = dir[1];
viewdir[2] = dir[2];
if ( dir[2] < 0 ) { // going down, so face the other way (towards ladder)
VectorInverse( viewdir );
}
viewdir[2] = 0; // straight forward goes up
VectorNormalize( viewdir );
Vector2Angles( viewdir, result.ideal_viewangles );
//elemantary action
EA_Move( ms->client, origin, 0 );
if ( dir[2] < 0 ) { // going down, so face the other way
EA_MoveBack( ms->client );
} else {
EA_MoveForward( ms->client );
}
// RF, against ladder code isn't completely accurate
//if (ms->moveflags & MFL_AGAINSTLADDER) {
// check for sideways adjustments to stay on the center of the ladder
VectorMA( ms->origin, 18, viewdir, p );
VectorCopy( reach->start, v1 );
v1[2] = ms->origin[2];
VectorCopy( reach->end, v2 );
v2[2] = ms->origin[2];
VectorSubtract( v2, v1, vec );
VectorNormalize( vec );
VectorMA( v1, -32, vec, v1 );
VectorMA( v2, 32, vec, v2 );
ProjectPointOntoVectorBounded( p, v1, v2, pos );
VectorSubtract( pos, p, vec );
if ( VectorLength( vec ) > 2 ) {
AngleVectors( result.ideal_viewangles, NULL, right, NULL );
if ( DotProduct( vec, right ) > 0 ) {
EA_MoveRight( ms->client );
} else {
EA_MoveLeft( ms->client );
}
}
//}
//set movement view flag so the AI can see the view is focussed
result.flags |= MOVERESULT_MOVEMENTVIEW;
} //end if
else
{
//botimport.Print(PRT_MESSAGE, "moving towards ladder base\n");
// find a postion back away from the base of the ladder
VectorSubtract( reach->end, reach->start, hordir );
hordir[2] = 0;
VectorNormalize( hordir );
VectorMA( reach->start, -24, hordir, pos );
VectorCopy( reach->end, v1 );
v1[2] = pos[2];
// project our position onto the vector
ProjectPointOntoVectorBounded( ms->origin, pos, v1, p );
VectorSubtract( p, ms->origin, dir );
//make sure the horizontal movement is large anough
VectorCopy( dir, hordir );
hordir[2] = 0;
dist = VectorNormalize( hordir );
if ( dist < 16 ) { // within range, go for the end
//botimport.Print(PRT_MESSAGE, "found base, moving towards ladder top\n");
VectorSubtract( reach->end, ms->origin, dir );
//make sure the horizontal movement is large anough
VectorCopy( dir, hordir );
hordir[2] = 0;
dist = VectorNormalize( hordir );
//set the ideal view angles, facing the ladder up or down
viewdir[0] = dir[0];
viewdir[1] = dir[1];
viewdir[2] = 0;
VectorNormalize( viewdir );
Vector2Angles( viewdir, result.ideal_viewangles );
result.flags |= MOVERESULT_MOVEMENTVIEW;
}
//
dir[0] = hordir[0];
dir[1] = hordir[1];
// if (dist < 48) {
// if (dir[2] > 0) dir[2] = 1;
// else dir[2] = -1;
// } else {
dir[2] = 0;
// }
if ( dist > 50 ) {
dist = 50;
}
speed = 400 - ( 300 - 6 * dist );
EA_Move( ms->client, dir, speed );
} //end else
}
//save the movement direction
VectorCopy( dir, result.movedir );
//
return result;
} //end of the function BotTravel_Ladder
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotTravel_Teleport( bot_movestate_t *ms, aas_reachability_t *reach ) {
vec3_t hordir;
float dist;
bot_moveresult_t result;
BotClearMoveResult( &result );
//if the bot is being teleported
if ( ms->moveflags & MFL_TELEPORTED ) {
return result;
}
//walk straight to center of the teleporter
VectorSubtract( reach->start, ms->origin, hordir );
if ( !( ms->moveflags & MFL_SWIMMING ) ) {
hordir[2] = 0;
}
dist = VectorNormalize( hordir );
//
BotCheckBlocked( ms, hordir, qtrue, &result );
if ( dist < 30 ) {
EA_Move( ms->client, hordir, 200 );
} else { EA_Move( ms->client, hordir, 400 );}
if ( ms->moveflags & MFL_SWIMMING ) {
result.flags |= MOVERESULT_SWIMVIEW;
}
VectorCopy( hordir, result.movedir );
return result;
} //end of the function BotTravel_Teleport
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotTravel_Elevator( bot_movestate_t *ms, aas_reachability_t *reach ) {
vec3_t dir, dir1, dir2, hordir, bottomcenter;
float dist, dist1, dist2, speed;
bot_moveresult_t result;
BotClearMoveResult( &result );
//if standing on the plat
if ( BotOnMover( ms->origin, ms->entitynum, reach ) ) {
#ifdef DEBUG_ELEVATOR
botimport.Print( PRT_MESSAGE, "bot on elevator\n" );
#endif //DEBUG_ELEVATOR
//if vertically not too far from the end point
if ( abs( ms->origin[2] - reach->end[2] ) < sv_maxbarrier ) {
#ifdef DEBUG_ELEVATOR
botimport.Print( PRT_MESSAGE, "bot moving to end\n" );
#endif //DEBUG_ELEVATOR
//move to the end point
VectorSubtract( reach->end, ms->origin, hordir );
hordir[2] = 0;
VectorNormalize( hordir );
if ( !BotCheckBarrierJump( ms, hordir, 100 ) ) {
EA_Move( ms->client, hordir, 400 );
} //end if
VectorCopy( hordir, result.movedir );
} //end else
//if not really close to the center of the elevator
else
{
MoverBottomCenter( reach, bottomcenter );
VectorSubtract( bottomcenter, ms->origin, hordir );
hordir[2] = 0;
dist = VectorNormalize( hordir );
//
if ( dist > 10 ) {
#ifdef DEBUG_ELEVATOR
botimport.Print( PRT_MESSAGE, "bot moving to center\n" );
#endif //DEBUG_ELEVATOR
//move to the center of the plat
if ( dist > 100 ) {
dist = 100;
}
speed = 400 - ( 400 - 4 * dist );
//
EA_Move( ms->client, hordir, speed );
VectorCopy( hordir, result.movedir );
} //end if
} //end else
} //end if
else
{
#ifdef DEBUG_ELEVATOR
botimport.Print( PRT_MESSAGE, "bot not on elevator\n" );
#endif //DEBUG_ELEVATOR
//if very near the reachability end
VectorSubtract( reach->end, ms->origin, dir );
dist = VectorLength( dir );
if ( dist < 64 ) {
if ( dist > 60 ) {
dist = 60;
}
speed = 360 - ( 360 - 6 * dist );
//
if ( ( ms->moveflags & MFL_SWIMMING ) || !BotCheckBarrierJump( ms, dir, 50 ) ) {
if ( speed > 5 ) {
EA_Move( ms->client, dir, speed );
}
} //end if
VectorCopy( dir, result.movedir );
//
if ( ms->moveflags & MFL_SWIMMING ) {
result.flags |= MOVERESULT_SWIMVIEW;
}
//stop using this reachability
ms->reachability_time = 0;
return result;
} //end if
//get direction and distance to reachability start
VectorSubtract( reach->start, ms->origin, dir1 );
if ( !( ms->moveflags & MFL_SWIMMING ) ) {
dir1[2] = 0;
}
dist1 = VectorNormalize( dir1 );
//if the elevator isn't down
if ( !MoverDown( reach ) ) {
#ifdef DEBUG_ELEVATOR
botimport.Print( PRT_MESSAGE, "elevator not down\n" );
#endif //DEBUG_ELEVATOR
dist = dist1;
VectorCopy( dir1, dir );
//
BotCheckBlocked( ms, dir, qfalse, &result );
//
if ( dist > 60 ) {
dist = 60;
}
speed = 360 - ( 360 - 6 * dist );
//
if ( !( ms->moveflags & MFL_SWIMMING ) && !BotCheckBarrierJump( ms, dir, 50 ) ) {
if ( speed > 5 ) {
EA_Move( ms->client, dir, speed );
}
} //end if
VectorCopy( dir, result.movedir );
//
if ( ms->moveflags & MFL_SWIMMING ) {
result.flags |= MOVERESULT_SWIMVIEW;
}
//this isn't a failure... just wait till the elevator comes down
//result.failure = qtrue;
result.type = RESULTTYPE_ELEVATORUP;
result.flags |= MOVERESULT_WAITING;
return result;
} //end if
//get direction and distance to elevator bottom center
MoverBottomCenter( reach, bottomcenter );
VectorSubtract( bottomcenter, ms->origin, dir2 );
if ( !( ms->moveflags & MFL_SWIMMING ) ) {
dir2[2] = 0;
}
dist2 = VectorNormalize( dir2 );
//if very close to the reachability start or
//closer to the elevator center or
//between reachability start and elevator center
if ( dist1 < 20 || dist2 < dist1 || DotProduct( dir1, dir2 ) < 0 ) {
#ifdef DEBUG_ELEVATOR
botimport.Print( PRT_MESSAGE, "bot moving to center\n" );
#endif //DEBUG_ELEVATOR
dist = dist2;
VectorCopy( dir2, dir );
} //end if
else //closer to the reachability start
{
#ifdef DEBUG_ELEVATOR
botimport.Print( PRT_MESSAGE, "bot moving to start\n" );
#endif //DEBUG_ELEVATOR
dist = dist1;
VectorCopy( dir1, dir );
} //end else
//
BotCheckBlocked( ms, dir, qfalse, &result );
//
if ( dist > 60 ) {
dist = 60;
}
speed = 400 - ( 400 - 6 * dist );
//
if ( !( ms->moveflags & MFL_SWIMMING ) && !BotCheckBarrierJump( ms, dir, 50 ) ) {
EA_Move( ms->client, dir, speed );
} //end if
VectorCopy( dir, result.movedir );
//
if ( ms->moveflags & MFL_SWIMMING ) {
result.flags |= MOVERESULT_SWIMVIEW;
}
} //end else
return result;
} //end of the function BotTravel_Elevator
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotFinishTravel_Elevator( bot_movestate_t *ms, aas_reachability_t *reach ) {
vec3_t bottomcenter, bottomdir, topdir;
bot_moveresult_t result;
BotClearMoveResult( &result );
//
MoverBottomCenter( reach, bottomcenter );
VectorSubtract( bottomcenter, ms->origin, bottomdir );
//
VectorSubtract( reach->end, ms->origin, topdir );
//
if ( Q_fabs( bottomdir[2] ) < Q_fabs( topdir[2] ) ) {
VectorNormalize( bottomdir );
EA_Move( ms->client, bottomdir, 300 );
} //end if
else
{
VectorNormalize( topdir );
EA_Move( ms->client, topdir, 300 );
} //end else
return result;
} //end of the function BotFinishTravel_Elevator
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void BotFuncBobStartEnd( aas_reachability_t *reach, vec3_t start, vec3_t end, vec3_t origin ) {
int spawnflags, modelnum;
vec3_t mins, maxs, mid, angles = {0, 0, 0};
int num0, num1;
modelnum = reach->facenum & 0x0000FFFF;
if ( !AAS_OriginOfEntityWithModelNum( modelnum, origin ) ) {
botimport.Print( PRT_MESSAGE, "BotFuncBobStartEnd: no entity with model %d\n", modelnum );
VectorSet( start, 0, 0, 0 );
VectorSet( end, 0, 0, 0 );
return;
} //end if
AAS_BSPModelMinsMaxsOrigin( modelnum, angles, mins, maxs, NULL );
VectorAdd( mins, maxs, mid );
VectorScale( mid, 0.5, mid );
VectorCopy( mid, start );
VectorCopy( mid, end );
spawnflags = reach->facenum >> 16;
num0 = reach->edgenum >> 16;
if ( num0 > 0x00007FFF ) {
num0 |= 0xFFFF0000;
}
num1 = reach->edgenum & 0x0000FFFF;
if ( num1 > 0x00007FFF ) {
num1 |= 0xFFFF0000;
}
if ( spawnflags & 1 ) {
start[0] = num0;
end[0] = num1;
//
origin[0] += mid[0];
origin[1] = mid[1];
origin[2] = mid[2];
} //end if
else if ( spawnflags & 2 ) {
start[1] = num0;
end[1] = num1;
//
origin[0] = mid[0];
origin[1] += mid[1];
origin[2] = mid[2];
} //end else if
else
{
start[2] = num0;
end[2] = num1;
//
origin[0] = mid[0];
origin[1] = mid[1];
origin[2] += mid[2];
} //end else
} //end of the function BotFuncBobStartEnd
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotTravel_FuncBobbing( bot_movestate_t *ms, aas_reachability_t *reach ) {
vec3_t dir, dir1, dir2, hordir, bottomcenter, bob_start, bob_end, bob_origin;
float dist, dist1, dist2, speed;
bot_moveresult_t result;
BotClearMoveResult( &result );
//
BotFuncBobStartEnd( reach, bob_start, bob_end, bob_origin );
//if standing ontop of the func_bobbing
if ( BotOnMover( ms->origin, ms->entitynum, reach ) ) {
#ifdef DEBUG_FUNCBOB
botimport.Print( PRT_MESSAGE, "bot on func_bobbing\n" );
#endif
//if near end point of reachability
VectorSubtract( bob_origin, bob_end, dir );
if ( VectorLength( dir ) < 24 ) {
#ifdef DEBUG_FUNCBOB
botimport.Print( PRT_MESSAGE, "bot moving to reachability end\n" );
#endif
//move to the end point
VectorSubtract( reach->end, ms->origin, hordir );
hordir[2] = 0;
VectorNormalize( hordir );
if ( !BotCheckBarrierJump( ms, hordir, 100 ) ) {
EA_Move( ms->client, hordir, 400 );
} //end if
VectorCopy( hordir, result.movedir );
} //end else
//if not really close to the center of the elevator
else
{
MoverBottomCenter( reach, bottomcenter );
VectorSubtract( bottomcenter, ms->origin, hordir );
hordir[2] = 0;
dist = VectorNormalize( hordir );
//
if ( dist > 10 ) {
#ifdef DEBUG_FUNCBOB
botimport.Print( PRT_MESSAGE, "bot moving to func_bobbing center\n" );
#endif
//move to the center of the plat
if ( dist > 100 ) {
dist = 100;
}
speed = 400 - ( 400 - 4 * dist );
//
EA_Move( ms->client, hordir, speed );
VectorCopy( hordir, result.movedir );
} //end if
} //end else
} //end if
else
{
#ifdef DEBUG_FUNCBOB
botimport.Print( PRT_MESSAGE, "bot not ontop of func_bobbing\n" );
#endif
//if very near the reachability end
VectorSubtract( reach->end, ms->origin, dir );
dist = VectorLength( dir );
if ( dist < 64 ) {
#ifdef DEBUG_FUNCBOB
botimport.Print( PRT_MESSAGE, "bot moving to end\n" );
#endif
if ( dist > 60 ) {
dist = 60;
}
speed = 360 - ( 360 - 6 * dist );
//if swimming or no barrier jump
if ( ( ms->moveflags & MFL_SWIMMING ) || !BotCheckBarrierJump( ms, dir, 50 ) ) {
if ( speed > 5 ) {
EA_Move( ms->client, dir, speed );
}
} //end if
VectorCopy( dir, result.movedir );
//
if ( ms->moveflags & MFL_SWIMMING ) {
result.flags |= MOVERESULT_SWIMVIEW;
}
//stop using this reachability
ms->reachability_time = 0;
return result;
} //end if
//get direction and distance to reachability start
VectorSubtract( reach->start, ms->origin, dir1 );
if ( !( ms->moveflags & MFL_SWIMMING ) ) {
dir1[2] = 0;
}
dist1 = VectorNormalize( dir1 );
//if func_bobbing is Not it's start position
VectorSubtract( bob_origin, bob_start, dir );
if ( VectorLength( dir ) > 16 ) {
#ifdef DEBUG_FUNCBOB
botimport.Print( PRT_MESSAGE, "func_bobbing not at start\n" );
#endif
dist = dist1;
VectorCopy( dir1, dir );
//
BotCheckBlocked( ms, dir, qfalse, &result );
//
if ( dist > 60 ) {
dist = 60;
}
speed = 360 - ( 360 - 6 * dist );
//
if ( !( ms->moveflags & MFL_SWIMMING ) && !BotCheckBarrierJump( ms, dir, 50 ) ) {
if ( speed > 5 ) {
EA_Move( ms->client, dir, speed );
}
} //end if
VectorCopy( dir, result.movedir );
//
if ( ms->moveflags & MFL_SWIMMING ) {
result.flags |= MOVERESULT_SWIMVIEW;
}
//this isn't a failure... just wait till the func_bobbing arrives
result.type = RESULTTYPE_ELEVATORUP;
result.flags |= MOVERESULT_WAITING;
return result;
} //end if
//get direction and distance to func_bob bottom center
MoverBottomCenter( reach, bottomcenter );
VectorSubtract( bottomcenter, ms->origin, dir2 );
if ( !( ms->moveflags & MFL_SWIMMING ) ) {
dir2[2] = 0;
}
dist2 = VectorNormalize( dir2 );
//if very close to the reachability start or
//closer to the elevator center or
//between reachability start and func_bobbing center
if ( dist1 < 20 || dist2 < dist1 || DotProduct( dir1, dir2 ) < 0 ) {
#ifdef DEBUG_FUNCBOB
botimport.Print( PRT_MESSAGE, "bot moving to func_bobbing center\n" );
#endif
dist = dist2;
VectorCopy( dir2, dir );
} //end if
else //closer to the reachability start
{
#ifdef DEBUG_FUNCBOB
botimport.Print( PRT_MESSAGE, "bot moving to reachability start\n" );
#endif
dist = dist1;
VectorCopy( dir1, dir );
} //end else
//
BotCheckBlocked( ms, dir, qfalse, &result );
//
if ( dist > 60 ) {
dist = 60;
}
speed = 400 - ( 400 - 6 * dist );
//
if ( !( ms->moveflags & MFL_SWIMMING ) && !BotCheckBarrierJump( ms, dir, 50 ) ) {
EA_Move( ms->client, dir, speed );
} //end if
VectorCopy( dir, result.movedir );
//
if ( ms->moveflags & MFL_SWIMMING ) {
result.flags |= MOVERESULT_SWIMVIEW;
}
} //end else
return result;
} //end of the function BotTravel_FuncBobbing
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotFinishTravel_FuncBobbing( bot_movestate_t *ms, aas_reachability_t *reach ) {
vec3_t bob_origin, bob_start, bob_end, dir, hordir, bottomcenter;
bot_moveresult_t result;
float dist, speed;
BotClearMoveResult( &result );
//
BotFuncBobStartEnd( reach, bob_start, bob_end, bob_origin );
//
VectorSubtract( bob_origin, bob_end, dir );
dist = VectorLength( dir );
//if the func_bobbing is near the end
if ( dist < 16 ) {
VectorSubtract( reach->end, ms->origin, hordir );
if ( !( ms->moveflags & MFL_SWIMMING ) ) {
hordir[2] = 0;
}
dist = VectorNormalize( hordir );
//
if ( dist > 60 ) {
dist = 60;
}
speed = 360 - ( 360 - 6 * dist );
//
if ( speed > 5 ) {
EA_Move( ms->client, dir, speed );
}
VectorCopy( dir, result.movedir );
//
if ( ms->moveflags & MFL_SWIMMING ) {
result.flags |= MOVERESULT_SWIMVIEW;
}
} //end if
else
{
MoverBottomCenter( reach, bottomcenter );
VectorSubtract( bottomcenter, ms->origin, hordir );
if ( !( ms->moveflags & MFL_SWIMMING ) ) {
hordir[2] = 0;
}
dist = VectorNormalize( hordir );
//
if ( dist > 5 ) {
//move to the center of the plat
if ( dist > 100 ) {
dist = 100;
}
speed = 400 - ( 400 - 4 * dist );
//
EA_Move( ms->client, hordir, speed );
VectorCopy( hordir, result.movedir );
} //end if
} //end else
return result;
} //end of the function BotFinishTravel_FuncBobbing
//===========================================================================
// 0 no valid grapple hook visible
// 1 the grapple hook is still flying
// 2 the grapple hooked into a wall
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
/*
int GrappleState(bot_movestate_t *ms, aas_reachability_t *reach)
{
static int grapplemodelindex;
int i;
vec3_t dir;
aas_entityinfo_t entinfo;
if (!grapplemodelindex)
{
grapplemodelindex = AAS_IndexFromModel("models/weapons/grapple/hook/tris.md2");
} //end if
for (i = AAS_NextEntity(0); i; i = AAS_NextEntity(i))
{
if (AAS_EntityModelindex(i) == grapplemodelindex)
{
AAS_EntityInfo(i, &entinfo);
if (VectorCompare(entinfo.origin, entinfo.old_origin))
{
VectorSubtract(entinfo.origin, reach->end, dir);
//if hooked near the reachability end
if (VectorLength(dir) < 32) return 2;
} //end if
else
{
//still shooting hook
return 1;
} //end else
} //end if
} //end if
//no valid grapple at all
return 0;
} //end of the function GrappleState*/
//===========================================================================
// 0 no valid grapple hook visible
// 1 the grapple hook is still flying
// 2 the grapple hooked into a wall
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int GrappleState( bot_movestate_t *ms, aas_reachability_t *reach ) {
static int grapplemodelindex;
static libvar_t *laserhook;
int i;
vec3_t dir;
aas_entityinfo_t entinfo;
if ( !laserhook ) {
laserhook = LibVar( "laserhook", "0" );
}
if ( !laserhook->value && !grapplemodelindex ) {
grapplemodelindex = AAS_IndexFromModel( "models/weapons/grapple/hook/tris.md2" );
} //end if
for ( i = AAS_NextEntity( 0 ); i; i = AAS_NextEntity( i ) )
{
if ( ( !laserhook->value && AAS_EntityModelindex( i ) == grapplemodelindex )
// || (laserhook->value && (AAS_EntityRenderFX(i) & RF_BEAM))
) {
AAS_EntityInfo( i, &entinfo );
//if the origin is equal to the last visible origin
if ( VectorCompare( entinfo.origin, entinfo.lastvisorigin ) ) {
VectorSubtract( entinfo.origin, reach->end, dir );
//if hooked near the reachability end
if ( VectorLength( dir ) < 32 ) {
return 2;
}
} //end if
else
{
//still shooting hook
return 1;
} //end else
} //end if
} //end for
//no valid grapple at all
return 0;
} //end of the function GrappleState
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void BotResetGrapple( bot_movestate_t *ms ) {
aas_reachability_t reach;
AAS_ReachabilityFromNum( ms->lastreachnum, &reach );
//if not using the grapple hook reachability anymore
if ( reach.traveltype != TRAVEL_GRAPPLEHOOK ) {
if ( ( ms->moveflags & MFL_ACTIVEGRAPPLE ) || ms->grapplevisible_time ) {
EA_Command( ms->client, CMD_HOOKOFF );
ms->moveflags &= ~MFL_ACTIVEGRAPPLE;
ms->grapplevisible_time = 0;
#ifdef DEBUG_GRAPPLE
botimport.Print( PRT_MESSAGE, "reset grapple\n" );
#endif //DEBUG_GRAPPLE
} //end if
} //end if
} //end of the function BotResetGrapple
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotTravel_Grapple( bot_movestate_t *ms, aas_reachability_t *reach ) {
bot_moveresult_t result;
float dist, speed;
vec3_t dir, viewdir, org;
int state, areanum;
#ifdef DEBUG_GRAPPLE
static int debugline;
if ( !debugline ) {
debugline = botimport.DebugLineCreate();
}
botimport.DebugLineShow( debugline, reach->start, reach->end, LINECOLOR_BLUE );
#endif //DEBUG_GRAPPLE
BotClearMoveResult( &result );
//
if ( ms->moveflags & MFL_GRAPPLERESET ) {
EA_Command( ms->client, CMD_HOOKOFF );
ms->moveflags &= ~MFL_ACTIVEGRAPPLE;
return result;
} //end if
//
if ( ms->moveflags & MFL_ACTIVEGRAPPLE ) {
#ifdef DEBUG_GRAPPLE
botimport.Print( PRT_MESSAGE, "BotTravel_Grapple: active grapple\n" );
#endif //DEBUG_GRAPPLE
//
state = GrappleState( ms, reach );
//
VectorSubtract( reach->end, ms->origin, dir );
dir[2] = 0;
dist = VectorLength( dir );
//if very close to the grapple end or
//the grappled is hooked and the bot doesn't get any closer
if ( state && dist < 48 ) {
if ( ms->lastgrappledist - dist < 1 ) {
EA_Command( ms->client, CMD_HOOKOFF );
ms->moveflags &= ~MFL_ACTIVEGRAPPLE;
ms->moveflags |= MFL_GRAPPLERESET;
ms->reachability_time = 0; //end the reachability
#ifdef DEBUG_GRAPPLE
botimport.Print( PRT_ERROR, "grapple normal end\n" );
#endif //DEBUG_GRAPPLE
} //end if
} //end if
//if no valid grapple at all, or the grapple hooked and the bot
//isn't moving anymore
else if ( !state || ( state == 2 && dist > ms->lastgrappledist - 2 ) ) {
if ( ms->grapplevisible_time < AAS_Time() - 0.4 ) {
#ifdef DEBUG_GRAPPLE
botimport.Print( PRT_ERROR, "grapple not visible\n" );
#endif //DEBUG_GRAPPLE
EA_Command( ms->client, CMD_HOOKOFF );
ms->moveflags &= ~MFL_ACTIVEGRAPPLE;
ms->moveflags |= MFL_GRAPPLERESET;
ms->reachability_time = 0; //end the reachability
//result.failure = qtrue;
//result.type = RESULTTYPE_INVISIBLEGRAPPLE;
return result;
} //end if
} //end if
else
{
ms->grapplevisible_time = AAS_Time();
} //end else
//remember the current grapple distance
ms->lastgrappledist = dist;
} //end if
else
{
#ifdef DEBUG_GRAPPLE
botimport.Print( PRT_MESSAGE, "BotTravel_Grapple: inactive grapple\n" );
#endif //DEBUG_GRAPPLE
//
ms->grapplevisible_time = AAS_Time();
//
VectorSubtract( reach->start, ms->origin, dir );
if ( !( ms->moveflags & MFL_SWIMMING ) ) {
dir[2] = 0;
}
VectorAdd( ms->origin, ms->viewoffset, org );
VectorSubtract( reach->end, org, viewdir );
//
dist = VectorNormalize( dir );
Vector2Angles( viewdir, result.ideal_viewangles );
result.flags |= MOVERESULT_MOVEMENTVIEW;
//
if ( dist < 5 &&
Q_fabs( AngleDiff( result.ideal_viewangles[0], ms->viewangles[0] ) ) < 2 &&
Q_fabs( AngleDiff( result.ideal_viewangles[1], ms->viewangles[1] ) ) < 2 ) {
#ifdef DEBUG_GRAPPLE
botimport.Print( PRT_MESSAGE, "BotTravel_Grapple: activating grapple\n" );
#endif //DEBUG_GRAPPLE
EA_Command( ms->client, CMD_HOOKON );
ms->moveflags |= MFL_ACTIVEGRAPPLE;
ms->lastgrappledist = 999999;
} //end if
else
{
if ( dist < 70 ) {
speed = 300 - ( 300 - 4 * dist );
} else { speed = 400;}
//
BotCheckBlocked( ms, dir, qtrue, &result );
//elemantary action move in direction
EA_Move( ms->client, dir, speed );
VectorCopy( dir, result.movedir );
} //end else
//if in another area before actually grappling
areanum = AAS_PointAreaNum( ms->origin );
if ( areanum && areanum != ms->reachareanum ) {
ms->reachability_time = 0;
}
} //end else
return result;
} //end of the function BotTravel_Grapple
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotTravel_RocketJump( bot_movestate_t *ms, aas_reachability_t *reach ) {
vec3_t hordir;
float dist, speed;
bot_moveresult_t result;
//botimport.Print(PRT_MESSAGE, "BotTravel_RocketJump: bah\n");
BotClearMoveResult( &result );
//
hordir[0] = reach->start[0] - ms->origin[0];
hordir[1] = reach->start[1] - ms->origin[1];
hordir[2] = 0;
//
dist = VectorNormalize( hordir );
//
if ( dist < 5 ) {
// botimport.Print(PRT_MESSAGE, "between jump start and run start point\n");
hordir[0] = reach->end[0] - ms->origin[0];
hordir[1] = reach->end[1] - ms->origin[1];
hordir[2] = 0;
VectorNormalize( hordir );
//elemantary action jump
EA_Jump( ms->client );
EA_Attack( ms->client );
EA_Move( ms->client, hordir, 800 );
//
ms->jumpreach = ms->lastreachnum;
} //end if
else
{
if ( dist > 80 ) {
dist = 80;
}
speed = 400 - ( 400 - 5 * dist );
EA_Move( ms->client, hordir, speed );
} //end else
//
/*
vec3_t hordir, dir1, dir2, start, end, runstart;
float dist1, dist2, speed;
bot_moveresult_t result;
botimport.Print(PRT_MESSAGE, "BotTravel_RocketJump: bah\n");
BotClearMoveResult(&result);
AAS_JumpReachRunStart(reach, runstart);
//
hordir[0] = runstart[0] - reach->start[0];
hordir[1] = runstart[1] - reach->start[1];
hordir[2] = 0;
VectorNormalize(hordir);
//
VectorCopy(reach->start, start);
start[2] += 1;
VectorMA(reach->start, 80, hordir, runstart);
//check for a gap
for (dist1 = 0; dist1 < 80; dist1 += 10)
{
VectorMA(start, dist1+10, hordir, end);
end[2] += 1;
if (AAS_PointAreaNum(end) != ms->reachareanum) break;
} //end for
if (dist1 < 80) VectorMA(reach->start, dist1, hordir, runstart);
//
VectorSubtract(ms->origin, reach->start, dir1);
dir1[2] = 0;
dist1 = VectorNormalize(dir1);
VectorSubtract(ms->origin, runstart, dir2);
dir2[2] = 0;
dist2 = VectorNormalize(dir2);
//if just before the reachability start
if (DotProduct(dir1, dir2) < -0.8 || dist2 < 5)
{
// botimport.Print(PRT_MESSAGE, "between jump start and run start point\n");
hordir[0] = reach->end[0] - ms->origin[0];
hordir[1] = reach->end[1] - ms->origin[1];
hordir[2] = 0;
VectorNormalize(hordir);
//elemantary action jump
if (dist1 < 24) EA_Jump(ms->client);
else if (dist1 < 32) EA_DelayedJump(ms->client);
EA_Attack(ms->client);
EA_Move(ms->client, hordir, 800);
//
ms->jumpreach = ms->lastreachnum;
} //end if
else
{
// botimport.Print(PRT_MESSAGE, "going towards run start point\n");
hordir[0] = runstart[0] - ms->origin[0];
hordir[1] = runstart[1] - ms->origin[1];
hordir[2] = 0;
VectorNormalize(hordir);
//
if (dist2 > 80) dist2 = 80;
speed = 400 - (400 - 5 * dist2);
EA_Move(ms->client, hordir, speed);
} //end else
*/
//look in the movement direction
Vector2Angles( hordir, result.ideal_viewangles );
//look straight down
result.ideal_viewangles[PITCH] = 90;
//set the view angles directly
EA_View( ms->client, result.ideal_viewangles );
//view is important for the movment
result.flags |= MOVERESULT_MOVEMENTVIEWSET;
//select the rocket launcher
EA_SelectWeapon( ms->client, WEAPONINDEX_ROCKET_LAUNCHER );
//weapon is used for movement
result.weapon = WEAPONINDEX_ROCKET_LAUNCHER;
result.flags |= MOVERESULT_MOVEMENTWEAPON;
//
VectorCopy( hordir, result.movedir );
//
return result;
} //end of the function BotTravel_RocketJump
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotTravel_BFGJump( bot_movestate_t *ms, aas_reachability_t *reach ) {
bot_moveresult_t result;
BotClearMoveResult( &result );
//
return result;
} //end of the function BotTravel_BFGJump
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotFinishTravel_WeaponJump( bot_movestate_t *ms, aas_reachability_t *reach ) {
vec3_t hordir;
bot_moveresult_t result;
BotClearMoveResult( &result );
//if not jumped yet
if ( !ms->jumpreach ) {
return result;
}
//go straight to the reachability end
hordir[0] = reach->end[0] - ms->origin[0];
hordir[1] = reach->end[1] - ms->origin[1];
hordir[2] = 0;
VectorNormalize( hordir );
//always use max speed when traveling through the air
EA_Move( ms->client, hordir, 800 );
VectorCopy( hordir, result.movedir );
//
return result;
} //end of the function BotFinishTravel_WeaponJump
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotTravel_JumpPad( bot_movestate_t *ms, aas_reachability_t *reach ) {
float dist, speed;
vec3_t hordir;
bot_moveresult_t result;
BotClearMoveResult( &result );
//first walk straight to the reachability start
hordir[0] = reach->start[0] - ms->origin[0];
hordir[1] = reach->start[1] - ms->origin[1];
hordir[2] = 0;
dist = VectorNormalize( hordir );
//
BotCheckBlocked( ms, hordir, qtrue, &result );
speed = 400;
//elemantary action move in direction
EA_Move( ms->client, hordir, speed );
VectorCopy( hordir, result.movedir );
//
return result;
} //end of the function BotTravel_JumpPad
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotFinishTravel_JumpPad( bot_movestate_t *ms, aas_reachability_t *reach ) {
float speed;
vec3_t hordir;
bot_moveresult_t result;
BotClearMoveResult( &result );
if ( !BotAirControl( ms->origin, ms->velocity, reach->end, hordir, &speed ) ) {
hordir[0] = reach->end[0] - ms->origin[0];
hordir[1] = reach->end[1] - ms->origin[1];
hordir[2] = 0;
VectorNormalize( hordir );
speed = 400;
} //end if
BotCheckBlocked( ms, hordir, qtrue, &result );
//elemantary action move in direction
EA_Move( ms->client, hordir, speed );
VectorCopy( hordir, result.movedir );
//
return result;
} //end of the function BotFinishTravel_JumpPad
//===========================================================================
// time before the reachability times out
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotReachabilityTime( aas_reachability_t *reach ) {
switch ( reach->traveltype )
{
case TRAVEL_WALK: return 5;
case TRAVEL_CROUCH: return 5;
case TRAVEL_BARRIERJUMP: return 5;
case TRAVEL_LADDER: return 6;
case TRAVEL_WALKOFFLEDGE: return 5;
case TRAVEL_JUMP: return 5;
case TRAVEL_SWIM: return 5;
case TRAVEL_WATERJUMP: return 5;
case TRAVEL_TELEPORT: return 5;
case TRAVEL_ELEVATOR: return 10;
case TRAVEL_GRAPPLEHOOK: return 8;
case TRAVEL_ROCKETJUMP: return 6;
//case TRAVEL_BFGJUMP: return 6;
case TRAVEL_JUMPPAD: return 10;
case TRAVEL_FUNCBOB: return 10;
default:
{
botimport.Print( PRT_ERROR, "travel type %d not implemented yet\n", reach->traveltype );
return 8;
} //end case
} //end switch
} //end of the function BotReachabilityTime
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotMoveInGoalArea( bot_movestate_t *ms, bot_goal_t *goal ) {
bot_moveresult_t result;
vec3_t dir;
float dist, speed;
#ifdef DEBUG
//botimport.Print(PRT_MESSAGE, "%s: moving straight to goal\n", ClientName(ms->entitynum-1));
//AAS_ClearShownDebugLines();
//AAS_DebugLine(ms->origin, goal->origin, LINECOLOR_RED);
#endif //DEBUG
BotClearMoveResult( &result );
//walk straight to the goal origin
dir[0] = goal->origin[0] - ms->origin[0];
dir[1] = goal->origin[1] - ms->origin[1];
if ( ms->moveflags & MFL_SWIMMING ) {
dir[2] = goal->origin[2] - ms->origin[2];
result.traveltype = TRAVEL_SWIM;
} //end if
else
{
dir[2] = 0;
result.traveltype = TRAVEL_WALK;
} //endif
//
dist = VectorNormalize( dir );
if ( dist > 100 || ( goal->flags & GFL_NOSLOWAPPROACH ) ) {
dist = 100;
}
speed = 400 - ( 400 - 4 * dist );
if ( speed < 10 ) {
speed = 0;
}
//
BotCheckBlocked( ms, dir, qtrue, &result );
//elemantary action move in direction
EA_Move( ms->client, dir, speed );
VectorCopy( dir, result.movedir );
//
if ( ms->moveflags & MFL_SWIMMING ) {
Vector2Angles( dir, result.ideal_viewangles );
result.flags |= MOVERESULT_SWIMVIEW;
} //end if
//if (!debugline) debugline = botimport.DebugLineCreate();
//botimport.DebugLineShow(debugline, ms->origin, goal->origin, LINECOLOR_BLUE);
//
ms->lastreachnum = 0;
ms->lastareanum = 0;
ms->lastgoalareanum = goal->areanum;
VectorCopy( ms->origin, ms->lastorigin );
ms->lasttime = AAS_Time();
//
return result;
} //end of the function BotMoveInGoalArea
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int AAS_AreaRouteToGoalArea( int areanum, vec3_t origin, int goalareanum, int travelflags, int *traveltime, int *reachnum );
extern float VectorDistance( vec3_t v1, vec3_t v2 );
void BotMoveToGoal( bot_moveresult_t *result, int movestate, bot_goal_t *goal, int travelflags ) {
int reachnum = 0; // TTimo (might be used uninitialized in this function)
int lastreachnum, foundjumppad, ent;
aas_reachability_t reach, lastreach;
bot_movestate_t *ms;
//vec3_t mins, maxs, up = {0, 0, 1};
//bsp_trace_t trace;
//static int debugline;
//
BotClearMoveResult( result );
//
ms = BotMoveStateFromHandle( movestate );
if ( !ms ) {
return;
}
//reset the grapple before testing if the bot has a valid goal
//because the bot could loose all it's goals when stuck to a wall
BotResetGrapple( ms );
//
if ( !goal ) {
#ifdef DEBUG
botimport.Print( PRT_MESSAGE, "client %d: movetogoal -> no goal\n", ms->client );
#endif //DEBUG
result->failure = qtrue;
return;
} //end if
//botimport.Print(PRT_MESSAGE, "numavoidreach = %d\n", ms->numavoidreach);
//remove some of the move flags
ms->moveflags &= ~( MFL_SWIMMING | MFL_AGAINSTLADDER );
//set some of the move flags
//NOTE: the MFL_ONGROUND flag is also set in the higher AI
if ( AAS_OnGround( ms->origin, ms->presencetype, ms->entitynum ) ) {
ms->moveflags |= MFL_ONGROUND;
}
//
if ( ms->moveflags & MFL_ONGROUND ) {
int modeltype, modelnum;
ent = BotOnTopOfEntity( ms );
if ( ent != -1 ) {
modelnum = AAS_EntityModelindex( ent );
if ( modelnum >= 0 && modelnum < MAX_MODELS ) {
modeltype = modeltypes[modelnum];
if ( modeltype == MODELTYPE_FUNC_PLAT ) {
AAS_ReachabilityFromNum( ms->lastreachnum, &reach );
//if the bot is Not using the elevator
if ( reach.traveltype != TRAVEL_ELEVATOR ||
//NOTE: the face number is the plat model number
( reach.facenum & 0x0000FFFF ) != modelnum ) {
reachnum = AAS_NextModelReachability( 0, modelnum );
if ( reachnum ) {
//botimport.Print(PRT_MESSAGE, "client %d: accidentally ended up on func_plat\n", ms->client);
AAS_ReachabilityFromNum( reachnum, &reach );
ms->lastreachnum = reachnum;
ms->reachability_time = AAS_Time() + BotReachabilityTime( &reach );
} //end if
else
{
if ( bot_developer ) {
botimport.Print( PRT_MESSAGE, "client %d: on func_plat without reachability\n", ms->client );
} //end if
result->blocked = qtrue;
result->blockentity = ent;
result->flags |= MOVERESULT_ONTOPOFOBSTACLE;
return;
} //end else
} //end if
result->flags |= MOVERESULT_ONTOPOF_ELEVATOR;
} //end if
else if ( modeltype == MODELTYPE_FUNC_BOB ) {
AAS_ReachabilityFromNum( ms->lastreachnum, &reach );
//if the bot is Not using the func bobbing
if ( reach.traveltype != TRAVEL_FUNCBOB ||
//NOTE: the face number is the func_bobbing model number
( reach.facenum & 0x0000FFFF ) != modelnum ) {
reachnum = AAS_NextModelReachability( 0, modelnum );
if ( reachnum ) {
//botimport.Print(PRT_MESSAGE, "client %d: accidentally ended up on func_bobbing\n", ms->client);
AAS_ReachabilityFromNum( reachnum, &reach );
ms->lastreachnum = reachnum;
ms->reachability_time = AAS_Time() + BotReachabilityTime( &reach );
} //end if
else
{
if ( bot_developer ) {
botimport.Print( PRT_MESSAGE, "client %d: on func_bobbing without reachability\n", ms->client );
} //end if
result->blocked = qtrue;
result->blockentity = ent;
result->flags |= MOVERESULT_ONTOPOFOBSTACLE;
return;
} //end else
} //end if
result->flags |= MOVERESULT_ONTOPOF_FUNCBOB;
} //end if
/* Ridah, disabled this, or standing on little fragments causes problems
else
{
result->blocked = qtrue;
result->blockentity = ent;
result->flags |= MOVERESULT_ONTOPOFOBSTACLE;
return;
} //end else
*/
} //end if
} //end if
} //end if
//if swimming
if ( AAS_Swimming( ms->origin ) ) {
ms->moveflags |= MFL_SWIMMING;
}
//if against a ladder
if ( AAS_AgainstLadder( ms->origin, ms->areanum ) ) {
ms->moveflags |= MFL_AGAINSTLADDER;
}
//if the bot is on the ground, swimming or against a ladder
if ( ms->moveflags & ( MFL_ONGROUND | MFL_SWIMMING | MFL_AGAINSTLADDER ) ) {
//botimport.Print(PRT_MESSAGE, "%s: onground, swimming or against ladder\n", ClientName(ms->entitynum-1));
//
AAS_ReachabilityFromNum( ms->lastreachnum, &lastreach );
//reachability area the bot is in
//ms->areanum = BotReachabilityArea(ms->origin, (lastreach.traveltype != TRAVEL_ELEVATOR));
if ( !ms->areanum ) {
result->failure = qtrue;
return;
}
//ms->areanum = BotFuzzyPointReachabilityArea(ms->origin);
//if the bot is in the goal area
if ( ms->areanum == goal->areanum ) {
*result = BotMoveInGoalArea( ms, goal );
return;
} //end if
//assume we can use the reachability from the last frame
reachnum = ms->lastreachnum;
//if there is a last reachability
if ( reachnum ) {
AAS_ReachabilityFromNum( reachnum, &reach );
//check if the reachability is still valid
if ( !( AAS_TravelFlagForType( reach.traveltype ) & travelflags ) ) {
reachnum = 0;
} //end if
//special grapple hook case
else if ( reach.traveltype == TRAVEL_GRAPPLEHOOK ) {
if ( ms->reachability_time < AAS_Time() ||
( ms->moveflags & MFL_GRAPPLERESET ) ) {
reachnum = 0;
} //end if
} //end if
//special elevator case
else if ( reach.traveltype == TRAVEL_ELEVATOR || reach.traveltype == TRAVEL_FUNCBOB ) {
if ( ( result->flags & MOVERESULT_ONTOPOF_FUNCBOB ) ||
( result->flags & MOVERESULT_ONTOPOF_FUNCBOB ) ) {
ms->reachability_time = AAS_Time() + 5;
} //end if
//if the bot was going for an elevator and reached the reachability area
if ( ms->areanum == reach.areanum ||
ms->reachability_time < AAS_Time() ) {
reachnum = 0;
} //end if
} //end if
else
{
if ( ms->reachability_time < AAS_Time() ) {
// the reachability timed out, add it to the ignore list
#ifdef AVOIDREACH
BotAddToAvoidReach( ms, reachnum, AVOIDREACH_TIME + 4 );
#endif //AVOIDREACH
}
#ifdef DEBUG
if ( bot_developer ) {
if ( ms->reachability_time < AAS_Time() ) {
botimport.Print( PRT_MESSAGE, "client %d: reachability timeout in ", ms->client );
AAS_PrintTravelType( reach.traveltype );
botimport.Print( PRT_MESSAGE, "\n" );
} //end if
/*
if (ms->lastareanum != ms->areanum)
{
botimport.Print(PRT_MESSAGE, "changed from area %d to %d\n", ms->lastareanum, ms->areanum);
} //end if*/
} //end if
#endif //DEBUG
//if the goal area changed or the reachability timed out
//or the area changed
if ( ms->lastgoalareanum != goal->areanum ||
ms->reachability_time < AAS_Time() ||
ms->lastareanum != ms->areanum ||
//@TODO. The hardcoded distance here should actually be tied to speed. As it was, 20 was too big for
// slow moving walking Nazis.
// ((ms->lasttime > (AAS_Time()-0.5)) && (VectorDistance(ms->origin, ms->lastorigin) < 20*(AAS_Time()-ms->lasttime))))
( ( ms->lasttime > ( AAS_Time() - 0.5 ) ) && ( VectorDistance( ms->origin, ms->lastorigin ) < 5 * ( AAS_Time() - ms->lasttime ) ) ) ) {
reachnum = 0;
//botimport.Print(PRT_MESSAGE, "area change or timeout\n");
} //end else if
} //end else
} //end if
//if the bot needs a new reachability
if ( !reachnum ) {
//if the area has no reachability links
if ( !AAS_AreaReachability( ms->areanum ) ) {
#ifdef DEBUG
if ( bot_developer ) {
botimport.Print( PRT_MESSAGE, "area %d no reachability\n", ms->areanum );
} //end if
#endif //DEBUG
} //end if
//get a new reachability leading towards the goal
reachnum = BotGetReachabilityToGoal( ms->origin, ms->areanum, ms->entitynum,
ms->lastgoalareanum, ms->lastareanum,
ms->avoidreach, ms->avoidreachtimes, ms->avoidreachtries,
goal, travelflags, travelflags );
//the area number the reachability starts in
ms->reachareanum = ms->areanum;
//reset some state variables
ms->jumpreach = 0; //for TRAVEL_JUMP
ms->moveflags &= ~MFL_GRAPPLERESET; //for TRAVEL_GRAPPLEHOOK
//if there is a reachability to the goal
if ( reachnum ) {
AAS_ReachabilityFromNum( reachnum, &reach );
//set a timeout for this reachability
ms->reachability_time = AAS_Time() + (float)( 0.01 * ( AAS_AreaTravelTime( ms->areanum, ms->origin, reach.start ) * 2 ) + BotReachabilityTime( &reach ) + 100 );
if ( reach.traveltype == TRAVEL_LADDER ) {
ms->reachability_time += 4.0; // allow more time to navigate ladders
}
//
#ifdef AVOIDREACH
if ( reach.traveltype != TRAVEL_LADDER ) { // don't avoid ladders unless we were unable to reach them in time
BotAddToAvoidReach( ms, reachnum, 3 ); // add a short avoid reach time
}
#endif //AVOIDREACH
} //end if
#ifdef DEBUG
else if ( bot_developer ) {
botimport.Print( PRT_MESSAGE, "goal not reachable\n" );
memset( &reach, 0, sizeof( aas_reachability_t ) ); //make compiler happy
} //end else
if ( bot_developer ) {
//if still going for the same goal
if ( ms->lastgoalareanum == goal->areanum ) {
if ( ms->lastareanum == reach.areanum ) {
botimport.Print( PRT_MESSAGE, "same goal, going back to previous area\n" );
} //end if
} //end if
} //end if
#endif //DEBUG
} //end else
//
ms->lastreachnum = reachnum;
ms->lastgoalareanum = goal->areanum;
ms->lastareanum = ms->areanum;
//if the bot has a reachability
if ( reachnum ) {
//get the reachability from the number
AAS_ReachabilityFromNum( reachnum, &reach );
result->traveltype = reach.traveltype;
//
if ( goal->flags & GFL_DEBUGPATH ) {
AAS_ClearShownPolygons();
AAS_ClearShownDebugLines();
AAS_PrintTravelType( reach.traveltype );
// src area
AAS_ShowAreaPolygons( ms->areanum, 1, qtrue );
// dest area
AAS_ShowAreaPolygons( goal->areanum, 3, qtrue );
// reachability
AAS_ShowReachability( &reach );
AAS_ShowAreaPolygons( reach.areanum, 2, qtrue );
}
//
#ifdef DEBUG
//botimport.Print(PRT_MESSAGE, "client %d: ", ms->client);
//AAS_PrintTravelType(reach.traveltype);
//botimport.Print(PRT_MESSAGE, "\n");
#endif //DEBUG
switch ( reach.traveltype )
{
case TRAVEL_WALK: *result = BotTravel_Walk( ms, &reach ); break;
case TRAVEL_CROUCH: *result = BotTravel_Crouch( ms, &reach ); break;
case TRAVEL_BARRIERJUMP: *result = BotTravel_BarrierJump( ms, &reach ); break;
case TRAVEL_LADDER: *result = BotTravel_Ladder( ms, &reach ); break;
case TRAVEL_WALKOFFLEDGE: *result = BotTravel_WalkOffLedge( ms, &reach ); break;
case TRAVEL_JUMP: *result = BotTravel_Jump( ms, &reach ); break;
case TRAVEL_SWIM: *result = BotTravel_Swim( ms, &reach ); break;
case TRAVEL_WATERJUMP: *result = BotTravel_WaterJump( ms, &reach ); break;
case TRAVEL_TELEPORT: *result = BotTravel_Teleport( ms, &reach ); break;
case TRAVEL_ELEVATOR: *result = BotTravel_Elevator( ms, &reach ); break;
case TRAVEL_GRAPPLEHOOK: *result = BotTravel_Grapple( ms, &reach ); break;
case TRAVEL_ROCKETJUMP: *result = BotTravel_RocketJump( ms, &reach ); break;
//case TRAVEL_BFGJUMP:
case TRAVEL_JUMPPAD: *result = BotTravel_JumpPad( ms, &reach ); break;
case TRAVEL_FUNCBOB: *result = BotTravel_FuncBobbing( ms, &reach ); break;
default:
{
botimport.Print( PRT_FATAL, "travel type %d not implemented yet\n", reach.traveltype );
break;
} //end case
} //end switch
} //end if
else
{
result->failure = qtrue;
memset( &reach, 0, sizeof( aas_reachability_t ) );
} //end else
#ifdef DEBUG
if ( bot_developer ) {
if ( result->failure ) {
botimport.Print( PRT_MESSAGE, "client %d: movement failure in ", ms->client );
AAS_PrintTravelType( reach.traveltype );
botimport.Print( PRT_MESSAGE, "\n" );
} //end if
} //end if
#endif //DEBUG
} //end if
else
{
int i, numareas, areas[16];
vec3_t end;
//special handling of jump pads when the bot uses a jump pad without knowing it
foundjumppad = qfalse;
VectorMA( ms->origin, -2 * ms->thinktime, ms->velocity, end );
numareas = AAS_TraceAreas( ms->origin, end, areas, NULL, 16 );
for ( i = numareas - 1; i >= 0; i-- )
{
if ( AAS_AreaJumpPad( areas[i] ) ) {
//botimport.Print(PRT_MESSAGE, "client %d used a jumppad without knowing, area %d\n", ms->client, areas[i]);
foundjumppad = qtrue;
lastreachnum = BotGetReachabilityToGoal( end, areas[i], ms->entitynum,
ms->lastgoalareanum, ms->lastareanum,
ms->avoidreach, ms->avoidreachtimes, ms->avoidreachtries,
goal, travelflags, TFL_JUMPPAD );
if ( lastreachnum ) {
ms->lastreachnum = lastreachnum;
ms->lastareanum = areas[i];
//botimport.Print(PRT_MESSAGE, "found jumppad reachability\n");
break;
} //end if
else
{
for ( lastreachnum = AAS_NextAreaReachability( areas[i], 0 ); lastreachnum;
lastreachnum = AAS_NextAreaReachability( areas[i], lastreachnum ) )
{
//get the reachability from the number
AAS_ReachabilityFromNum( lastreachnum, &reach );
if ( reach.traveltype == TRAVEL_JUMPPAD ) {
ms->lastreachnum = lastreachnum;
ms->lastareanum = areas[i];
//botimport.Print(PRT_MESSAGE, "found jumppad reachability hard!!\n");
break;
} //end if
} //end for
if ( lastreachnum ) {
break;
}
} //end else
} //end if
} //end for
if ( bot_developer ) {
//if a jumppad is found with the trace but no reachability is found
if ( foundjumppad && !ms->lastreachnum ) {
botimport.Print( PRT_MESSAGE, "client %d didn't find jumppad reachability\n", ms->client );
} //end if
} //end if
//
if ( ms->lastreachnum ) {
//botimport.Print(PRT_MESSAGE, "%s: NOT onground, swimming or against ladder\n", ClientName(ms->entitynum-1));
AAS_ReachabilityFromNum( ms->lastreachnum, &reach );
result->traveltype = reach.traveltype;
#ifdef DEBUG
//botimport.Print(PRT_MESSAGE, "client %d finish: ", ms->client);
//AAS_PrintTravelType(reach.traveltype);
//botimport.Print(PRT_MESSAGE, "\n");
#endif //DEBUG
//
switch ( reach.traveltype )
{
case TRAVEL_WALK: *result = BotTravel_Walk( ms, &reach ); break; //BotFinishTravel_Walk(ms, &reach); break;
case TRAVEL_CROUCH: /*do nothing*/ break;
case TRAVEL_BARRIERJUMP: *result = BotFinishTravel_BarrierJump( ms, &reach ); break;
case TRAVEL_LADDER: *result = BotTravel_Ladder( ms, &reach ); break;
case TRAVEL_WALKOFFLEDGE: *result = BotFinishTravel_WalkOffLedge( ms, &reach ); break;
case TRAVEL_JUMP: *result = BotFinishTravel_Jump( ms, &reach ); break;
case TRAVEL_SWIM: *result = BotTravel_Swim( ms, &reach ); break;
case TRAVEL_WATERJUMP: *result = BotFinishTravel_WaterJump( ms, &reach ); break;
case TRAVEL_TELEPORT: /*do nothing*/ break;
case TRAVEL_ELEVATOR: *result = BotFinishTravel_Elevator( ms, &reach ); break;
case TRAVEL_GRAPPLEHOOK: *result = BotTravel_Grapple( ms, &reach ); break;
case TRAVEL_ROCKETJUMP: *result = BotFinishTravel_WeaponJump( ms, &reach ); break;
//case TRAVEL_BFGJUMP:
case TRAVEL_JUMPPAD: *result = BotFinishTravel_JumpPad( ms, &reach ); break;
case TRAVEL_FUNCBOB: *result = BotFinishTravel_FuncBobbing( ms, &reach ); break;
default:
{
botimport.Print( PRT_FATAL, "(last) travel type %d not implemented yet\n", reach.traveltype );
break;
} //end case
} //end switch
#ifdef DEBUG
if ( bot_developer ) {
if ( result->failure ) {
botimport.Print( PRT_MESSAGE, "client %d: movement failure in finish ", ms->client );
AAS_PrintTravelType( reach.traveltype );
botimport.Print( PRT_MESSAGE, "\n" );
} //end if
} //end if
#endif //DEBUG
} //end if
} //end else
//FIXME: is it right to do this here?
if ( result->blocked ) {
ms->reachability_time -= 10 * ms->thinktime;
}
//copy the last origin
VectorCopy( ms->origin, ms->lastorigin );
ms->lasttime = AAS_Time();
/*
// RF, try to look in the direction we will be moving ahead of time
if (reachnum > 0 && !(result->flags & (MOVERESULT_MOVEMENTVIEW|MOVERESULT_SWIMVIEW))) {
vec3_t dir;
int ftraveltime, freachnum;
AAS_ReachabilityFromNum( reachnum, &reach);
if (reach.areanum != goal->areanum) {
if (AAS_AreaRouteToGoalArea( reach.areanum, reach.end, goal->areanum, travelflags, &ftraveltime, &freachnum )) {
AAS_ReachabilityFromNum( freachnum, &reach);
VectorSubtract( reach.end, ms->origin, dir );
VectorNormalize( dir );
vectoangles( dir, result->ideal_viewangles );
result->flags |= MOVERESULT_FUTUREVIEW;
}
} else {
VectorSubtract( goal->origin, ms->origin, dir );
VectorNormalize( dir );
vectoangles( dir, result->ideal_viewangles );
result->flags |= MOVERESULT_FUTUREVIEW;
}
}
*/
//return the movement result
return;
} //end of the function BotMoveToGoal
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void BotResetAvoidReach( int movestate ) {
bot_movestate_t *ms;
ms = BotMoveStateFromHandle( movestate );
if ( !ms ) {
return;
}
memset( ms->avoidreach, 0, MAX_AVOIDREACH * sizeof( int ) );
memset( ms->avoidreachtimes, 0, MAX_AVOIDREACH * sizeof( float ) );
memset( ms->avoidreachtries, 0, MAX_AVOIDREACH * sizeof( int ) );
// RF, also clear movestate stuff
ms->lastareanum = 0;
ms->lastgoalareanum = 0;
ms->lastreachnum = 0;
} //end of the function BotResetAvoidReach
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void BotResetLastAvoidReach( int movestate ) {
int i, latest;
float latesttime;
bot_movestate_t *ms;
ms = BotMoveStateFromHandle( movestate );
if ( !ms ) {
return;
}
latesttime = 0;
latest = 0;
for ( i = 0; i < MAX_AVOIDREACH; i++ )
{
if ( ms->avoidreachtimes[i] > latesttime ) {
latesttime = ms->avoidreachtimes[i];
latest = i;
} //end if
} //end for
if ( latesttime ) {
ms->avoidreachtimes[latest] = 0;
if ( ms->avoidreachtries[i] > 0 ) {
ms->avoidreachtries[latest]--;
}
} //end if
} //end of the function BotResetLastAvoidReach
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void BotResetMoveState( int movestate ) {
bot_movestate_t *ms;
ms = BotMoveStateFromHandle( movestate );
if ( !ms ) {
return;
}
memset( ms, 0, sizeof( bot_movestate_t ) );
} //end of the function BotResetMoveState
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotSetupMoveAI( void ) {
BotSetBrushModelTypes();
sv_maxstep = LibVarValue( "sv_step", "18" );
sv_maxbarrier = LibVarValue( "sv_maxbarrier", "32" );
sv_gravity = LibVarValue( "sv_gravity", "800" );
return BLERR_NOERROR;
} //end of the function BotSetupMoveAI
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void BotShutdownMoveAI( void ) {
int i;
for ( i = 1; i <= MAX_CLIENTS; i++ )
{
if ( botmovestates[i] ) {
FreeMemory( botmovestates[i] );
botmovestates[i] = NULL;
} //end if
} //end for
} //end of the function BotShutdownMoveAI
| 412 | 0.913911 | 1 | 0.913911 | game-dev | MEDIA | 0.981999 | game-dev | 0.951015 | 1 | 0.951015 |
VGVentures/digital_escape_room | 2,436 | lib/player_selection/views/player_selection_page.dart | import 'package:digital_escape_room/game/game.dart';
import 'package:digital_escape_room/l10n/l10n.dart';
import 'package:digital_escape_room/player_creation_form/player_creation_form.dart';
import 'package:digital_escape_room/player_selection/player_selection.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:game_repository/game_repository.dart';
import 'package:nes_ui/nes_ui.dart';
import 'package:statistics_repository/statistics_repository.dart';
class PlayerSelectionPage extends StatelessWidget {
const PlayerSelectionPage({super.key});
static Route<void> route() {
return NesFillTransition.route<void>(
pageBuilder: (_, __, ___) {
return const PlayerSelectionPage();
},
);
}
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => PlayerSelectionBloc(
context.read<GameRepository>(),
context.read<StatisticsRepository>(),
),
child: _PlayerSelectionView(),
);
}
}
class _PlayerSelectionView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: BlocConsumer<PlayerSelectionBloc, PlayerSelectionState>(
listener: (context, state) {
if (state is LoadGameSuccess) {
Navigator.of(context)
.push(EscapeRoomPage.route(state.challenges));
}
},
builder: (context, state) {
return switch (state) {
PlayerSelectionInitial() => const PlayerCreationForm(),
LoadGameSuccess() => _LoadingGame(),
LoadGameFailure() => const PlayerCreationForm(),
LoadGameInProgress() => _LoadingGame(),
};
},
),
),
);
}
}
class _LoadingGame extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(14),
child: NesContainer(
height: 200,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const NesHourglassLoadingIndicator(),
const SizedBox(height: 25),
Text(
context.l10n.createCustomGame,
style: Theme.of(context).textTheme.titleSmall,
),
],
),
),
);
}
}
| 412 | 0.789998 | 1 | 0.789998 | game-dev | MEDIA | 0.82081 | game-dev | 0.88379 | 1 | 0.88379 |
mgfjx/JAVBus | 13,448 | Pods/Headers/Public/ObjectiveDropboxOfficial/DBTEAMLOGEventCategory.h | ///
/// Copyright (c) 2016 Dropbox, Inc. All rights reserved.
///
/// Auto-generated by Stone, do not modify.
///
#import <Foundation/Foundation.h>
#import "DBSerializableProtocol.h"
@class DBTEAMLOGEventCategory;
NS_ASSUME_NONNULL_BEGIN
#pragma mark - API Object
///
/// The `EventCategory` union.
///
/// Category of events in event audit log.
///
/// This class implements the `DBSerializable` protocol (serialize and
/// deserialize instance methods), which is required for all Obj-C SDK API route
/// objects.
///
@interface DBTEAMLOGEventCategory : NSObject <DBSerializable, NSCopying>
#pragma mark - Instance fields
/// The `DBTEAMLOGEventCategoryTag` enum type represents the possible tag states
/// with which the `DBTEAMLOGEventCategory` union can exist.
typedef NS_ENUM(NSInteger, DBTEAMLOGEventCategoryTag) {
/// Events that apply to management of linked apps.
DBTEAMLOGEventCategoryApps,
/// Events that have to do with comments on files and Paper documents.
DBTEAMLOGEventCategoryComments,
/// Events that apply to linked devices on mobile, desktop and Web
/// platforms.
DBTEAMLOGEventCategoryDevices,
/// Events that involve domain management feature: domain verification,
/// invite enforcement and account capture.
DBTEAMLOGEventCategoryDomains,
/// Events that have to do with filesystem operations on files and folders:
/// copy, move, delete, etc.
DBTEAMLOGEventCategoryFileOperations,
/// Events that apply to the file requests feature.
DBTEAMLOGEventCategoryFileRequests,
/// Events that involve group management.
DBTEAMLOGEventCategoryGroups,
/// Events that involve users signing in to or out of Dropbox.
DBTEAMLOGEventCategoryLogins,
/// Events that involve team member management.
DBTEAMLOGEventCategoryMembers,
/// Events that apply to Dropbox Paper.
DBTEAMLOGEventCategoryPaper,
/// Events that involve using, changing or resetting passwords.
DBTEAMLOGEventCategoryPasswords,
/// Events that concern generation of admin reports, including team activity
/// and device usage.
DBTEAMLOGEventCategoryReports,
/// Events that apply to all types of sharing and collaboration.
DBTEAMLOGEventCategorySharing,
/// Events that apply to Dropbox Showcase.
DBTEAMLOGEventCategoryShowcase,
/// Events that involve using or configuring single sign-on as well as
/// administrative policies concerning single sign-on.
DBTEAMLOGEventCategorySso,
/// Events that involve team folder management.
DBTEAMLOGEventCategoryTeamFolders,
/// Events that involve a change in team-wide policies.
DBTEAMLOGEventCategoryTeamPolicies,
/// Events that involve a change in the team profile.
DBTEAMLOGEventCategoryTeamProfile,
/// Events that involve using or configuring two factor authentication as
/// well as administrative policies concerning two factor authentication.
DBTEAMLOGEventCategoryTfa,
/// Events that apply to cross-team trust establishment.
DBTEAMLOGEventCategoryTrustedTeams,
/// (no description).
DBTEAMLOGEventCategoryOther,
};
/// Represents the union's current tag state.
@property (nonatomic, readonly) DBTEAMLOGEventCategoryTag tag;
#pragma mark - Constructors
///
/// Initializes union class with tag state of "apps".
///
/// Description of the "apps" tag state: Events that apply to management of
/// linked apps.
///
/// @return An initialized instance.
///
- (instancetype)initWithApps;
///
/// Initializes union class with tag state of "comments".
///
/// Description of the "comments" tag state: Events that have to do with
/// comments on files and Paper documents.
///
/// @return An initialized instance.
///
- (instancetype)initWithComments;
///
/// Initializes union class with tag state of "devices".
///
/// Description of the "devices" tag state: Events that apply to linked devices
/// on mobile, desktop and Web platforms.
///
/// @return An initialized instance.
///
- (instancetype)initWithDevices;
///
/// Initializes union class with tag state of "domains".
///
/// Description of the "domains" tag state: Events that involve domain
/// management feature: domain verification, invite enforcement and account
/// capture.
///
/// @return An initialized instance.
///
- (instancetype)initWithDomains;
///
/// Initializes union class with tag state of "file_operations".
///
/// Description of the "file_operations" tag state: Events that have to do with
/// filesystem operations on files and folders: copy, move, delete, etc.
///
/// @return An initialized instance.
///
- (instancetype)initWithFileOperations;
///
/// Initializes union class with tag state of "file_requests".
///
/// Description of the "file_requests" tag state: Events that apply to the file
/// requests feature.
///
/// @return An initialized instance.
///
- (instancetype)initWithFileRequests;
///
/// Initializes union class with tag state of "groups".
///
/// Description of the "groups" tag state: Events that involve group management.
///
/// @return An initialized instance.
///
- (instancetype)initWithGroups;
///
/// Initializes union class with tag state of "logins".
///
/// Description of the "logins" tag state: Events that involve users signing in
/// to or out of Dropbox.
///
/// @return An initialized instance.
///
- (instancetype)initWithLogins;
///
/// Initializes union class with tag state of "members".
///
/// Description of the "members" tag state: Events that involve team member
/// management.
///
/// @return An initialized instance.
///
- (instancetype)initWithMembers;
///
/// Initializes union class with tag state of "paper".
///
/// Description of the "paper" tag state: Events that apply to Dropbox Paper.
///
/// @return An initialized instance.
///
- (instancetype)initWithPaper;
///
/// Initializes union class with tag state of "passwords".
///
/// Description of the "passwords" tag state: Events that involve using,
/// changing or resetting passwords.
///
/// @return An initialized instance.
///
- (instancetype)initWithPasswords;
///
/// Initializes union class with tag state of "reports".
///
/// Description of the "reports" tag state: Events that concern generation of
/// admin reports, including team activity and device usage.
///
/// @return An initialized instance.
///
- (instancetype)initWithReports;
///
/// Initializes union class with tag state of "sharing".
///
/// Description of the "sharing" tag state: Events that apply to all types of
/// sharing and collaboration.
///
/// @return An initialized instance.
///
- (instancetype)initWithSharing;
///
/// Initializes union class with tag state of "showcase".
///
/// Description of the "showcase" tag state: Events that apply to Dropbox
/// Showcase.
///
/// @return An initialized instance.
///
- (instancetype)initWithShowcase;
///
/// Initializes union class with tag state of "sso".
///
/// Description of the "sso" tag state: Events that involve using or configuring
/// single sign-on as well as administrative policies concerning single sign-on.
///
/// @return An initialized instance.
///
- (instancetype)initWithSso;
///
/// Initializes union class with tag state of "team_folders".
///
/// Description of the "team_folders" tag state: Events that involve team folder
/// management.
///
/// @return An initialized instance.
///
- (instancetype)initWithTeamFolders;
///
/// Initializes union class with tag state of "team_policies".
///
/// Description of the "team_policies" tag state: Events that involve a change
/// in team-wide policies.
///
/// @return An initialized instance.
///
- (instancetype)initWithTeamPolicies;
///
/// Initializes union class with tag state of "team_profile".
///
/// Description of the "team_profile" tag state: Events that involve a change in
/// the team profile.
///
/// @return An initialized instance.
///
- (instancetype)initWithTeamProfile;
///
/// Initializes union class with tag state of "tfa".
///
/// Description of the "tfa" tag state: Events that involve using or configuring
/// two factor authentication as well as administrative policies concerning two
/// factor authentication.
///
/// @return An initialized instance.
///
- (instancetype)initWithTfa;
///
/// Initializes union class with tag state of "trusted_teams".
///
/// Description of the "trusted_teams" tag state: Events that apply to
/// cross-team trust establishment.
///
/// @return An initialized instance.
///
- (instancetype)initWithTrustedTeams;
///
/// Initializes union class with tag state of "other".
///
/// @return An initialized instance.
///
- (instancetype)initWithOther;
- (instancetype)init NS_UNAVAILABLE;
#pragma mark - Tag state methods
///
/// Retrieves whether the union's current tag state has value "apps".
///
/// @return Whether the union's current tag state has value "apps".
///
- (BOOL)isApps;
///
/// Retrieves whether the union's current tag state has value "comments".
///
/// @return Whether the union's current tag state has value "comments".
///
- (BOOL)isComments;
///
/// Retrieves whether the union's current tag state has value "devices".
///
/// @return Whether the union's current tag state has value "devices".
///
- (BOOL)isDevices;
///
/// Retrieves whether the union's current tag state has value "domains".
///
/// @return Whether the union's current tag state has value "domains".
///
- (BOOL)isDomains;
///
/// Retrieves whether the union's current tag state has value "file_operations".
///
/// @return Whether the union's current tag state has value "file_operations".
///
- (BOOL)isFileOperations;
///
/// Retrieves whether the union's current tag state has value "file_requests".
///
/// @return Whether the union's current tag state has value "file_requests".
///
- (BOOL)isFileRequests;
///
/// Retrieves whether the union's current tag state has value "groups".
///
/// @return Whether the union's current tag state has value "groups".
///
- (BOOL)isGroups;
///
/// Retrieves whether the union's current tag state has value "logins".
///
/// @return Whether the union's current tag state has value "logins".
///
- (BOOL)isLogins;
///
/// Retrieves whether the union's current tag state has value "members".
///
/// @return Whether the union's current tag state has value "members".
///
- (BOOL)isMembers;
///
/// Retrieves whether the union's current tag state has value "paper".
///
/// @return Whether the union's current tag state has value "paper".
///
- (BOOL)isPaper;
///
/// Retrieves whether the union's current tag state has value "passwords".
///
/// @return Whether the union's current tag state has value "passwords".
///
- (BOOL)isPasswords;
///
/// Retrieves whether the union's current tag state has value "reports".
///
/// @return Whether the union's current tag state has value "reports".
///
- (BOOL)isReports;
///
/// Retrieves whether the union's current tag state has value "sharing".
///
/// @return Whether the union's current tag state has value "sharing".
///
- (BOOL)isSharing;
///
/// Retrieves whether the union's current tag state has value "showcase".
///
/// @return Whether the union's current tag state has value "showcase".
///
- (BOOL)isShowcase;
///
/// Retrieves whether the union's current tag state has value "sso".
///
/// @return Whether the union's current tag state has value "sso".
///
- (BOOL)isSso;
///
/// Retrieves whether the union's current tag state has value "team_folders".
///
/// @return Whether the union's current tag state has value "team_folders".
///
- (BOOL)isTeamFolders;
///
/// Retrieves whether the union's current tag state has value "team_policies".
///
/// @return Whether the union's current tag state has value "team_policies".
///
- (BOOL)isTeamPolicies;
///
/// Retrieves whether the union's current tag state has value "team_profile".
///
/// @return Whether the union's current tag state has value "team_profile".
///
- (BOOL)isTeamProfile;
///
/// Retrieves whether the union's current tag state has value "tfa".
///
/// @return Whether the union's current tag state has value "tfa".
///
- (BOOL)isTfa;
///
/// Retrieves whether the union's current tag state has value "trusted_teams".
///
/// @return Whether the union's current tag state has value "trusted_teams".
///
- (BOOL)isTrustedTeams;
///
/// Retrieves whether the union's current tag state has value "other".
///
/// @return Whether the union's current tag state has value "other".
///
- (BOOL)isOther;
///
/// Retrieves string value of union's current tag state.
///
/// @return A human-readable string representing the union's current tag state.
///
- (NSString *)tagName;
@end
#pragma mark - Serializer Object
///
/// The serialization class for the `DBTEAMLOGEventCategory` union.
///
@interface DBTEAMLOGEventCategorySerializer : NSObject
///
/// Serializes `DBTEAMLOGEventCategory` instances.
///
/// @param instance An instance of the `DBTEAMLOGEventCategory` API object.
///
/// @return A json-compatible dictionary representation of the
/// `DBTEAMLOGEventCategory` API object.
///
+ (nullable NSDictionary<NSString *, id> *)serialize:(DBTEAMLOGEventCategory *)instance;
///
/// Deserializes `DBTEAMLOGEventCategory` instances.
///
/// @param dict A json-compatible dictionary representation of the
/// `DBTEAMLOGEventCategory` API object.
///
/// @return An instantiation of the `DBTEAMLOGEventCategory` object.
///
+ (DBTEAMLOGEventCategory *)deserialize:(NSDictionary<NSString *, id> *)dict;
@end
NS_ASSUME_NONNULL_END
| 412 | 0.642757 | 1 | 0.642757 | game-dev | MEDIA | 0.327468 | game-dev | 0.664499 | 1 | 0.664499 |
Statsify/statsify | 3,509 | apps/discord-bot/src/commands/warlords/warlords.profile.tsx | /**
* Copyright (c) Statsify
*
* This source code is licensed under the GNU GPL v3 license found in the
* LICENSE file in the root directory of this source tree.
* https://github.com/Statsify/statsify/blob/main/LICENSE
*/
import { Container, Footer, Header, type SidebarItem, formatProgression } from "#components";
import { FormattedGame, type GameMode, WarlordsMage, WarlordsModes, WarlordsPaladin, WarlordsShaman, WarlordsWarrior } from "@statsify/schemas";
import { WarlordsCaptureTheFlagTable, WarlordsClassTable, WarlordsDeathmatchTable, WarlordsDominationTable, WarlordsOverallTable } from "./tables/index.js";
import { prettify } from "@statsify/util";
import type { BaseProfileProps } from "#commands/base.hypixel-command";
export interface WarlordsProfileProps extends BaseProfileProps {
mode: GameMode<WarlordsModes>;
}
export const WarlordsProfile = ({
player,
background,
logo,
skin,
t,
badge,
user,
mode,
time,
}: WarlordsProfileProps) => {
const { warlords } = player.stats;
const sidebar: SidebarItem[] = [
[t("stats.coins"), t(warlords.coins), "§6"],
];
if (mode.api !== "overall" && mode.api !== "captureTheFlag" && mode.api !== "domination" && mode.api !== "teamDeathmatch") {
sidebar.push(
[t("stats.spec"), prettify(warlords[mode.api].specification), "§a"],
[t("stats.level"), t(warlords[mode.api].level), "§a"]
);
} else {
sidebar.push([t("stats.class"), prettify(warlords.class), "§e"]);
const clazz = warlords.class as "mage" | "warrior" | "paladin" | "shaman";
// Verify that the cast is correct and the class is a valid class
if (clazz in warlords && typeof warlords[clazz] === "object") sidebar.push([t("stats.spec"), prettify(warlords[clazz].specification), "§a"]);
}
let table: JSX.Element;
switch (mode.api) {
case "overall":
table = <WarlordsOverallTable warlords={warlords} t={t} />;
break;
case "captureTheFlag":
table = <WarlordsCaptureTheFlagTable warlords={warlords} t={t} />;
break;
case "domination":
table = <WarlordsDominationTable warlords={warlords} t={t} />;
break;
case "teamDeathmatch":
table = <WarlordsDeathmatchTable warlords={warlords} t={t} />;
break;
case "mage":
table = <WarlordsClassTable stats={warlords.mage} constructor={WarlordsMage} color="§b" t={t} />;
break;
case "warrior":
table = <WarlordsClassTable stats={warlords.warrior} constructor={WarlordsWarrior} color="§7" t={t} />;
break;
case "paladin":
table = <WarlordsClassTable stats={warlords.paladin} constructor={WarlordsPaladin} color="§e" t={t} />;
break;
case "shaman":
table = <WarlordsClassTable stats={warlords.shaman} constructor={WarlordsShaman} color="§2" t={t} />;
break;
}
return (
<Container background={background}>
<Header
skin={skin}
name={player.prefixName}
badge={badge}
sidebar={sidebar}
title={`§l${FormattedGame.WARLORDS} §fStats §r(${mode.formatted})`}
description={`§7${t("stats.title")}: ${
warlords.titleFormatted
}\n${formatProgression({
t,
label: t("stats.progression.win"),
progression: warlords.progression,
currentLevel: warlords.titleFormatted,
nextLevel: warlords.nextTitleFormatted,
})}`}
time={time}
/>
{table}
<Footer logo={logo} user={user} />
</Container>
);
};
| 412 | 0.658505 | 1 | 0.658505 | game-dev | MEDIA | 0.923879 | game-dev | 0.915857 | 1 | 0.915857 |
project-topaz/topaz | 2,427 | scripts/zones/Aht_Urhgan_Whitegate/npcs/Famad.lua | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Famad
-- Type: Assault Mission Giver
-- !pos 134.098 0.161 -43.759 50
-----------------------------------
local ID = require("scripts/zones/Aht_Urhgan_Whitegate/IDs")
require("scripts/globals/besieged")
require("scripts/globals/keyitems")
require("scripts/globals/missions")
require("scripts/globals/npc_util")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
local rank = tpz.besieged.getMercenaryRank(player)
local haveimperialIDtag
local assaultPoints = player:getAssaultPoint(LEBROS_ASSAULT_POINT)
if (player:hasKeyItem(tpz.ki.IMPERIAL_ARMY_ID_TAG)) then
haveimperialIDtag = 1
else
haveimperialIDtag = 0
end
--[[ if (rank > 0) then
player:startEvent(275, rank, haveimperialIDtag, assaultPoints, player:getCurrentAssault())
else]]
player:startEvent(281) -- no rank
--end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if (csid == 275) then
local selectiontype = bit.band(option, 0xF)
if (selectiontype == 1) then
-- taken assault mission
player:addAssault(bit.rshift(option, 4))
player:delKeyItem(tpz.ki.IMPERIAL_ARMY_ID_TAG)
npcUtil.giveKeyItem(player, tpz.ki.LEBROS_ASSAULT_ORDERS)
elseif (selectiontype == 2) then
-- purchased an item
local item = bit.rshift(option, 14)
local items =
{
[1] = {itemid = 15972, price = 3000},
[2] = {itemid = 15777, price = 5000},
[3] = {itemid = 15523, price = 8000},
[4] = {itemid = 15886, price = 10000},
[5] = {itemid = 15492, price = 10000},
[6] = {itemid = 18583, price = 15000},
[7] = {itemid = 18383, price = 15000},
[8] = {itemid = 18417, price = 15000},
[9] = {itemid = 14525, price = 20000},
[10] = {itemid = 14940, price = 20000},
[11] = {itemid = 15690, price = 20000},
}
local choice = items[item]
if choice and npcUtil.giveItem(player, choice.itemid) then
player:delCurrency("LEBROS_ASSAULT_POINT", choice.price)
end
end
end
end
| 412 | 0.878648 | 1 | 0.878648 | game-dev | MEDIA | 0.987722 | game-dev | 0.946817 | 1 | 0.946817 |
ProjectIgnis/CardScripts | 3,013 | rush/c160212018.lua | --メタリオン・メデゥースター
--Metarion Medustar
--Scripted by YoshiDuels
local s,id=GetID()
function s.initial_effect(c)
--fusion material
c:EnableReviveLimit()
Fusion.AddProcMix(c,true,true,CARD_IMAGINARY_ACTOR,160212027)
--Prevent the activation of a face-down Spell/Trap your opponent controls
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1,0,EFFECT_COUNT_CODE_SINGLE)
e1:SetCost(s.cost)
e1:SetTarget(s.distg)
e1:SetOperation(s.disop)
c:RegisterEffect(e1)
--Destroy 1 face-up Fiend
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,1))
e2:SetCategory(CATEGORY_DESTROY)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1,0,EFFECT_COUNT_CODE_SINGLE)
e2:SetCost(s.cost)
e2:SetTarget(s.destg)
e2:SetOperation(s.desop)
c:RegisterEffect(e2)
end
function s.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetFieldGroupCount(tp,LOCATION_MZONE,0)==1
end
function s.cfilter(c)
return c:IsMonster() and c:IsAbleToDeckOrExtraAsCost()
end
function s.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(s.cfilter,tp,LOCATION_GRAVE,0,1,nil) end
end
function s.disfilter(c)
return c:IsFacedown() and c:IsSpellTrap()
end
function s.distg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(s.disfilter,tp,0,LOCATION_ONFIELD,1,nil) end
end
function s.disop(e,tp,eg,ep,ev,re,r,rp)
--Requirement
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g=Duel.SelectMatchingCard(tp,s.cfilter,tp,LOCATION_GRAVE,0,1,1,nil)
Duel.HintSelection(g)
if Duel.SendtoDeck(g,nil,SEQ_DECKBOTTOM,REASON_COST)<1 then return end
--Effect
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_APPLYTO)
local tc=Duel.SelectMatchingCard(tp,s.disfilter,tp,0,LOCATION_ONFIELD,1,1,nil):GetFirst()
if tc then
Duel.HintSelection(tc,true)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CANNOT_TRIGGER)
e1:SetReset(RESETS_STANDARD_PHASE_END,2)
e1:SetValue(1)
tc:RegisterEffect(e1)
end
end
function s.desfilter(c)
return c:IsMonster() and c:IsFaceup() and c:IsRace(RACE_FIEND) and not c:IsMaximumModeSide()
end
function s.destg(e,tp,eg,ep,ev,re,r,rp,chk)
local dg=Duel.GetMatchingGroup(s.desfilter,tp,0,LOCATION_MZONE,nil)
if chk==0 then return #dg>0 end
Duel.SetOperationInfo(0,CATEGORY_DESTROY,dg,1,0,0)
end
function s.desop(e,tp,eg,ep,ev,re,r,rp)
--Requirement
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g=Duel.SelectMatchingCard(tp,s.cfilter,tp,LOCATION_GRAVE,0,1,1,nil)
Duel.HintSelection(g)
if Duel.SendtoDeck(g,nil,SEQ_DECKBOTTOM,REASON_COST)<1 then return end
--Effect
local dg=Duel.GetMatchingGroup(s.desfilter,tp,0,LOCATION_MZONE,nil)
if #dg>0 then
local sg=dg:Select(tp,1,1,nil)
if sg:GetFirst():IsMaximumMode() then
sg=sg:AddMaximumCheck()
Duel.HintSelection(sg)
Duel.Destroy(dg,REASON_EFFECT)
else
Duel.Destroy(sg,REASON_EFFECT)
end
end
end | 412 | 0.836215 | 1 | 0.836215 | game-dev | MEDIA | 0.973907 | game-dev | 0.969066 | 1 | 0.969066 |
oVirt/ovirt-engine | 1,533 | frontend/webadmin/modules/gwt-common/src/main/java/org/ovirt/engine/ui/common/uicommon/TimerImpl.java | package org.ovirt.engine.ui.common.uicommon;
import java.util.logging.Logger;
import org.ovirt.engine.ui.uicommonweb.ITimer;
import org.ovirt.engine.ui.uicommonweb.ProvideTickEvent;
import org.ovirt.engine.ui.uicompat.Event;
import org.ovirt.engine.ui.uicompat.EventArgs;
import com.google.gwt.user.client.Timer;
public class TimerImpl implements ITimer {
private final Event<EventArgs> tickEvent;
private static final Logger logger = Logger.getLogger(TimerImpl.class.getName());
private int interval;
private final Timer timer = TimerFactory.factoryTimer("UICommon Timer", new Timer() { //$NON-NLS-1$
@Override
public void run() {
logger.info("Timer execution"); //$NON-NLS-1$
tickEvent.raise(this, EventArgs.EMPTY);
}
});
public TimerImpl() {
tickEvent = new Event<>(ProvideTickEvent.definition);
}
@Override
public int getInterval() {
return 0;
}
@Override
public void setInterval(int value) {
logger.info("Timer interval set to " + value + " by UICommon"); //$NON-NLS-1$ //$NON-NLS-2$
interval = value;
}
@Override
public void start() {
logger.info("Timer started by UICommon"); //$NON-NLS-1$
timer.scheduleRepeating(interval);
}
@Override
public void stop() {
logger.info("Timer stopped by UICommon"); //$NON-NLS-1$
timer.cancel();
}
@Override
public Event<EventArgs> getTickEvent() {
return tickEvent;
}
}
| 412 | 0.784799 | 1 | 0.784799 | game-dev | MEDIA | 0.26785 | game-dev | 0.919343 | 1 | 0.919343 |
OpenFOAM/OpenFOAM-9 | 4,555 | src/OpenFOAM/memory/autoPtr/autoPtr.H | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Copyright (C) 2011-2019 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM 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.
OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::autoPtr
Description
An auto-pointer similar to the STL auto_ptr but with automatic casting
to a reference to the type and with pointer allocation checking on access.
SourceFiles
autoPtrI.H
\*---------------------------------------------------------------------------*/
#ifndef autoPtr_H
#define autoPtr_H
#include <cstddef>
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
/*---------------------------------------------------------------------------*\
Class autoPtr Declaration
\*---------------------------------------------------------------------------*/
template<class T>
class autoPtr
{
// Public data
//- Pointer to object
mutable T* ptr_;
public:
typedef T Type;
// Constructors
//- Store object pointer
inline explicit autoPtr(T* = nullptr);
//- Construct as copy by transferring pointer to this autoPtr and
// setting the arguments pointer to nullptr
inline autoPtr(const autoPtr<T>&);
//- Construct either by transferring pointer or cloning.
// Should only be called with type that supports cloning
inline autoPtr(const autoPtr<T>&, const bool reuse);
//- Destructor, delete object if pointer is not nullptr
inline ~autoPtr();
// Member Functions
// Check
//- Return true if the autoPtr is empty (ie, no pointer set)
inline bool empty() const;
//- Return true if the autoPtr valid (ie, the pointer is set)
inline bool valid() const;
// Edit
//- Return object pointer for reuse
inline T* ptr();
//- Set pointer to that given.
// If object pointer already set issue a FatalError
inline void set(T*);
//- If object pointer already set, delete object and set to given
// pointer
inline void reset(T* = nullptr);
//- Delete object (if the pointer is valid) and set pointer to
// nullptr
inline void clear();
// Member Operators
//- Return reference to the object data
inline T& operator()();
//- Return const reference to the object data
inline const T& operator()() const;
//- Return reference to the object data
inline T& operator*();
//- Return const reference to the object data
inline const T& operator*() const;
//- Const cast to the underlying type reference
inline operator const T&() const;
//- Return object pointer
inline T* operator->();
//- Return const object pointer
inline const T* operator->() const;
//- Take over the object pointer from parameter
inline void operator=(T*);
//- Take over the object pointer from parameter
inline void operator=(const autoPtr<T>&);
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#include "autoPtrI.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| 412 | 0.889751 | 1 | 0.889751 | game-dev | MEDIA | 0.382071 | game-dev | 0.693983 | 1 | 0.693983 |
PatrickGTR/gta-open | 4,711 | gamemodes/core/anti-cheat/anti-cheat_money.inc | #include <YSI_Coding\y_hooks>
static enum E_COMPONENT_DATA {
E_COMPONENT_ID,
E_COMPONENT_PRICE
}
static ComponentData[][E_COMPONENT_DATA] = {
1018, 350,
1019, 300,
1020, 250,
1021, 200,
1022, 150,
1028, 770,
1029, 680,
1034, 790,
1037, 690,
1043, 500,
1044, 500,
1045, 510,
1046, 710,
1059, 720,
1064, 830,
1065, 850,
1066, 750,
1089, 650,
1092, 750,
1104, 1610,
1105, 1540,
1113, 3340,
1114, 3250,
1126, 3340,
1127, 3250,
1129, 1650,
1132, 1590,
1135, 1500,
1136, 1000,
1004, 100,
1005, 150,
1011, 220,
1012, 250,
1117, 2130,
1152, 910,
1153, 1200,
1155, 1030,
1157, 930,
1160, 1050,
1165, 850,
1166, 950,
1169, 970,
1170, 880,
1171, 990,
1172, 900,
1173, 950,
1174, 1000,
1175, 900,
1179, 2150,
1181, 2050,
1182, 2130,
1185, 2040,
1188, 2080,
1189, 2200,
1190, 1200,
1191, 1040,
1140, 870,
1141, 980,
1148, 890,
1149, 1000,
1150, 1090,
1151, 840,
1154, 1030,
1156, 920,
1159, 1050,
1161, 950,
1167, 850,
1168, 950,
1176, 1000,
1177, 900,
1178, 2050,
1180, 2130,
1183, 2040,
1184, 2150,
1186, 2095,
1187, 2175,
1192, 940,
1193, 1100,
1006, 80,
1128, 3340,
1130, 3380,
1131, 3290,
1103, 3250,
1032, 170,
1033, 120,
1035, 150,
1038, 190,
1053, 130,
1054, 210,
1055, 230,
1061, 180,
1067, 250,
1068, 200,
1088, 150,
1091, 100,
1000, 400,
1001, 550,
1002, 200,
1003, 250,
1014, 400,
1015, 500,
1016, 200,
1023, 350,
1049, 810,
1050, 620,
1058, 620,
1060, 530,
1138, 580,
1139, 470,
1146, 490,
1147, 600,
1158, 550,
1162, 650,
1163, 550,
1164, 450,
1007, 500,
1017, 500,
1026, 480,
1027, 480,
1030, 37,
1031, 370,
1036, 500,
1039, 390,
1040, 500,
1041, 390,
1042, 1000,
1047, 670,
1048, 530,
1051, 670,
1052, 530,
1056, 520,
1057, 430,
1062, 250,
1063, 430,
1069, 550,
1070, 450,
1071, 550,
1072, 450,
1090, 450,
1093, 350,
1094, 450,
1095, 350,
1099, 1000,
1101, 780,
1102, 830,
1106, 780,
1107, 780,
1108, 780,
1118, 780,
1119, 940,
1120, 780,
1121, 940,
1122, 780,
1124, 780,
1133, 830,
1134, 800,
1137, 800,
1013, 100,
1024, 50,
1142, 150,
1143, 150,
1144, 100,
1145, 100,
1025, 1000,
1073, 1000,
1074, 1030,
1075, 980,
1076, 1560,
1077, 1620,
1078, 1200,
1079, 1030,
1080, 1000,
1081, 1230,
1082, 820,
1083, 1560,
1084, 1350,
1085, 770,
1096, 1000,
1097, 620,
1098, 1140,
1008, 200,
1009, 500,
1010, 1000,
1086, 100,
1087, 1500,
1100, 940,
1123, 860,
1125, 1120,
1109, 1610,
1110, 1540,
1115, 2130,
1116, 2050
};
static
PlayerCash[MAX_PLAYERS],
PlayerOldCash[MAX_PLAYERS];
hook OnPlayerConnect(playerid) {
PlayerCash[playerid] =
PlayerOldCash[playerid] = 0;
return 1;
}
hook OnPlayerSecondUpdate(playerid) {
// if server side money does not match client side money AND client side money is more than server side money.
if ((GetPlayerMoney(playerid) != PlayerCash[playerid]) && (GetPlayerMoney(playerid) > PlayerCash[playerid])) {
PlayerOldCash[playerid] = PlayerCash[playerid];
ResetPlayerMoney(playerid);
// we're nice enough to return player's old money instead of resetting it back to 0.
GivePlayerMoney(playerid, PlayerOldCash[playerid]);
}
return 1;
}
hook native GivePlayerMoney(playerid, money)
{
PlayerCash[playerid] += money;
if(GetPlayerMoney(playerid) != PlayerCash[playerid]) {
CallLocalFunction("OnPlayerMoneyChange", "iii", playerid, GetPlayerMoney(playerid), PlayerCash[playerid]);
}
return continue(playerid, money);
}
hook native ResetPlayerMoney(playerid)
{
PlayerCash[playerid] = 0;
return continue(playerid);
}
hook OnVehicleMod(playerid, vehicleid, componentid)
{
for(new i = 0; i < sizeof(ComponentData); i ++) {
if(componentid == ComponentData[i][E_COMPONENT_ID]) {
GivePlayerMoney(playerid, -ComponentData[i][E_COMPONENT_PRICE]);
break;
}
}
return 1;
}
hook OnVehicleRespray(playerid, vehicleid, color1, color2)
{
GivePlayerMoney(playerid, -100); // costs 100 to respray
return 1;
}
forward OnPlayerMoneyChange(playerid, previous, current); | 412 | 0.643763 | 1 | 0.643763 | game-dev | MEDIA | 0.759392 | game-dev | 0.662062 | 1 | 0.662062 |
stetre/moongl | 14,570 | src/func.h | /* The MIT License (MIT)
*
* Copyright (c) 2016 Stefano Trettel
*
* Software repository: MoonGL, https://github.com/stetre/moongl
*
* 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.
*/
/*------------------------------------------------------------------------------*
| Malloc, Free, CheckError |
*------------------------------------------------------------------------------*/
#define Malloc moongl_Malloc
void *Malloc(lua_State *L, size_t size);
#define Malloc2 moongl_Malloc2
void* Malloc2(lua_State *L, size_t size, void **ptr2, size_t size2);
#define Malloc3 moongl_Malloc3
void* Malloc3(lua_State *L, size_t size, void **ptr2, size_t size2, void **ptr3, size_t size3);
#define MallocNoErr moongl_MallocNoErr
void *MallocNoErr(lua_State *L, size_t size);
#define Strdup moongl_Strdup
char *Strdup(lua_State *L, const char *s);
#define Free moongl_Free
void Free(lua_State *L, void *ptr);
#define CheckError moongl_CheckError
int CheckError(lua_State *L);
#define CheckErrorp moongl_CheckErrorp
void *CheckErrorp(lua_State *L);
#define CheckErrorFree moongl_CheckErrorFree
int CheckErrorFree(lua_State *L, void *ptr);
#define CheckErrorFree2 moongl_CheckErrorFree2
int CheckErrorFree2(lua_State *L, void *ptr1, void *ptr2);
#define CheckErrorFree3 moongl_CheckErrorFree3
int CheckErrorFree3(lua_State *L, void *ptr1, void *ptr2, void *ptr3);
/*------------------------------------------------------------------------------*
| Gen, Bind & C |
*------------------------------------------------------------------------------*/
#define NEW_FUNC(what, otype) /* glGen() + glBind() */ \
static int New##what(lua_State *L) \
{ \
GLuint name; \
check_init_called(L); \
glGen##what##s(1, &name); \
CheckError(L); \
object_new(L, otype, name); \
glBind##what(name); \
CheckError(L); \
lua_pushinteger(L, name); \
return 1; \
}
#define NEW_TARGET_FUNC(what, otype, checkxxx) /* glGen() + glBind() */ \
static int New##what(lua_State *L) \
{ \
GLuint name; \
GLenum target = checkxxx(L, 1); \
check_init_called(L); \
glGen##what##s(1, &name); \
CheckError(L); \
object_new(L, otype, name); \
glBind##what(target, name); \
CheckError(L); \
lua_pushinteger(L, name); \
return 1; \
}
#define GEN_FUNC(what, otype) \
static int Gen##what##s(lua_State *L) \
{ \
int i; \
GLuint* names; \
GLsizei n = luaL_optinteger(L, 1, 1); /* defaults to a single name */ \
if(n <= 0) \
return luaL_argerror(L, 1, "positive number expected"); \
check_init_called(L); \
luaL_checkstack(L, n, NULL); \
names = (GLuint*)Malloc(L, n*sizeof(GLuint)); \
glGen##what##s(n, names); \
CheckErrorFree(L, names); \
for(i = 0; i < n; i++) \
{ \
object_new(L, otype, names[i]); \
lua_pushinteger(L, names[i]); \
} \
Free(L, names); \
return n; \
}
#define BIND_FUNC(what) \
static int Bind##what(lua_State *L) \
{ \
GLuint name = luaL_optinteger(L, 1, 0); \
glBind##what(name); \
CheckError(L); \
return 0; \
}
#define BIND_TARGET_FUNC(what, checkxxx) \
static int Bind##what(lua_State *L) \
{ \
GLenum target = checkxxx(L, 1); \
GLuint name = luaL_optinteger(L, 2, 0); \
glBind##what(target, name); \
CheckError(L); \
return 0; \
}
#define BINDN_FUNC(what) \
static int Bind##what##s(lua_State *L) \
{ \
int i; \
GLuint* names; \
GLuint first = luaL_checkinteger(L, 1); \
GLsizei n = 2; \
while(lua_isinteger(L, n)) n++; /* get the number of names */\
n = n - 2; \
if(--n==0) return luaL_argerror(L, 2, "integer expected"); \
names = (GLuint*)Malloc(L, n*sizeof(GLuint)); \
for(i = 0; i < n; i++) \
names[i] = lua_tointeger(L, i+2); \
glBind##what##s(first, n, names); \
CheckErrorFree(L, names); \
Free(L, names); \
return 0; \
}
#ifndef GL_VERSION_4_5
#define CREATE_FUNC(what, otype) \
static int Create##what##s(lua_State *L) { NOT_AVAILABLE; }
#else
#define CREATE_FUNC(what, otype) \
static int Create##what##s(lua_State *L) \
{ \
int i; \
GLuint* names; \
GLsizei n = luaL_optinteger(L, 1, 1); \
check_init_called(L); \
luaL_checkstack(L, n, NULL); \
names = (GLuint*)Malloc(L, n*sizeof(GLuint)); \
glCreate##what##s(n, names); \
CheckErrorFree(L, names); \
for(i = 0; i < n; i++) \
{ \
object_new(L, otype, names[i]); \
lua_pushinteger(L, names[i]); \
} \
Free(L, names); \
return n; \
}
#endif
#define DELETE_FUNC(what, otype) \
static int Delete##what##s(lua_State *L) \
{ \
GLuint name; \
int arg = 1; \
while(!lua_isnoneornil(L, arg)) \
{ \
name = luaL_checkinteger(L, arg++); \
object_free(L, otype, name); \
} \
return 0; \
}
#define IS_FUNC(what) \
static int Is##what(lua_State *L) \
{ \
GLuint arg = luaL_checkinteger(L, 1); \
GLboolean res = glIs##what(arg); \
CheckError(L); \
lua_pushboolean(L, res); \
return 1; \
}
/*------------------------------------------------------------------------------*
| void glXxx() generic functions |
*------------------------------------------------------------------------------*/
#define VOID_FUNC(func) /* void func(void) */ \
static int func(lua_State *L) \
{ \
gl##func(); \
CheckError(L); \
return 0; \
}
#define BOOLEAN_FUNC(func) /* void func(GLboolean) */\
static int func(lua_State *L) \
{ \
GLboolean arg = checkboolean(L, 1); \
gl##func(arg); \
CheckError(L); \
return 0; \
}
#define INT_FUNC(func) /* void func(GLint) */ \
static int func(lua_State *L) \
{ \
GLint arg = luaL_checkinteger(L, 1); \
gl##func(arg); \
CheckError(L); \
return 0; \
}
#define UINT_FUNC(func) /* void func(GLuint) */ \
static int func(lua_State *L) \
{ \
GLuint arg = luaL_checkinteger(L, 1); \
gl##func(arg); \
CheckError(L); \
return 0; \
}
#define UINT2_FUNC(func) /* void func(GLuint, GLuint) */\
static int func(lua_State *L) \
{ \
GLuint arg1 = luaL_checkinteger(L, 1); \
GLuint arg2 = luaL_checkinteger(L, 2); \
gl##func(arg1, arg2); \
CheckError(L); \
return 0; \
}
#define UINT3_FUNC(func) /* void func(GLuint, GLuint, GLuint) */\
static int func(lua_State *L) \
{ \
GLuint arg1 = luaL_checkinteger(L, 1); \
GLuint arg2 = luaL_checkinteger(L, 2); \
GLuint arg3 = luaL_checkinteger(L, 3); \
gl##func(arg1, arg2, arg3); \
CheckError(L); \
return 0; \
}
#define FLOAT_FUNC(func) /* void func(GLfloat) */ \
static int func(lua_State *L) \
{ \
GLfloat arg = luaL_checknumber(L, 1); \
gl##func(arg); \
CheckError(L); \
return 0; \
}
#define FLOAT2_FUNC(func) /* void func(GLfloat, GLfloat) */\
static int func(lua_State *L) \
{ \
GLfloat arg1 = luaL_checknumber(L, 1); \
GLfloat arg2 = luaL_checknumber(L, 2); \
gl##func(arg1, arg2); \
CheckError(L); \
return 0; \
}
#define FLOAT3_FUNC(func) /* void func(GLfloat, GLfloat, GLfloat) */\
static int func(lua_State *L) \
{ \
GLfloat arg1 = luaL_checknumber(L, 1); \
GLfloat arg2 = luaL_checknumber(L, 2); \
GLfloat arg3 = luaL_checknumber(L, 3); \
gl##func(arg1, arg2, arg3); \
CheckError(L); \
return 0; \
}
#define DOUBLE_FUNC(func) /* void func(GLdouble) */ \
static int func(lua_State *L) \
{ \
GLdouble arg = luaL_checknumber(L, 1); \
gl##func(arg); \
CheckError(L); \
return 0; \
}
| 412 | 0.880004 | 1 | 0.880004 | game-dev | MEDIA | 0.487509 | game-dev | 0.82544 | 1 | 0.82544 |
magefree/mage | 2,997 | Mage.Sets/src/mage/cards/p/PariahsShield.java |
package mage.cards.p;
import java.util.UUID;
import mage.abilities.Ability;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.costs.mana.GenericManaCost;
import mage.abilities.effects.ReplacementEffectImpl;
import mage.abilities.keyword.EquipAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.Duration;
import mage.constants.Outcome;
import mage.constants.Zone;
import mage.game.Game;
import mage.game.events.DamagePlayerEvent;
import mage.game.events.GameEvent;
import mage.game.permanent.Permanent;
import mage.target.common.TargetControlledCreaturePermanent;
/**
*
* @author escplan9 (Derek Monturo - dmontur1 at gmail dot com)
*/
public final class PariahsShield extends CardImpl {
public PariahsShield(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.ARTIFACT},"{5}");
this.subtype.add(SubType.EQUIPMENT);
// All damage that would be dealt to you is dealt to equipped creature instead.
this.addAbility(new SimpleStaticAbility(new PariahsShieldEffect()));
// Equip {3}
this.addAbility(new EquipAbility(Outcome.BoostCreature, new GenericManaCost(3), new TargetControlledCreaturePermanent(), false));
}
private PariahsShield(final PariahsShield card) {
super(card);
}
@Override
public PariahsShield copy() {
return new PariahsShield(this);
}
}
class PariahsShieldEffect extends ReplacementEffectImpl { // TODO: extend redirection effect instead? Redundant with PariahEffect?
PariahsShieldEffect() {
super(Duration.WhileOnBattlefield, Outcome.RedirectDamage);
staticText = "All damage that would be dealt to you is dealt to equipped creature instead";
}
private PariahsShieldEffect(final PariahsShieldEffect effect) {
super(effect);
}
@Override
public boolean replaceEvent(GameEvent event, Ability source, Game game) {
Permanent equipment = game.getPermanent(source.getSourceId());
if (equipment != null) {
Permanent permanent = game.getPermanent(equipment.getAttachedTo());
if (permanent != null) {
DamagePlayerEvent damageEvent = (DamagePlayerEvent) event;
permanent.damage(damageEvent.getAmount(), event.getSourceId(), source, game, damageEvent.isCombatDamage(), damageEvent.isPreventable());
return true;
}
}
return false;
}
@Override
public boolean checksEventType(GameEvent event, Game game) {
return event.getType() == GameEvent.EventType.DAMAGE_PLAYER;
}
@Override
public boolean applies(GameEvent event, Ability source, Game game) {
return event.getPlayerId().equals(source.getControllerId());
}
@Override
public PariahsShieldEffect copy() {
return new PariahsShieldEffect(this);
}
}
| 412 | 0.966462 | 1 | 0.966462 | game-dev | MEDIA | 0.995474 | game-dev | 0.973757 | 1 | 0.973757 |
oiuv/mud | 2,467 | kungfu/skill/guzheng-jifa.c | #include <ansi.h>
inherit SKILL;
string type() { return "knowledge"; }
int valid_learn(object me)
{
if (me->query("int") < 24 && me->query_int() < 35)
return notify_fail("就你那点悟性?五音不全,学什么古筝?\n");
return 1;
}
int play(object me, object ob, string arg)
{
int lvl;
//int i;
string m_name;
if (! arg)
return notify_fail("你要演奏什么曲子?\n");
if (! (lvl = me->query_skill(arg, 1)))
return notify_fail("你不会演奏这首曲子。\n");
if (! SKILL_D(arg)->valid_enable("guzheng-jifa"))
return notify_fail("这不能用来弹奏!\n");
lvl += me->query_skill("guzheng-jifa", 1) / 2;
m_name = to_chinese(arg);
if (me->is_busy())
return notify_fail("你现在正忙,等会儿再演奏吧。\n");
if (lvl < 15)
{
message_vision(WHT "\n$N" WHT "胡乱拨了拨$n" WHT ",结果只是发"
"出了几下刺耳的杂音。\n" NOR, me, ob);
} else
if (lvl < 30)
{
message_vision(WHT "\n$N" WHT "拨拉了一下$n" WHT ",发出几声怪"
"响,难听的一塌糊涂。\n" NOR, me, ob);
} else
if (lvl < 60)
{
message_vision(WHT "\n$N" WHT "摆好$n" WHT "轻轻弹了几下,声音"
"还算清脆,不太难听。\n" NOR, me, ob);
} else
if (lvl < 90)
{
message_vision(HIW "\n$N" HIW "摆好$n" HIW "弹了一首" + m_name +
HIW ",韵律洋洋洒洒,颇为不错。\n" NOR, me, ob);
} else
if (lvl < 150)
{
message_vision(HIW "\n$N" HIW "摆好$n" HIW "弹了一首" + m_name +
HIW ",颇为动人,引人入胜。\n" NOR, me, ob);
} else
if (lvl < 225)
{
message_vision(HIW "\n$N" HIW "摆好$n" HIW "弹了一首" + m_name +
HIW ",听得众人感慨万千,甚是投入。\n" NOR, me,
ob);
} else
if (lvl < 300)
{
message_vision(HIC "\n$N" HIC "摆好$n" HIC "弹了一首" + m_name +
HIC ",琴音宛若溪水荡流,怡然陶趣,雅致万千。\n"
NOR, me, ob);
} else
{
message_vision(HIG "\n$N" HIG "摆好$n" HIG "弹了一首" + m_name +
HIG ",宛若清溪流上心头,令人无酒自醉,却又似身"
"至仙境,心灵空明。\n" NOR, me, ob);
}
me->start_busy(3 + random(3));
SKILL_D(arg)->do_effect(me);
return 1;
}
| 412 | 0.655899 | 1 | 0.655899 | game-dev | MEDIA | 0.621779 | game-dev | 0.776393 | 1 | 0.776393 |
PacktPublishing/Pragmatic-Microservices-with-CSharp-and-Azure | 2,927 | ch15/Codebreaker.BotQ/CodeBreakerTimer.cs | using CodeBreaker.Bot.Api;
using CodeBreaker.Bot.Exceptions;
namespace CodeBreaker.Bot;
public class CodebreakerTimer(CodebreakerGameRunner runner, ILogger<CodebreakerTimer> logger)
{
private readonly CodebreakerGameRunner _gameRunner = runner;
private static readonly ConcurrentDictionary<Guid, CodebreakerTimer> _bots = new();
private PeriodicTimer? _timer;
private int _loop = 0;
private string _statusMessage = "running";
private readonly CancellationTokenSource _cancellationTokenSource = new();
public Guid Start(int delaySecondsBetweenGames, int numberGames, int thinkSeconds)
{
ArgumentOutOfRangeException.ThrowIfNegative(delaySecondsBetweenGames);
ArgumentOutOfRangeException.ThrowIfLessThan(numberGames, 1);
ArgumentOutOfRangeException.ThrowIfNegative(thinkSeconds);
logger.StartGameRunner();
Guid id = Guid.NewGuid();
_bots.TryAdd(id, this);
_timer = new PeriodicTimer(TimeSpan.FromSeconds(delaySecondsBetweenGames));
Task _ = Task.Factory.StartNew(async () =>
{
try
{
do
{
logger.WaitingForNextTick(_loop);
if (await _timer.WaitForNextTickAsync(_cancellationTokenSource.Token)) // simulate some waiting time
{
logger.TimerTickFired(_loop);
await _gameRunner.StartGameAsync(_cancellationTokenSource.Token); // start the game
await _gameRunner.RunAsync(thinkSeconds, _cancellationTokenSource.Token); // play the game until finished
_loop++;
}
} while (_loop < numberGames);
}
catch (HttpRequestException ex)
{
_statusMessage = ex.Message;
logger.Error(ex, ex.Message);
}
}, TaskCreationOptions.LongRunning);
return id;
}
public void Stop()
{
_statusMessage = "stopped";
_timer?.Dispose();
}
public StatusResponse Status() =>
new(_loop + 1, _statusMessage);
public static void Stop(Guid id)
{
if (id == default)
throw new ArgumentException("Invalid argument value {id}", nameof(id));
if (_bots.TryGetValue(id, out CodebreakerTimer? timer))
{
timer.Stop();
_bots.TryRemove(id, out _);
}
throw new BotNotFoundException();
}
public static StatusResponse Status(Guid id)
{
if (id == default)
throw new ArgumentException("Invalid argument value {id}", nameof(id));
if (_bots.TryGetValue(id, out CodebreakerTimer? timer))
return timer?.Status() ?? throw new UnknownStatusException("id found, but unknown status");
throw new BotNotFoundException();
}
}
| 412 | 0.979764 | 1 | 0.979764 | game-dev | MEDIA | 0.508526 | game-dev | 0.967709 | 1 | 0.967709 |
isotoxin/isotoxin | 1,329 | source/plugins/proto_xmp/gloox/pubsubitem.cpp | /*
Copyright (c) 2005-2016 by Jakob Schröter <js@camaya.net>
This file is part of the gloox library. http://camaya.net/gloox
This software is distributed under a license. The full license
agreement can be found in the file LICENSE in this distribution.
This software may not be copied, modified, sold or distributed
other than expressed in the named license agreement.
This software is distributed without any warranty.
*/
#include "pubsubitem.h"
#include "tag.h"
namespace gloox
{
namespace PubSub
{
Item::Item()
: m_payload( 0 )
{
}
Item::Item( const Tag* tag )
: m_payload( 0 )
{
if( !tag || tag->name() != "item" )
return;
m_id = tag->findAttribute( "id" );
if( tag->children().size() )
m_payload = tag->children().front()->clone();
}
Item::Item( const Item& item )
: m_payload( item.m_payload ? item.m_payload->clone() : 0 )
{
m_id = item.m_id;
}
Item::~Item()
{
delete m_payload;
}
void Item::setPayload( Tag* tag )
{
delete m_payload;
m_payload = tag;
}
Tag* Item::tag() const
{
Tag* t = new Tag( "item" );
t->addAttribute( "id", m_id );
if( m_payload )
t->addChild( m_payload->clone() );
return t;
}
}
}
| 412 | 0.87747 | 1 | 0.87747 | game-dev | MEDIA | 0.519532 | game-dev | 0.660708 | 1 | 0.660708 |
latte-soft/datamodelpatch | 4,267 | src/PatchRoot/DataModelInstances/CoreGui/RobloxGui/Modules/LuaApp/Thunks/Authentication/AppStorageUtilities.luau | local v0 = require(game:GetService("CoreGui").RobloxGui.Modules.LuaApp.Enum.LocalStorageKey);
local l_AppStorageService_0 = game:GetService("AppStorageService");
local l_HttpService_0 = game:GetService("HttpService");
local v9 = {
setRobloxLocaleId = function(v3)
l_AppStorageService_0:SetItem(v0.RobloxLocaleId, v3);
end,
setGameLocaleId = function(v4)
l_AppStorageService_0:SetItem(v0.GameLocaleId, v4);
end,
getAuthenticatedTheme = function()
return l_AppStorageService_0:GetItem(v0.AuthenticatedTheme);
end,
setAuthenticatedTheme = function(v5)
l_AppStorageService_0:SetItem(v0.AuthenticatedTheme, v5);
end,
getAccountBlob = function()
if not game:GetEngineFeature("AccountSwitchFeatureEnabled") then
return "";
else
return l_AppStorageService_0:GetItem(v0.AccountBlob) or "";
end;
end,
setAccountBlob = function(v6)
if game:GetEngineFeature("AccountSwitchFeatureEnabled") then
l_AppStorageService_0:SetItem(v0.AccountBlob, v6 or "");
end;
end,
getSignupActionRequired = function()
return l_AppStorageService_0:GetItem(v0.SignupActionRequired);
end,
setSignupActionRequired = function(v7)
l_AppStorageService_0:SetItem(v0.SignupActionRequired, v7);
end,
getAccountSwitcherMetadataMap = function()
if not game:GetEngineFeature("AccountSwitcherMetadataMapKeyAvailable") then
return "";
else
return l_AppStorageService_0:GetItem(v0.AccountSwitcherMetadataMap) or "";
end;
end,
setAccountSwitcherMetadataMap = function(v8)
if game:GetEngineFeature("AccountSwitcherMetadataMapKeyAvailable") then
l_AppStorageService_0:SetItem(v0.AccountSwitcherMetadataMap, v8 or "");
end;
end
};
v9.getAccountSwitchTargetUsername = function()
if not game:GetEngineFeature("AccountSwitcherMetadataMapKeyAvailable") then
return "";
else
local v10 = v9.getAccountSwitcherMetadataMap();
if not (v10 ~= nil) or v10 == "" then
return "";
else
local v11 = l_HttpService_0:JSONDecode(v10);
if not (((v11 ~= nil and v11 ~= "") and next(v11) ~= nil) and next(v11) ~= "") or v11.AccountSwitchTargetUsername == nil then
return "";
else
return v11.AccountSwitchTargetUsername;
end;
end;
end;
end;
v9.setAccountSwitchTargetUsername = function(v12)
if game:GetEngineFeature("AccountSwitcherMetadataMapKeyAvailable") then
local v13 = v9.getAccountSwitcherMetadataMap();
local v14 = nil;
if not (v13 ~= nil) or v13 == "" then
v14 = {
AccountSwitchTargetUsername = v12
};
else
v14 = l_HttpService_0:JSONDecode(v13);
v14.AccountSwitchTargetUsername = v12;
end;
v9.setAccountSwitcherMetadataMap(l_HttpService_0:JSONEncode(v14));
end;
end;
v9.getAccountSwitchStatus = function()
if not game:GetEngineFeature("AccountSwitcherMetadataMapKeyAvailable") then
return "";
else
local v15 = v9.getAccountSwitcherMetadataMap();
if not (v15 ~= nil) or v15 == "" then
return "";
else
local v16 = l_HttpService_0:JSONDecode(v15);
if not (((v16 ~= nil and v16 ~= "") and next(v16) ~= nil) and next(v16) ~= "") or v16.AccountSwitchStatus == nil then
return "";
else
return v16.AccountSwitchStatus;
end;
end;
end;
end;
v9.setAccountSwitchStatus = function(v17)
if game:GetEngineFeature("AccountSwitcherMetadataMapKeyAvailable") then
local v18 = v9.getAccountSwitcherMetadataMap();
local v19 = nil;
if not (v18 ~= nil) or v18 == "" then
v19 = {
AccountSwitchStatus = v17
};
else
v19 = l_HttpService_0:JSONDecode(v18);
v19.AccountSwitchStatus = v17;
end;
v9.setAccountSwitcherMetadataMap(l_HttpService_0:JSONEncode(v19));
end;
end;
v9.flush = function()
l_AppStorageService_0:flush();
end;
return v9;
| 412 | 0.860359 | 1 | 0.860359 | game-dev | MEDIA | 0.781503 | game-dev | 0.955781 | 1 | 0.955781 |
sschmid/Match-One | 8,489 | Assets/Demigiant/DOTween/Modules/DOTweenModuleAudio.cs | // Author: Daniele Giardini - http://www.demigiant.com
// Created: 2018/07/13
#if true // MODULE_MARKER
using System;
using UnityEngine;
#if UNITY_5 || UNITY_2017_1_OR_NEWER
using UnityEngine.Audio; // Required for AudioMixer
#endif
#pragma warning disable 1591
namespace DG.Tweening
{
public static class DOTweenModuleAudio
{
#region Shortcuts
#region Audio
/// <summary>Tweens an AudioSource's volume to the given value.
/// Also stores the AudioSource as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach (0 to 1)</param><param name="duration">The duration of the tween</param>
public static Tweener DOFade(this AudioSource target, float endValue, float duration)
{
if (endValue < 0) endValue = 0;
else if (endValue > 1) endValue = 1;
return DOTween.To(() => target.volume, x => target.volume = x, endValue, duration).SetTarget(target);
}
/// <summary>Tweens an AudioSource's pitch to the given value.
/// Also stores the AudioSource as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static Tweener DOPitch(this AudioSource target, float endValue, float duration)
{
return DOTween.To(() => target.pitch, x => target.pitch = x, endValue, duration).SetTarget(target);
}
#endregion
#if UNITY_5 || UNITY_2017_1_OR_NEWER
#region AudioMixer (Unity 5 or Newer)
/// <summary>Tweens an AudioMixer's exposed float to the given value.
/// Also stores the AudioMixer as the tween's target so it can be used for filtered operations.
/// Note that you need to manually expose a float in an AudioMixerGroup in order to be able to tween it from an AudioMixer.</summary>
/// <param name="floatName">Name given to the exposed float to set</param>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static Tweener DOSetFloat(this AudioMixer target, string floatName, float endValue, float duration)
{
return DOTween.To(()=> {
float currVal;
target.GetFloat(floatName, out currVal);
return currVal;
}, x=> target.SetFloat(floatName, x), endValue, duration)
.SetTarget(target);
}
#region Operation Shortcuts
/// <summary>
/// Completes all tweens that have this target as a reference
/// (meaning tweens that were started from this target, or that had this target added as an Id)
/// and returns the total number of tweens completed
/// (meaning the tweens that don't have infinite loops and were not already complete)
/// </summary>
/// <param name="withCallbacks">For Sequences only: if TRUE also internal Sequence callbacks will be fired,
/// otherwise they will be ignored</param>
public static int DOComplete(this AudioMixer target, bool withCallbacks = false)
{
return DOTween.Complete(target, withCallbacks);
}
/// <summary>
/// Kills all tweens that have this target as a reference
/// (meaning tweens that were started from this target, or that had this target added as an Id)
/// and returns the total number of tweens killed.
/// </summary>
/// <param name="complete">If TRUE completes the tween before killing it</param>
public static int DOKill(this AudioMixer target, bool complete = false)
{
return DOTween.Kill(target, complete);
}
/// <summary>
/// Flips the direction (backwards if it was going forward or viceversa) of all tweens that have this target as a reference
/// (meaning tweens that were started from this target, or that had this target added as an Id)
/// and returns the total number of tweens flipped.
/// </summary>
public static int DOFlip(this AudioMixer target)
{
return DOTween.Flip(target);
}
/// <summary>
/// Sends to the given position all tweens that have this target as a reference
/// (meaning tweens that were started from this target, or that had this target added as an Id)
/// and returns the total number of tweens involved.
/// </summary>
/// <param name="to">Time position to reach
/// (if higher than the whole tween duration the tween will simply reach its end)</param>
/// <param name="andPlay">If TRUE will play the tween after reaching the given position, otherwise it will pause it</param>
public static int DOGoto(this AudioMixer target, float to, bool andPlay = false)
{
return DOTween.Goto(target, to, andPlay);
}
/// <summary>
/// Pauses all tweens that have this target as a reference
/// (meaning tweens that were started from this target, or that had this target added as an Id)
/// and returns the total number of tweens paused.
/// </summary>
public static int DOPause(this AudioMixer target)
{
return DOTween.Pause(target);
}
/// <summary>
/// Plays all tweens that have this target as a reference
/// (meaning tweens that were started from this target, or that had this target added as an Id)
/// and returns the total number of tweens played.
/// </summary>
public static int DOPlay(this AudioMixer target)
{
return DOTween.Play(target);
}
/// <summary>
/// Plays backwards all tweens that have this target as a reference
/// (meaning tweens that were started from this target, or that had this target added as an Id)
/// and returns the total number of tweens played.
/// </summary>
public static int DOPlayBackwards(this AudioMixer target)
{
return DOTween.PlayBackwards(target);
}
/// <summary>
/// Plays forward all tweens that have this target as a reference
/// (meaning tweens that were started from this target, or that had this target added as an Id)
/// and returns the total number of tweens played.
/// </summary>
public static int DOPlayForward(this AudioMixer target)
{
return DOTween.PlayForward(target);
}
/// <summary>
/// Restarts all tweens that have this target as a reference
/// (meaning tweens that were started from this target, or that had this target added as an Id)
/// and returns the total number of tweens restarted.
/// </summary>
public static int DORestart(this AudioMixer target)
{
return DOTween.Restart(target);
}
/// <summary>
/// Rewinds all tweens that have this target as a reference
/// (meaning tweens that were started from this target, or that had this target added as an Id)
/// and returns the total number of tweens rewinded.
/// </summary>
public static int DORewind(this AudioMixer target)
{
return DOTween.Rewind(target);
}
/// <summary>
/// Smoothly rewinds all tweens that have this target as a reference
/// (meaning tweens that were started from this target, or that had this target added as an Id)
/// and returns the total number of tweens rewinded.
/// </summary>
public static int DOSmoothRewind(this AudioMixer target)
{
return DOTween.SmoothRewind(target);
}
/// <summary>
/// Toggles the paused state (plays if it was paused, pauses if it was playing) of all tweens that have this target as a reference
/// (meaning tweens that were started from this target, or that had this target added as an Id)
/// and returns the total number of tweens involved.
/// </summary>
public static int DOTogglePause(this AudioMixer target)
{
return DOTween.TogglePause(target);
}
#endregion
#endregion
#endif
#endregion
}
}
#endif
| 412 | 0.788369 | 1 | 0.788369 | game-dev | MEDIA | 0.953853 | game-dev | 0.917519 | 1 | 0.917519 |
hydro-sdk/hydro-sdk | 11,600 | lib/cfr/builtins/libs/dart/async/future.dart | import 'dart:async';
import 'dart:core';
import 'package:hydro_sdk/cfr/runtimeSupport.dart';
class VMManagedFuture extends VMManagedBox<Future<dynamic>> {
VMManagedFuture(
{required this.table, required this.vmObject, required this.hydroState})
: super(
table: table,
vmObject: vmObject,
hydroState: hydroState,
) {
table['then'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) {
Closure unpackedonValue = luaCallerArguments[1];
Closure? unpackedonError = luaCallerArguments.length >= 3
? luaCallerArguments[2]['onError']
: null;
return [
maybeBoxObject<Future>(
object: vmObject.then(
(_) => ((
final List<dynamic>? val,
) =>
val != null && val.length >= 1 ? val[0] : null)(
unpackedonValue.dispatch(
[luaCallerArguments[0], _],
parentState: hydroState,
),
),
onError: unpackedonError != null
? (_, __) => ((
final List<dynamic>? val,
) =>
val != null && val.length >= 1 ? val[0] : null)(
unpackedonError.dispatch(
[luaCallerArguments[0], _, __],
parentState: hydroState,
),
)
: null),
hydroState: hydroState,
table: HydroTable()),
];
});
table['catchError'] =
makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) {
Closure unpackedonError = luaCallerArguments[1];
Closure? unpackedtest =
luaCallerArguments.length >= 3 ? luaCallerArguments[2]['test'] : null;
return [
maybeBoxObject<Future>(
object: vmObject.catchError(
(_, __) => ((
final List<dynamic>? val,
) =>
val != null && val.length >= 1 ? val[0] : null)(
unpackedonError.dispatch(
[luaCallerArguments[0], _, __],
parentState: hydroState,
),
),
test: unpackedtest != null
? (_) => unpackedtest.dispatch(
[luaCallerArguments[0], _],
parentState: hydroState,
)[0]
: null),
hydroState: hydroState,
table: HydroTable()),
];
});
table['whenComplete'] =
makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) {
Closure unpackedaction = luaCallerArguments[1];
return [
maybeBoxObject<Future>(
object: vmObject.whenComplete(
() => maybeUnBoxAndBuildArgument<FutureOr<void>, void>(
unpackedaction.dispatch(
[
luaCallerArguments[0],
],
parentState: hydroState,
)[0],
parentState: hydroState)),
hydroState: hydroState,
table: HydroTable()),
];
});
table['asStream'] =
makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) {
return [
maybeBoxObject<Stream>(
object: vmObject.asStream(),
hydroState: hydroState,
table: HydroTable()),
];
});
table['timeout'] =
makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) {
Closure? unpackedonTimeout = luaCallerArguments.length >= 3
? luaCallerArguments[2]['onTimeout']
: null;
return [
maybeBoxObject<Future>(
object: vmObject.timeout(
maybeUnBoxAndBuildArgument<Duration, dynamic>(
luaCallerArguments[1],
parentState: hydroState),
onTimeout: unpackedonTimeout != null
? () =>
maybeUnBoxAndBuildArgument<FutureOr<dynamic>, dynamic>(
unpackedonTimeout.dispatch(
[
luaCallerArguments[0],
],
parentState: hydroState,
)[0],
parentState: hydroState)
: null),
hydroState: hydroState,
table: HydroTable()),
];
});
}
final HydroTable table;
final HydroState hydroState;
final Future vmObject;
}
void loadFuture({required HydroState hydroState, required HydroTable table}) {
table['future'] = makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) {
Closure unpackedcomputation = luaCallerArguments[1];
return [
maybeBoxObject<Future>(
object: Future(
() => maybeUnBoxAndBuildArgument<FutureOr<dynamic>, dynamic>(
unpackedcomputation.dispatch(
[
luaCallerArguments[0],
],
parentState: hydroState,
)[0],
parentState: hydroState)),
hydroState: hydroState,
table: luaCallerArguments[0])
];
});
table['futureMicrotask'] =
makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) {
Closure unpackedcomputation = luaCallerArguments[1];
return [
maybeBoxObject<Future>(
object: Future.microtask(
() => maybeUnBoxAndBuildArgument<FutureOr<dynamic>, dynamic>(
unpackedcomputation.dispatch(
[
luaCallerArguments[0],
],
parentState: hydroState,
)[0],
parentState: hydroState)),
hydroState: hydroState,
table: HydroTable()),
];
});
table['futureSync'] =
makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) {
Closure unpackedcomputation = luaCallerArguments[1];
return [
maybeBoxObject<Future>(
object: Future.sync(
() => maybeUnBoxAndBuildArgument<FutureOr<dynamic>, dynamic>(
unpackedcomputation.dispatch(
[
luaCallerArguments[0],
],
parentState: hydroState,
)[0],
parentState: hydroState)),
hydroState: hydroState,
table: HydroTable()),
];
});
table['futureValue'] =
makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) {
return [
maybeBoxObject<Future>(
object: Future.value(
maybeUnBoxAndBuildArgument<FutureOr<dynamic>?, dynamic>(
luaCallerArguments[1],
parentState: hydroState)),
hydroState: hydroState,
table: HydroTable()),
];
});
table['futureError'] =
makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) {
return [
maybeBoxObject<Future>(
object: Future.error(
maybeUnBoxAndBuildArgument<Object, dynamic>(luaCallerArguments[1],
parentState: hydroState),
maybeUnBoxAndBuildArgument<StackTrace?, dynamic>(
luaCallerArguments[2],
parentState: hydroState)),
hydroState: hydroState,
table: HydroTable()),
];
});
table['futureDelayed'] =
makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) {
Closure? unpackedcomputation = luaCallerArguments[2];
return [
maybeBoxObject<Future>(
object: Future.delayed(
maybeUnBoxAndBuildArgument<Duration, dynamic>(
luaCallerArguments[1],
parentState: hydroState),
unpackedcomputation != null
? () =>
maybeUnBoxAndBuildArgument<FutureOr<dynamic>, dynamic>(
unpackedcomputation.dispatch(
[
luaCallerArguments[0],
],
parentState: hydroState,
)[0],
parentState: hydroState)
: null),
hydroState: hydroState,
table: HydroTable()),
];
});
table['futureWait'] =
makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) {
Closure? unpackedcleanUp = luaCallerArguments.length >= 3
? luaCallerArguments[2]['cleanUp']
: null;
return [
maybeBoxObject<Future>(
object: Future.wait(
maybeUnBoxAndBuildArgument<Iterable<Future<dynamic>>,
Future<dynamic>>(luaCallerArguments[1],
parentState: hydroState),
cleanUp: unpackedcleanUp != null
? (successValue) => unpackedcleanUp.dispatch(
[luaCallerArguments[0], successValue],
parentState: hydroState,
)
: null,
eagerError: luaCallerArguments.length >= 3
? luaCallerArguments[2]['eagerError']
: null),
hydroState: hydroState,
table: HydroTable()),
];
});
table['futureAny'] =
makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) {
return [
maybeBoxObject<Future>(
object: Future.any(maybeUnBoxAndBuildArgument<
Iterable<Future<dynamic>>,
Future<dynamic>>(luaCallerArguments[1], parentState: hydroState)),
hydroState: hydroState,
table: HydroTable()),
];
});
table['futureForEach'] =
makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) {
Closure unpackedaction = luaCallerArguments[2];
return [
maybeBoxObject<Future>(
object: Future.forEach(
maybeUnBoxAndBuildArgument<Iterable<dynamic>, dynamic>(
luaCallerArguments[1],
parentState: hydroState),
(element) =>
maybeUnBoxAndBuildArgument<FutureOr<dynamic>, dynamic>(
unpackedaction.dispatch(
[luaCallerArguments[0], element],
parentState: hydroState,
)[0],
parentState: hydroState)),
hydroState: hydroState,
table: HydroTable()),
];
});
table['futureDoWhile'] =
makeLuaDartFunc(func: (List<dynamic> luaCallerArguments) {
Closure unpackedaction = luaCallerArguments[1];
return [
maybeBoxObject<Future>(
object: Future.doWhile(
() => maybeUnBoxAndBuildArgument<FutureOr<bool>, bool>(
unpackedaction.dispatch(
[
luaCallerArguments[0],
],
parentState: hydroState,
)[0],
parentState: hydroState)),
hydroState: hydroState,
table: HydroTable()),
];
});
registerBoxer<Future>(boxer: (
{required Future vmObject,
required HydroState hydroState,
required HydroTable table}) {
return VMManagedFuture(
vmObject: vmObject, hydroState: hydroState, table: table);
});
}
| 412 | 0.847236 | 1 | 0.847236 | game-dev | MEDIA | 0.689656 | game-dev | 0.967698 | 1 | 0.967698 |
codingben/maple-fighters | 1,782 | src/game-service/Game.Application/Components/ComponentCollection.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace Game.Application.Components
{
/// <summary>
/// Collection of components.
/// </summary>
public sealed class ComponentCollection : IComponents
{
private readonly List<IComponent> components = new();
public ComponentCollection(IEnumerable<IComponent> collection = null)
{
if (collection == null) return;
components.AddRange(collection);
foreach (var component in components)
{
component.Awake(this);
}
}
/// <summary>
/// See <see cref="IComponents.Add"/> for more information.
/// </summary>
public void Add(IComponent component)
{
if (component == null) return;
components.Add(component);
component.Awake(this);
}
/// <summary>
/// See <see cref="IComponents.Get{T}"/> for more information.
/// </summary>
public TComponent Get<TComponent>()
where TComponent : class
{
if (typeof(TComponent).IsInterface == false)
{
var name = typeof(TComponent).Name;
var message =
$"Component {name} should be accessible via interface.";
throw new Exception(message);
}
return components.OfType<TComponent>().FirstOrDefault();
}
/// <summary>
/// See <see cref="IDisposable.Dispose"/> for more information.
/// </summary>
public void Dispose()
{
foreach (var component in components)
{
component?.Dispose();
}
}
}
} | 412 | 0.611412 | 1 | 0.611412 | game-dev | MEDIA | 0.26852 | game-dev | 0.723128 | 1 | 0.723128 |
ProjectIgnis/CardScripts | 3,881 | official/c70551291.lua | --伝説の剣闘士 カオス・ソルジャー
--Black Luster Soldier - Legendary Swordsman
--scripted by pyrQ
local s,id=GetID()
function s.initial_effect(c)
c:EnableReviveLimit()
--Must be Ritual Summoned
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(aux.ritlimit)
c:RegisterEffect(e1)
--Give up your normal draw to search 1 Ritual Spell
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,0))
e2:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_PREDRAW)
e2:SetRange(LOCATION_HAND)
e2:SetCondition(s.thcon)
e2:SetCost(s.thcost)
e2:SetTarget(s.thtg)
e2:SetOperation(s.thop)
c:RegisterEffect(e2)
--Opponent cannot activate cards/effects during your Battle Phase
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD)
e3:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e3:SetCode(EFFECT_CANNOT_ACTIVATE)
e3:SetTargetRange(0,1)
e3:SetRange(LOCATION_MZONE)
e3:SetCondition(function(e) return Duel.IsBattlePhase() and Duel.IsTurnPlayer(e:GetHandlerPlayer()) end)
e3:SetValue(1)
c:RegisterEffect(e3)
--Material check
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_SINGLE)
e4:SetCode(EFFECT_MATERIAL_CHECK)
e4:SetValue(s.valcheck)
c:RegisterEffect(e4)
--Shuffle all cards the opponent controls to the Deck
local e5=Effect.CreateEffect(c)
e5:SetDescription(aux.Stringid(id,1))
e5:SetCategory(CATEGORY_TODECK)
e5:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e5:SetCode(EVENT_BATTLE_DESTROYING)
e5:SetCondition(s.tdcon)
e5:SetTarget(s.tdtg)
e5:SetOperation(s.tdop)
c:RegisterEffect(e5)
end
s.listed_names={21082832,14094090}
function s.thcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsTurnPlayer(tp) and Duel.GetFieldGroupCount(tp,LOCATION_DECK,0)>0
and Duel.GetDrawCount(tp)>0 and (Duel.GetTurnCount()>1 or Duel.IsDuelType(DUEL_1ST_TURN_DRAW))
end
function s.thcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return not e:GetHandler():IsPublic() end
end
function s.thfilter(c)
return c:IsRitualSpell() and c:IsAbleToHand()
end
function s.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(s.thfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,0,LOCATION_DECK)
end
function s.thop(e,tp,eg,ep,ev,re,r,rp)
local dt=Duel.GetDrawCount(tp)
if dt==0 then return false end
_replace_count=1
_replace_max=dt
--Give up your normal draw this turn
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetCode(EFFECT_DRAW_COUNT)
e1:SetTargetRange(1,0)
e1:SetReset(RESET_PHASE|PHASE_DRAW)
e1:SetValue(0)
Duel.RegisterEffect(e1,tp)
if _replace_count>_replace_max then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,s.thfilter,tp,LOCATION_DECK,0,1,1,nil)
if #g>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
function s.valcheck(e,c)
local g=c:GetMaterial()
if g:IsExists(Card.IsType,1,nil,TYPE_NORMAL) then
c:RegisterFlagEffect(id,RESET_EVENT|RESETS_STANDARD&~(RESET_TOFIELD|RESET_LEAVE|RESET_TEMP_REMOVE),EFFECT_FLAG_CLIENT_HINT,1,0,aux.Stringid(id,2))
end
end
function s.tdcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:GetFlagEffect(id)>0 and Duel.GetAttacker()==c and c:IsStatus(STATUS_OPPO_BATTLE)
end
function s.tdtg(e,tp,eg,ep,ev,re,r,rp,chk)
local dg=Duel.GetMatchingGroup(Card.IsAbleToDeck,tp,0,LOCATION_ONFIELD,nil)
if chk==0 then return #dg>0 end
Duel.SetOperationInfo(0,CATEGORY_TODECK,dg,#dg,0,0)
end
function s.tdop(e,tp,eg,ep,ev,re,r,rp)
local dg=Duel.GetMatchingGroup(Card.IsAbleToDeck,tp,0,LOCATION_ONFIELD,nil)
if #dg==0 then return end
Duel.SendtoDeck(dg,nil,SEQ_DECKSHUFFLE,REASON_EFFECT)
end | 412 | 0.844265 | 1 | 0.844265 | game-dev | MEDIA | 0.980568 | game-dev | 0.956883 | 1 | 0.956883 |
BuildCraft/BuildCraft | 2,882 | common/buildcraft/builders/container/ContainerFiller.java | /*
* Copyright (c) 2017 SpaceToad and the BuildCraft team
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/
*/
package buildcraft.builders.container;
import java.io.IOException;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import net.minecraftforge.fml.relauncher.Side;
import buildcraft.api.filler.IFillerPattern;
import buildcraft.lib.gui.ContainerBCTile;
import buildcraft.lib.gui.slot.SlotBase;
import buildcraft.lib.net.PacketBufferBC;
import buildcraft.lib.statement.FullStatement;
import buildcraft.builders.filler.FillerType;
import buildcraft.builders.tile.TileFiller;
import buildcraft.core.marker.volume.WorldSavedDataVolumeBoxes;
public class ContainerFiller extends ContainerBCTile<TileFiller> implements IContainerFilling {
private final FullStatement<IFillerPattern> patternStatementClient = new FullStatement<>(
FillerType.INSTANCE,
4,
(statement, paramIndex) -> onStatementChange()
);
public ContainerFiller(EntityPlayer player, TileFiller tile) {
super(player, tile);
addFullPlayerInventory(153);
for (int sy = 0; sy < 3; sy++) {
for (int sx = 0; sx < 9; sx++) {
addSlotToContainer(new SlotBase(tile.invResources, sx + sy * 9, sx * 18 + 8, sy * 18 + 40));
}
}
init();
}
@Override
public EntityPlayer getPlayer() {
return player;
}
@Override
public FullStatement<IFillerPattern> getPatternStatementClient() {
return patternStatementClient;
}
@Override
public FullStatement<IFillerPattern> getPatternStatement() {
return tile.addon != null ? tile.addon.patternStatement : tile.patternStatement;
}
@Override
public boolean isInverted() {
return tile.addon != null ? tile.addon.inverted : tile.inverted;
}
@Override
public void setInverted(boolean value) {
if (tile.addon != null) {
tile.addon.inverted = value;
} else {
tile.inverted = value;
}
}
@Override
public void valuesChanged() {
if (tile.addon != null) {
tile.addon.updateBuildingInfo();
if (!player.world.isRemote) {
WorldSavedDataVolumeBoxes.get(getPlayer().world).markDirty();
}
}
if (!player.world.isRemote) {
tile.onStatementChange();
}
}
@Override
public void readMessage(int id, PacketBufferBC buffer, Side side, MessageContext ctx) throws IOException {
super.readMessage(id, buffer, side, ctx);
IContainerFilling.super.readMessage(id, buffer, side, ctx);
}
}
| 412 | 0.860959 | 1 | 0.860959 | game-dev | MEDIA | 0.991615 | game-dev | 0.959129 | 1 | 0.959129 |
KoshakMineDEV/Lumi | 3,157 | src/main/java/cn/nukkit/command/selector/ParseUtils.java | package cn.nukkit.command.selector;
import cn.nukkit.Server;
import cn.nukkit.command.exceptions.SelectorSyntaxException;
/**
* 一些有关目标选择器解析的常用静态函数
* @author PowerNukkitX Project Team
*/
public class ParseUtils {
/**
* 解析偏移int值
* @param value 文本
* @param base 基础值
* @return 偏移值
*/
public static int parseOffsetInt(String value, int base) throws SelectorSyntaxException {
try {
if (value.startsWith("~")) {
return value.length() != 1 ? base + Integer.parseInt(value.substring(1)) : base;
} else {
return Integer.parseInt(value);
}
} catch (NumberFormatException e) {
throw new SelectorSyntaxException("Error parsing target selector", e);
}
}
/**
* 解析偏移double值
* @param value 文本
* @param base 基础值
* @return 偏移值
*/
public static double parseOffsetDouble(String value, double base) throws SelectorSyntaxException {
try {
if (value.startsWith("~")) {
return value.length() != 1 ? base + Double.parseDouble(value.substring(1)) : base;
} else {
return Double.parseDouble(value);
}
} catch (NumberFormatException e) {
throw new SelectorSyntaxException("Error parsing target selector", e);
}
}
/**
* 检查参数是否反转
* @param value 给定字符串
* @return 是否反转
*/
public static boolean checkReversed(String value) {
return value.startsWith("!");
}
/**
* 要求参数不能取反。若取反,则抛出{@link SelectorSyntaxException}
* @param value 给定字符串
*/
public static void cannotReversed(String value) throws SelectorSyntaxException {
if (checkReversed(value))
throw new SelectorSyntaxException("Argument cannot be reversed!");
}
/**
* 要求参数不能多于1
* @param args 参数列表
* @param keyName 参数键名
*/
public static void singleArgument(String[] args, String keyName) throws SelectorSyntaxException {
if (args.length > 1)
throw new SelectorSyntaxException("Multiple arguments is not allow in arg " + keyName);
}
/**
* 检查给定值是否在给定的两个数之间
* @param bound1 边界1
* @param bound2 边界2
* @param value 之值
* @return 给定值是否在给定的两个数之间
*/
public static boolean checkBetween(double bound1, double bound2, double value) {
return bound1 < bound2 ?
(value >= bound1 && value <= bound2) :
(value >= bound2 && value <= bound1);
}
/**
* 通过给定游戏模式字符串解析游戏模式数字<p/>
* 此方法可匹配参数与原版选择器参数m给定预定值相同
* @param token 字符串
* @return 游戏模式数字
*/
public static int parseGameMode(String token) throws SelectorSyntaxException {
return switch (token) {
case "s", "survival", "0" -> 0;
case "c", "creative", "1" -> 1;
case "a", "adventure", "2" -> 2;
case "spectator", "3" -> 3;
case "d", "default" -> Server.getInstance().getDefaultGamemode();
default -> throw new SelectorSyntaxException("Unknown gamemode token: " + token);
};
}
}
| 412 | 0.941517 | 1 | 0.941517 | game-dev | MEDIA | 0.578903 | game-dev,web-backend | 0.946737 | 1 | 0.946737 |
Aussiemon/Darktide-Source-Code | 3,032 | dialogues/generated/adamant_female_a_ogryn_b.lua | -- chunkname: @dialogues/generated/adamant_female_a_ogryn_b.lua
local adamant_female_a_ogryn_b = {
adamant_female_a_ogryn_bonding_conversation_11_b = {
randomize_indexes_n = 0,
sound_events_n = 1,
sound_events = {
[1] = "loc_ogryn_b__adamant_female_a_ogryn_bonding_conversation_11_b_01",
},
sound_events_duration = {
[1] = 1.761406,
},
randomize_indexes = {},
},
adamant_female_a_ogryn_bonding_conversation_11_d = {
randomize_indexes_n = 0,
sound_events_n = 1,
sound_events = {
[1] = "loc_ogryn_b__adamant_female_a_ogryn_bonding_conversation_11_d_01",
},
sound_events_duration = {
[1] = 1.828396,
},
randomize_indexes = {},
},
adamant_female_a_ogryn_bonding_conversation_12_b = {
randomize_indexes_n = 0,
sound_events_n = 1,
sound_events = {
[1] = "loc_ogryn_b__adamant_female_a_ogryn_bonding_conversation_12_b_01",
},
sound_events_duration = {
[1] = 3.754354,
},
randomize_indexes = {},
},
adamant_female_a_ogryn_bonding_conversation_12_d = {
randomize_indexes_n = 0,
sound_events_n = 1,
sound_events = {
[1] = "loc_ogryn_b__adamant_female_a_ogryn_bonding_conversation_12_d_01",
},
sound_events_duration = {
[1] = 1.375458,
},
randomize_indexes = {},
},
adamant_female_a_ogryn_bonding_conversation_13_b = {
randomize_indexes_n = 0,
sound_events_n = 1,
sound_events = {
[1] = "loc_ogryn_b__adamant_female_a_ogryn_bonding_conversation_13_b_01",
},
sound_events_duration = {
[1] = 1.197573,
},
randomize_indexes = {},
},
adamant_female_a_ogryn_bonding_conversation_13_d = {
randomize_indexes_n = 0,
sound_events_n = 1,
sound_events = {
[1] = "loc_ogryn_b__adamant_female_a_ogryn_bonding_conversation_13_d_01",
},
sound_events_duration = {
[1] = 3.491844,
},
randomize_indexes = {},
},
adamant_female_a_ogryn_bonding_conversation_14_b = {
randomize_indexes_n = 0,
sound_events_n = 1,
sound_events = {
[1] = "loc_ogryn_b__adamant_female_a_ogryn_bonding_conversation_14_b_01",
},
sound_events_duration = {
[1] = 0.608927,
},
randomize_indexes = {},
},
adamant_female_a_ogryn_bonding_conversation_14_d = {
randomize_indexes_n = 0,
sound_events_n = 1,
sound_events = {
[1] = "loc_ogryn_b__adamant_female_a_ogryn_bonding_conversation_14_d_01",
},
sound_events_duration = {
[1] = 2.517823,
},
randomize_indexes = {},
},
adamant_female_a_ogryn_bonding_conversation_15_b = {
randomize_indexes_n = 0,
sound_events_n = 1,
sound_events = {
[1] = "loc_ogryn_b__adamant_female_a_ogryn_bonding_conversation_15_b_01",
},
sound_events_duration = {
[1] = 2.80175,
},
randomize_indexes = {},
},
adamant_female_a_ogryn_bonding_conversation_15_d = {
randomize_indexes_n = 0,
sound_events_n = 1,
sound_events = {
[1] = "loc_ogryn_b__adamant_female_a_ogryn_bonding_conversation_15_d_01",
},
sound_events_duration = {
[1] = 3.41099,
},
randomize_indexes = {},
},
}
return settings("adamant_female_a_ogryn_b", adamant_female_a_ogryn_b)
| 412 | 0.520867 | 1 | 0.520867 | game-dev | MEDIA | 0.1763 | game-dev | 0.779064 | 1 | 0.779064 |
electronicarts/CnC_Modding_Support | 7,273 | Kanes Wrath/Xml/SkirmishAI/Personalities/GDIOverlord.xml | <?xml version="1.0" encoding="utf-8"?>
<AssetDeclaration xmlns="uri:ea.com:eala:asset" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Tags></Tags>
<Includes></Includes>
<AIPersonalityDefinition
id="5GDIOverlord"
PersonalityType="5GDIOverlord"
PersonalityUIName="Personality:Overlord"
SkirmishPersonality="true"
SecondsTillTargetsCanExpire="15.0"
ChanceForTargetToExpire="100"
MaxBuildingsToBeDefensiveTarget_Small="0"
MaxBuildingsToBeDefensiveTarget_Med="0"
ChanceForUnitsToUpgrade="100"
ChanceToUseAllUnitsForDefenseTarget_Small="0"
ChanceToUseAllUnitsForDefenseTarget_Med="0"
ChanceToUseAllUnitsForDefenseTarget_Large="0"
DesiredExcessPowerBuffer="10"
BaseCompactness="0.65"
DefaultThreatFindRadius="0"
UnitBuilderCostEffectivenessWeight="1.0"
UnitBuilderMoneyVersusTimePreference="0.5"
UnitBuilderOverallOffensivePreference="100%"
UnitBuilderOverallDefensivePreference="110%"
Expansion_TiberiumSearchRadius="1000"
Expansion_MaxTiberiumRemaining="999999"
ReactiveDefenseRadius="1000"
RepairBuildingsAtDifficulty="MEDIUM HARD BRUTAL"
EmergencyManagerHandleNoPowerAtDifficulty="MEDIUM HARD BRUTAL"
EmergencyManagerHandleNoIncomeAtDifficulty="EASY MEDIUM HARD BRUTAL"
EmergencyManagerHandleNoConyardAtDifficulty="EASY MEDIUM HARD BRUTAL"
StructureSaveChanceEasy="0.0"
StructureSaveChanceMedium="0.01"
StructureSaveChanceHard="1.0"
>
<Side>GDI</Side>
<BuildDelayRange MinDelay="0s" MaxDelay="60s" MinTTKRatio="0.5" MaxTTKRatio="1.5" Difficulty="EASY" />
<BuildDelayRange MinDelay="0s" MaxDelay="30s" MinTTKRatio="0.5" MaxTTKRatio="1.5" Difficulty="MEDIUM" />
<UnitBuilderUnitChoiceStrategy Shape="BEST" StandardDeviation="0.25" Difficulty="HARD BRUTAL" />
<UnitBuilderUnitChoiceStrategyAdaptive
MinEffectiveness="0.5" MaxEffectiveness="1.0"
MinStandardDeviation="2.0" MaxStandardDeviation="0.5"
MinEfficiency="1.0" MaxEfficiency="2.0"
Difficulty="EASY"
/>
<UnitBuilderUnitChoiceStrategyAdaptive
MinEffectiveness="0.0" MaxEffectiveness="0.5"
MinStandardDeviation="0.25" MaxStandardDeviation="2.0"
MinEfficiency="0.75" MaxEfficiency="1.0"
Difficulty="MEDIUM"
/>
<UnitBuilderEvaluationDelayRange
UseAllAvailableQueues="false"
MinDelay="180s" MaxDelay="180s"
MinEfficiency="1.0" MaxEfficiency="1.0"
Difficulty="EASY"
/>
<UnitBuilderEvaluationDelayRange
UseAllAvailableQueues="true"
MinDelay="10s" MaxDelay="60s"
MinEfficiency="0.75" MaxEfficiency="1.0"
Difficulty="MEDIUM"
/>
<ResourceMultiplierCheat Percentage="200%" Difficulty="BRUTAL"/>
<TacticalTarget TacticalAITarget="PrimaryTarget" MaxTeamsPerTarget="1"/>
<TacticalTarget TacticalAITarget="PrimaryTarget" MaxTeamsPerTarget="1"/>
<TacticalTarget TacticalAITarget="PrimaryTarget" MaxTeamsPerTarget="1"/>
<TacticalTarget TacticalAITarget="PrimaryTarget" MaxTeamsPerTarget="1"/>
<TacticalTarget TacticalAITarget="SpecialDefense" MaxTeamsPerTarget="1"/>
<TacticalTarget TacticalAITarget="SpecialDefense" MaxTeamsPerTarget="1"/>
<TacticalTarget TacticalAITarget="ExpansionDefense" MaxTeamsPerTarget="1"/>
<TacticalTarget TacticalAITarget="CaptureTech" MaxTeamsPerTarget="1"/>
<TacticalTarget TacticalAITarget="CaptureTech" MaxTeamsPerTarget="1"/>
<TacticalTarget TacticalAITarget="Superweapon" MaxTeamsPerTarget="1"/>
<TacticalTarget TacticalAITarget="Expansion" MaxTeamsPerTarget="1" UpdateTime="10s"/>
<TacticalTarget TacticalAITarget="Bridge" MaxTeamsPerTarget="1"/>
<TacticalTarget TacticalAITarget="Isolation" MaxTeamsPerTarget="1"/>
<TacticalTarget TacticalAITarget="Isolation" MaxTeamsPerTarget="1"/>
<TacticalTarget TacticalAITarget="Beacon" MaxTeamsPerTarget="1"/>
<TacticalTarget TacticalAITarget="Crate" MaxTeamsPerTarget="1"/>
<TacticalTarget TacticalAITarget="Husk" MaxTeamsPerTarget="1"/>
<TacticalTarget TacticalAITarget="Husk" MaxTeamsPerTarget="1"/>
<OpeningMove Name="GDI_EASY" Weight="100%" Difficulty="EASY"/>
<OpeningMove Name="GDIStandard" Weight="20%" Difficulty="MEDIUM HARD"/>
<OpeningMove Name="GDIStandard2" Weight="20%" Difficulty="MEDIUM HARD"/>
<OpeningMove Name="GDIStandardCrane" Weight="20%" Difficulty="MEDIUM HARD"/>
<OpeningMove Name="GDIZoneTrooperRush" Weight="10%" Difficulty="MEDIUM HARD"/>
<OpeningMove Name="GDIMegaUnitRush" Weight="30%" Difficulty="MEDIUM HARD"/>
<OpeningMove Name="GDIBrutalCrane" Weight="90%" Difficulty="BRUTAL"/>
<OpeningMove Name="GDIZoneTrooperRush" Weight="10%" Difficulty="BRUTAL"/>
<States State="GDIOverrunEarly" Difficulty="EASY MEDIUM HARD BRUTAL" />
<States State="GDIOverrunMiddle" Difficulty="EASY MEDIUM HARD BRUTAL" />
<States State="GDIOverrunLate" Difficulty="EASY MEDIUM HARD BRUTAL" />
<States State="Overlord_EASY" Difficulty="EASY" />
<States State="GDIReactiveDefense" Difficulty="EASY MEDIUM HARD BRUTAL"/>
<States State="GDIEngineerDefense" Difficulty="HARD BRUTAL"/>
<States State="GDICommandoDefense" Difficulty="HARD BRUTAL"/>
<States State="ExpansionDefense" Difficulty="EASY MEDIUM HARD BRUTAL"/>
<States State="GDIOverlordExpansion" Difficulty="MEDIUM HARD BRUTAL"/>
<States State="GDICaptureTech" Difficulty="MEDIUM HARD BRUTAL"/>
<States State="GDISuperweapon" Difficulty="MEDIUM HARD BRUTAL"/>
<States State="GDIBridgeRepair" Difficulty="EASY MEDIUM HARD BRUTAL"/>
<States State="GDIIsolation" Difficulty="EASY MEDIUM HARD BRUTAL"/>
<States State="GDIHuskCapture" Difficulty="MEDIUM HARD BRUTAL"/>
<States State="BeaconHelp" Difficulty="EASY MEDIUM HARD BRUTAL"/>
<States State="CratePickup" Difficulty="HARD BRUTAL"/>
<States State="GDIUnitPreferences" Difficulty="MEDIUM HARD BRUTAL"/>
<BudgetStates State="OpeningMoveBudget" Difficulty="EASY MEDIUM HARD BRUTAL"/>
<BudgetStates State="OffensiveEarlyGameBudget" Difficulty="EASY MEDIUM HARD BRUTAL"/>
<BudgetStates State="OffensiveMidGameBudget" Difficulty="EASY MEDIUM HARD BRUTAL"/>
<BudgetStates State="OffensiveLateGameBudget" Difficulty="EASY MEDIUM HARD BRUTAL"/>
<BudgetStates State="FullInvestmentBudget" Difficulty="HARD BRUTAL"/>
<BudgetStates State="FullInvestmentBudget_EASY_WINNING" Difficulty="EASY"/>
<BudgetStates State="FullInvestmentBudget_MEDIUM_WINNING" Difficulty="MEDIUM"/>
<BudgetStates State="FullInvestmentBudget_MEDIUM_LOSING" Difficulty="MEDIUM"/>
<BudgetStates State="InvestmentFinishBudget" Difficulty="EASY MEDIUM HARD BRUTAL"/>
<BudgetStates State="GDIOverlordTechByTimeBudget" Difficulty="HARD BRUTAL"/>
<BudgetStates State="GDIOverlordTechByTimeBudget_EASY" Difficulty="EASY"/>
<BudgetStates State="GDIOverlordTechByTimeBudget_MEDIUM" Difficulty="MEDIUM"/>
<BudgetStates State="TechByMoneyBudget" Difficulty="MEDIUM HARD BRUTAL"/>
<BudgetStates State="TechByNeedAntiGarrisonBudget" Difficulty="MEDIUM HARD BRUTAL"/>
<BudgetStates State="TechByNeedSiegeBudget" Difficulty="MEDIUM HARD BRUTAL"/>
<BudgetStates State="TechFinishBudget" Difficulty="EASY MEDIUM HARD BRUTAL"/>
</AIPersonalityDefinition>
</AssetDeclaration>
| 412 | 0.730841 | 1 | 0.730841 | game-dev | MEDIA | 0.963089 | game-dev | 0.879358 | 1 | 0.879358 |
eooce/NanoLimbo | 3,738 | src/main/java/ua/nanit/limbo/server/data/BossBar.java | /*
* Copyright (C) 2020 Nan1t
*
* 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 <https://www.gnu.org/licenses/>.
*/
package ua.nanit.limbo.server.data;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.serialize.SerializationException;
import org.spongepowered.configurate.serialize.TypeSerializer;
import ua.nanit.limbo.protocol.NbtMessage;
import ua.nanit.limbo.util.Colors;
import ua.nanit.limbo.util.NbtMessageUtil;
import java.lang.reflect.Type;
public class BossBar {
private NbtMessage text;
private float health;
private Color color;
private Division division;
public NbtMessage getText() {
return text;
}
public float getHealth() {
return health;
}
public Color getColor() {
return color;
}
public Division getDivision() {
return division;
}
public void setText(NbtMessage text) {
this.text = text;
}
public void setHealth(float health) {
this.health = health;
}
public void setColor(Color color) {
this.color = color;
}
public void setDivision(Division division) {
this.division = division;
}
public enum Color {
PINK(0),
BLUE(1),
RED(2),
GREEN(3),
YELLOW(4),
PURPLE(5),
WHITE(6);
private final int index;
Color(int index) {
this.index = index;
}
public int getIndex() {
return index;
}
}
public enum Division {
SOLID(0),
DASHES_6(1),
DASHES_10(2),
DASHES_12(3),
DASHES_20(4);
private final int index;
Division(int index) {
this.index = index;
}
public int getIndex() {
return index;
}
}
public static class Serializer implements TypeSerializer<BossBar> {
@Override
public BossBar deserialize(Type type, ConfigurationNode node) throws SerializationException {
BossBar bossBar = new BossBar();
bossBar.setText(NbtMessageUtil.create(Colors.of(node.node("text").getString(""))));
bossBar.setHealth(node.node("health").getFloat());
if (bossBar.getHealth() < 0 || bossBar.getHealth() > 1)
throw new SerializationException("BossBar health value must be between 0.0 and 1.0");
try {
bossBar.setColor(Color.valueOf(node.node("color").getString("").toUpperCase()));
} catch (IllegalArgumentException e) {
throw new SerializationException("Invalid bossbar color");
}
try {
bossBar.setDivision(Division.valueOf(node.node("division").getString("").toUpperCase()));
} catch (IllegalArgumentException e) {
throw new SerializationException("Invalid bossbar division");
}
return bossBar;
}
@Override
public void serialize(Type type, @Nullable BossBar obj, ConfigurationNode node) {
}
}
}
| 412 | 0.576577 | 1 | 0.576577 | game-dev | MEDIA | 0.912909 | game-dev | 0.943956 | 1 | 0.943956 |
elefant-ai/chatclef | 1,876 | src/main/java/adris/altoclef/tasks/resources/CollectNetherBricksTask.java | package adris.altoclef.tasks.resources;
import adris.altoclef.AltoClef;
import adris.altoclef.tasks.CraftInInventoryTask;
import adris.altoclef.tasks.ResourceTask;
import adris.altoclef.tasksystem.Task;
import adris.altoclef.util.CraftingRecipe;
import adris.altoclef.util.ItemTarget;
import adris.altoclef.util.MiningRequirement;
import adris.altoclef.util.RecipeTarget;
import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import net.minecraft.item.Items;
public class CollectNetherBricksTask extends ResourceTask {
private final int _count;
public CollectNetherBricksTask(int count) {
super(Items.NETHER_BRICKS, count);
_count = count;
}
@Override
protected boolean shouldAvoidPickingUp(AltoClef mod) {
return false;
}
@Override
protected void onResourceStart(AltoClef mod) {
}
@Override
protected Task onResourceTick(AltoClef mod) {
/*
* If we find nether bricks, mine them.
*
* Otherwise craft them from the "nether_brick" item.
*/
if (mod.getBlockScanner().anyFound(Blocks.NETHER_BRICKS)) {
return new MineAndCollectTask(Items.NETHER_BRICKS, _count, new Block[]{Blocks.NETHER_BRICKS}, MiningRequirement.WOOD);
}
ItemTarget b = new ItemTarget(Items.NETHER_BRICK, 1);
return new CraftInInventoryTask(new RecipeTarget(Items.NETHER_BRICK, _count, CraftingRecipe.newShapedRecipe("nether_brick", new ItemTarget[]{b, b, b, b}, 1)));
}
@Override
protected void onResourceStop(AltoClef mod, Task interruptTask) {
}
@Override
protected boolean isEqualResource(ResourceTask other) {
return other instanceof CollectNetherBricksTask;
}
@Override
protected String toDebugStringName() {
return "Collecting " + _count + " nether bricks.";
}
}
| 412 | 0.841389 | 1 | 0.841389 | game-dev | MEDIA | 0.997233 | game-dev | 0.913248 | 1 | 0.913248 |
ProjectIgnis/CardScripts | 1,388 | unofficial/c511023012.lua | --Umbral Horror Will o' the Wisp
--fixed by MLD
local s,id=GetID()
function s.initial_effect(c)
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetTarget(s.lvtg)
e1:SetOperation(s.lvop)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
c:RegisterEffect(e2)
end
function s.filter(c,clv)
local lv=c:GetLevel()
return c:IsFaceup() and lv>0 and lv~=clv
end
function s.lvtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
local c=e:GetHandler()
if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_MZONE) and chkc~=c and s.filter(chkc,c:GetLevel()) end
if chk==0 then return Duel.IsExistingTarget(s.filter,tp,LOCATION_MZONE,0,1,c,c:GetLevel()) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET)
Duel.SelectTarget(tp,s.filter,tp,LOCATION_MZONE,0,1,1,c,c:GetLevel())
end
function s.lvop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if c:IsRelateToEffect(e) and c:IsFaceup() and tc and tc:IsRelateToEffect(e) and tc:IsFaceup() then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_LEVEL)
e1:SetValue(tc:GetLevel())
e1:SetReset(RESET_EVENT+RESETS_STANDARD_DISABLE)
c:RegisterEffect(e1)
end
end | 412 | 0.908273 | 1 | 0.908273 | game-dev | MEDIA | 0.972669 | game-dev | 0.923651 | 1 | 0.923651 |
HyperMC-Team/OpenRoxy | 3,696 | src/main/java/net/minecraft/item/ItemArmorStand.java | package net.minecraft.item;
import java.util.List;
import java.util.Random;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityArmorStand;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.MathHelper;
import net.minecraft.util.Rotations;
import net.minecraft.world.World;
public class ItemArmorStand
extends Item {
public ItemArmorStand() {
this.setCreativeTab(CreativeTabs.tabDecorations);
}
@Override
public boolean onItemUse(ItemStack stack, EntityPlayer playerIn, World worldIn, BlockPos pos, EnumFacing side, float hitX, float hitY, float hitZ) {
double d2;
double d1;
BlockPos blockpos;
if (side == EnumFacing.DOWN) {
return false;
}
boolean flag = worldIn.getBlockState(pos).getBlock().isReplaceable(worldIn, pos);
BlockPos blockPos = blockpos = flag ? pos : pos.offset(side);
if (!playerIn.canPlayerEdit(blockpos, side, stack)) {
return false;
}
BlockPos blockpos1 = blockpos.up();
boolean flag1 = !worldIn.isAirBlock(blockpos) && !worldIn.getBlockState(blockpos).getBlock().isReplaceable(worldIn, blockpos);
if (flag1 |= !worldIn.isAirBlock(blockpos1) && !worldIn.getBlockState(blockpos1).getBlock().isReplaceable(worldIn, blockpos1)) {
return false;
}
double d0 = blockpos.getX();
List<Entity> list = worldIn.getEntitiesWithinAABBExcludingEntity(null, AxisAlignedBB.fromBounds(d0, d1 = (double)blockpos.getY(), d2 = (double)blockpos.getZ(), d0 + 1.0, d1 + 2.0, d2 + 1.0));
if (list.size() > 0) {
return false;
}
if (!worldIn.isRemote) {
worldIn.setBlockToAir(blockpos);
worldIn.setBlockToAir(blockpos1);
EntityArmorStand entityarmorstand = new EntityArmorStand(worldIn, d0 + 0.5, d1, d2 + 0.5);
float f = (float)MathHelper.floor_float((MathHelper.wrapAngleTo180_float(playerIn.rotationYaw - 180.0f) + 22.5f) / 45.0f) * 45.0f;
entityarmorstand.setLocationAndAngles(d0 + 0.5, d1, d2 + 0.5, f, 0.0f);
this.applyRandomRotations(entityarmorstand, worldIn.rand);
NBTTagCompound nbttagcompound = stack.getTagCompound();
if (nbttagcompound != null && nbttagcompound.hasKey("EntityTag", 10)) {
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
entityarmorstand.writeToNBTOptional(nbttagcompound1);
nbttagcompound1.merge(nbttagcompound.getCompoundTag("EntityTag"));
entityarmorstand.readFromNBT(nbttagcompound1);
}
worldIn.spawnEntityInWorld(entityarmorstand);
}
--stack.stackSize;
return true;
}
private void applyRandomRotations(EntityArmorStand armorStand, Random rand) {
Rotations rotations = armorStand.getHeadRotation();
float f = rand.nextFloat() * 5.0f;
float f1 = rand.nextFloat() * 20.0f - 10.0f;
Rotations rotations1 = new Rotations(rotations.getX() + f, rotations.getY() + f1, rotations.getZ());
armorStand.setHeadRotation(rotations1);
rotations = armorStand.getBodyRotation();
f = rand.nextFloat() * 10.0f - 5.0f;
rotations1 = new Rotations(rotations.getX(), rotations.getY() + f, rotations.getZ());
armorStand.setBodyRotation(rotations1);
}
}
| 412 | 0.944272 | 1 | 0.944272 | game-dev | MEDIA | 0.998664 | game-dev | 0.973173 | 1 | 0.973173 |
frankfenghua/ios | 10,607 | Creating Games with cocos2d for iPhone/9007OS_Code bundle/Chapter 05 -Brick/ch5-brick/libs/Box2D/Dynamics/b2World.h | /*
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef B2_WORLD_H
#define B2_WORLD_H
#include <Box2D/Common/b2Math.h>
#include <Box2D/Common/b2BlockAllocator.h>
#include <Box2D/Common/b2StackAllocator.h>
#include <Box2D/Dynamics/b2ContactManager.h>
#include <Box2D/Dynamics/b2WorldCallbacks.h>
#include <Box2D/Dynamics/b2TimeStep.h>
struct b2AABB;
struct b2BodyDef;
struct b2Color;
struct b2JointDef;
class b2Body;
class b2Draw;
class b2Fixture;
class b2Joint;
/// The world class manages all physics entities, dynamic simulation,
/// and asynchronous queries. The world also contains efficient memory
/// management facilities.
class b2World
{
public:
/// Construct a world object.
/// @param gravity the world gravity vector.
b2World(const b2Vec2& gravity);
/// Destruct the world. All physics entities are destroyed and all heap memory is released.
~b2World();
/// Register a destruction listener. The listener is owned by you and must
/// remain in scope.
void SetDestructionListener(b2DestructionListener* listener);
/// Register a contact filter to provide specific control over collision.
/// Otherwise the default filter is used (b2_defaultFilter). The listener is
/// owned by you and must remain in scope.
void SetContactFilter(b2ContactFilter* filter);
/// Register a contact event listener. The listener is owned by you and must
/// remain in scope.
void SetContactListener(b2ContactListener* listener);
/// Register a routine for debug drawing. The debug draw functions are called
/// inside with b2World::DrawDebugData method. The debug draw object is owned
/// by you and must remain in scope.
void SetDebugDraw(b2Draw* debugDraw);
/// Create a rigid body given a definition. No reference to the definition
/// is retained.
/// @warning This function is locked during callbacks.
b2Body* CreateBody(const b2BodyDef* def);
/// Destroy a rigid body given a definition. No reference to the definition
/// is retained. This function is locked during callbacks.
/// @warning This automatically deletes all associated shapes and joints.
/// @warning This function is locked during callbacks.
void DestroyBody(b2Body* body);
/// Create a joint to constrain bodies together. No reference to the definition
/// is retained. This may cause the connected bodies to cease colliding.
/// @warning This function is locked during callbacks.
b2Joint* CreateJoint(const b2JointDef* def);
/// Destroy a joint. This may cause the connected bodies to begin colliding.
/// @warning This function is locked during callbacks.
void DestroyJoint(b2Joint* joint);
/// Take a time step. This performs collision detection, integration,
/// and constraint solution.
/// @param timeStep the amount of time to simulate, this should not vary.
/// @param velocityIterations for the velocity constraint solver.
/// @param positionIterations for the position constraint solver.
void Step( float32 timeStep,
int32 velocityIterations,
int32 positionIterations);
/// Manually clear the force buffer on all bodies. By default, forces are cleared automatically
/// after each call to Step. The default behavior is modified by calling SetAutoClearForces.
/// The purpose of this function is to support sub-stepping. Sub-stepping is often used to maintain
/// a fixed sized time step under a variable frame-rate.
/// When you perform sub-stepping you will disable auto clearing of forces and instead call
/// ClearForces after all sub-steps are complete in one pass of your game loop.
/// @see SetAutoClearForces
void ClearForces();
/// Call this to draw shapes and other debug draw data.
void DrawDebugData();
/// Query the world for all fixtures that potentially overlap the
/// provided AABB.
/// @param callback a user implemented callback class.
/// @param aabb the query box.
void QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) const;
/// Ray-cast the world for all fixtures in the path of the ray. Your callback
/// controls whether you get the closest point, any point, or n-points.
/// The ray-cast ignores shapes that contain the starting point.
/// @param callback a user implemented callback class.
/// @param point1 the ray starting point
/// @param point2 the ray ending point
void RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const;
/// Get the world body list. With the returned body, use b2Body::GetNext to get
/// the next body in the world list. A NULL body indicates the end of the list.
/// @return the head of the world body list.
b2Body* GetBodyList();
const b2Body* GetBodyList() const;
/// Get the world joint list. With the returned joint, use b2Joint::GetNext to get
/// the next joint in the world list. A NULL joint indicates the end of the list.
/// @return the head of the world joint list.
b2Joint* GetJointList();
const b2Joint* GetJointList() const;
/// Get the world contact list. With the returned contact, use b2Contact::GetNext to get
/// the next contact in the world list. A NULL contact indicates the end of the list.
/// @return the head of the world contact list.
/// @warning contacts are created and destroyed in the middle of a time step.
/// Use b2ContactListener to avoid missing contacts.
b2Contact* GetContactList();
const b2Contact* GetContactList() const;
/// Enable/disable sleep.
void SetAllowSleeping(bool flag);
bool GetAllowSleeping() const { return m_allowSleep; }
/// Enable/disable warm starting. For testing.
void SetWarmStarting(bool flag) { m_warmStarting = flag; }
bool GetWarmStarting() const { return m_warmStarting; }
/// Enable/disable continuous physics. For testing.
void SetContinuousPhysics(bool flag) { m_continuousPhysics = flag; }
bool GetContinuousPhysics() const { return m_continuousPhysics; }
/// Enable/disable single stepped continuous physics. For testing.
void SetSubStepping(bool flag) { m_subStepping = flag; }
bool GetSubStepping() const { return m_subStepping; }
/// Get the number of broad-phase proxies.
int32 GetProxyCount() const;
/// Get the number of bodies.
int32 GetBodyCount() const;
/// Get the number of joints.
int32 GetJointCount() const;
/// Get the number of contacts (each may have 0 or more contact points).
int32 GetContactCount() const;
/// Get the height of the dynamic tree.
int32 GetTreeHeight() const;
/// Get the balance of the dynamic tree.
int32 GetTreeBalance() const;
/// Get the quality metric of the dynamic tree. The smaller the better.
/// The minimum is 1.
float32 GetTreeQuality() const;
/// Change the global gravity vector.
void SetGravity(const b2Vec2& gravity);
/// Get the global gravity vector.
b2Vec2 GetGravity() const;
/// Is the world locked (in the middle of a time step).
bool IsLocked() const;
/// Set flag to control automatic clearing of forces after each time step.
void SetAutoClearForces(bool flag);
/// Get the flag that controls automatic clearing of forces after each time step.
bool GetAutoClearForces() const;
/// Get the contact manager for testing.
const b2ContactManager& GetContactManager() const;
/// Get the current profile.
const b2Profile& GetProfile() const;
/// Dump the world into the log file.
/// @warning this should be called outside of a time step.
void Dump();
private:
// m_flags
enum
{
e_newFixture = 0x0001,
e_locked = 0x0002,
e_clearForces = 0x0004
};
friend class b2Body;
friend class b2Fixture;
friend class b2ContactManager;
friend class b2Controller;
void Solve(const b2TimeStep& step);
void SolveTOI(const b2TimeStep& step);
void DrawJoint(b2Joint* joint);
void DrawShape(b2Fixture* shape, const b2Transform& xf, const b2Color& color);
b2BlockAllocator m_blockAllocator;
b2StackAllocator m_stackAllocator;
int32 m_flags;
b2ContactManager m_contactManager;
b2Body* m_bodyList;
b2Joint* m_jointList;
int32 m_bodyCount;
int32 m_jointCount;
b2Vec2 m_gravity;
bool m_allowSleep;
b2DestructionListener* m_destructionListener;
b2Draw* m_debugDraw;
// This is used to compute the time step ratio to
// support a variable time step.
float32 m_inv_dt0;
// These are for debugging the solver.
bool m_warmStarting;
bool m_continuousPhysics;
bool m_subStepping;
bool m_stepComplete;
b2Profile m_profile;
};
inline b2Body* b2World::GetBodyList()
{
return m_bodyList;
}
inline const b2Body* b2World::GetBodyList() const
{
return m_bodyList;
}
inline b2Joint* b2World::GetJointList()
{
return m_jointList;
}
inline const b2Joint* b2World::GetJointList() const
{
return m_jointList;
}
inline b2Contact* b2World::GetContactList()
{
return m_contactManager.m_contactList;
}
inline const b2Contact* b2World::GetContactList() const
{
return m_contactManager.m_contactList;
}
inline int32 b2World::GetBodyCount() const
{
return m_bodyCount;
}
inline int32 b2World::GetJointCount() const
{
return m_jointCount;
}
inline int32 b2World::GetContactCount() const
{
return m_contactManager.m_contactCount;
}
inline void b2World::SetGravity(const b2Vec2& gravity)
{
m_gravity = gravity;
}
inline b2Vec2 b2World::GetGravity() const
{
return m_gravity;
}
inline bool b2World::IsLocked() const
{
return (m_flags & e_locked) == e_locked;
}
inline void b2World::SetAutoClearForces(bool flag)
{
if (flag)
{
m_flags |= e_clearForces;
}
else
{
m_flags &= ~e_clearForces;
}
}
/// Get the flag that controls automatic clearing of forces after each time step.
inline bool b2World::GetAutoClearForces() const
{
return (m_flags & e_clearForces) == e_clearForces;
}
inline const b2ContactManager& b2World::GetContactManager() const
{
return m_contactManager;
}
inline const b2Profile& b2World::GetProfile() const
{
return m_profile;
}
#endif
| 412 | 0.880631 | 1 | 0.880631 | game-dev | MEDIA | 0.927675 | game-dev | 0.768988 | 1 | 0.768988 |
k4ntz/OC_Atari | 4,597 | ocatari/vision/battlezone.py | from .game_objects import GameObject
from .utils import find_objects, find_mc_objects, most_common_color
import numpy as np
objects_colors = {"player": [[26, 102, 26], [111, 111, 111], [74, 74, 74]], "radar": [111, 210, 111], "radar_hud": [236, 236, 236], "tank_blue1": [24, 80, 128],
"tank_blue2": [66, 136, 176], "tank_grey": [142, 142, 142], "tank_grey2": [170, 170, 170], "tank_yellow": [195, 144, 61],
"crosshair1": [0, 0, 0], "crosshair2": [236, 200, 96], "red": [[228, 111, 111], [200, 72, 72], [148, 0, 0]], "hud_green": [45, 129, 105],
"boss_yellow": [223, 183, 85]}
# "red": [[228, 111, 111], [214, 92, 92], [200, 72, 72], [184, 50, 50], [167, 26, 26], [148, 0, 0]]}
class Player(GameObject):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.rgb = [26, 102, 26]
class Crosshair(GameObject):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.rgb = [0, 0, 0]
class Shot(GameObject):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.rgb = [236, 236, 236]
class Radar(GameObject):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.rgb = [111, 210, 111]
class Radar_Content(GameObject):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.rgb = [236, 236, 236]
class Blue_Tank(GameObject):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.rgb = [66, 136, 176]
class Yellow_Blue_Tank(GameObject):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.rgb = [195, 144, 61]
class Red_Thing(GameObject):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.rgb = [200, 72, 72]
class Boss(GameObject):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.rgb = [223, 183, 85]
# ---- HUD -----
class Score(GameObject):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.rgb = [252, 252, 84]
class Life(GameObject):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.rgb = [252, 252, 84]
def _detect_objects(objects, obs, hud=False):
objects.clear()
player = find_mc_objects(obs, objects_colors["player"], miny=110, maxy=178)
for bb in player:
objects.append(Player(*bb))
shot = find_objects(obs, objects_colors["radar_hud"], miny=70, maxy=175)
for bb in shot:
objects.append(Shot(*bb))
crosshair = find_objects(
obs, objects_colors["crosshair1"], miny=79, maxy=175, size=(1, 6), tol_s=1)
for bb in crosshair:
objects.append(Crosshair(*bb))
crosshair = find_objects(
obs, objects_colors["crosshair2"], miny=79, maxy=175, size=(1, 6), tol_s=1)
for bb in crosshair:
cr = Crosshair(*bb)
cr.rgb = objects_colors["crosshair2"]
objects.append(cr)
radar = find_objects(obs, objects_colors["radar"], maxy=36)
for bb in radar:
objects.append(Radar(*bb))
radar_c = find_objects(
obs, objects_colors["radar_hud"], maxy=37, size=(1, 1), tol_s=1)
for bb in radar_c:
objects.append(Radar_Content(*bb))
blue = find_mc_objects(obs, [objects_colors["tank_blue1"],
objects_colors["tank_blue2"], objects_colors["tank_grey"]], miny=78, maxy=175)
for bb in blue:
objects.append(Blue_Tank(*bb))
yellow = find_mc_objects(obs, [objects_colors["tank_blue1"],
objects_colors["tank_yellow"], objects_colors["tank_grey2"]], miny=78, maxy=175)
for bb in yellow:
objects.append(Yellow_Blue_Tank(*bb))
red = find_mc_objects(
obs, objects_colors["red"], miny=78, maxy=175, closing_dist=5)
for bb in red:
objects.append(Red_Thing(*bb))
boss = find_mc_objects(
obs, [objects_colors["boss_yellow"], objects_colors["crosshair1"]], miny=78, maxy=175)
for bb in boss:
if bb[2] > 1:
objects.append(Boss(*bb))
if hud:
score = find_objects(
obs, objects_colors["hud_green"], closing_dist=4, miny=178, maxy=188)
for bb in score:
objects.append(Score(*bb))
lives = find_objects(
obs, objects_colors["hud_green"], miny=188, closing_dist=1)
for bb in lives:
objects.append(Life(*bb))
| 412 | 0.733469 | 1 | 0.733469 | game-dev | MEDIA | 0.436266 | game-dev | 0.754306 | 1 | 0.754306 |
kesava-wow/kuinameplates2 | 22,583 | Kui_Nameplates_Core_Config/locale/enGB.lua | -- luacheck:globals KuiNameplatesCoreConfig
local L = KuiNameplatesCoreConfig:Locale('enGB')
if not L then return end
L.common = {
text = 'Text',
size = 'Size',
font_size = 'Font size',
point = 'Point',
point_x = 'X point',
point_y = 'Y point',
offset_x = 'X offset',
offset_y = 'Y offset',
position = 'Position',
width = 'Width',
height = 'Height',
offset = 'Offset',
layout = 'Layout',
page = 'Page',
profile = 'Profile',
copy = 'Copy',
paste = 'Paste',
reset = 'Reset',
rename = 'Rename',
delete = 'Delete',
}
L.page_names = {
general = 'General',
fade_rules = 'Fade rules',
healthbars = 'Health bars',
castbars = 'Cast bars',
text = 'Text',
nameonly = 'Name-only',
framesizes = 'Frame sizes',
auras = 'Auras',
classpowers = 'Class powers',
threat = 'Threat',
bossmod = 'Boss mods',
cvars = 'CVars',
}
L.titles = {
profile = 'Profile',
new_profile = 'New profile...',
new_profile_label = 'Enter profile name',
delete_profile_title = 'Delete profile',
delete_profile_label = 'Delete profile |cffffffff%s|r?',
reset_profile_title = 'Reset profile',
reset_profile_label = 'Reset profile |cffffffff%s|r?',
rename_profile_title = 'Rename profile',
rename_profile_label = 'Enter new name for |cffffffff%s',
copy_profile_title = 'Copy profile',
copy_profile_label = 'Enter name for new profile',
reset_page_label = 'Reset all options in |cffffffff%s|r?',
paste_page_label = 'Copy |cffffffff%s|r settings from |cffffffff%s|r to |cffffffff%s|r?',
version = '%s by %s at %s|nVersion %s',
bar_texture = 'Bar texture',
bar_animation = 'Bar animation',
dd_bar_animation_smooth = 'Smooth',
dd_bar_animation_cutaway = 'Cutaway',
combat_hostile = 'Combat action: hostile',
combat_friendly = 'Combat action: friendly',
dd_combat_toggle_nothing = 'Do nothing',
dd_combat_toggle_hide = 'Hide, then show',
dd_combat_toggle_show = 'Show, then hide',
ignore_uiscale = 'Pixel correction',
use_blizzard_personal = 'Ignore personal nameplate',
use_blizzard_powers = 'Show default class powers',
clickthrough_sep = 'Clickthrough frames',
clickthrough_self = 'Personal',
clickthrough_friend = 'Friendly',
clickthrough_enemy = 'Enemy',
nameonly = 'Use name-only mode',
nameonly_no_font_style = 'No text outline',
nameonly_health_colour = 'Health colour',
nameonly_damaged_friends = 'Damaged',
nameonly_damaged_enemies = 'Damaged',
nameonly_friends = 'Friendly NPCs',
nameonly_friendly_players = 'Friendly players',
nameonly_enemies = 'Hostile NPCs',
nameonly_hostile_players = 'Hostile players',
nameonly_target = 'Target',
nameonly_all_enemies = 'Attackable',
nameonly_neutral = 'Neutral enemies',
nameonly_combat_friends = 'In combat',
nameonly_combat_hostile = 'In combat',
nameonly_combat_hostile_player = 'With you',
guild_text_npcs = 'Show NPC titles',
guild_text_players = 'Show player guilds',
title_text_players = 'Show player titles',
nameonly_visibility_sep = 'Use name-only mode on...',
glow_as_shadow = 'Frame shadow',
state_icons = 'Rare/boss icon',
target_glow = 'Target glow',
target_glow_colour = 'Target glow colour',
mouseover_glow = 'Mouseover glow',
mouseover_glow_colour = 'Mouseover glow colour',
mouseover_highlight = 'Mouseover highlight',
target_arrows = 'Target arrows',
frame_glow_size = 'Frame glow size',
target_arrows_size = 'Target arrow size',
fade_avoid_sep = 'Don\'t fade...',
fade_non_target_alpha = 'Non-target alpha',
fade_conditional_alpha = 'Conditional alpha',
fade_speed = 'Animation speed',
fade_all = 'Fade out by default',
fade_friendly_npc = 'Fade friendly NPCs',
fade_neutral_enemy = 'Fade neutral enemies',
fade_untracked = 'Fade non-tracked units',
fade_avoid_mouseover = 'Mouseover',
fade_avoid_nameonly = 'In name-only',
fade_avoid_raidicon = 'With raid icon',
fade_avoid_execute_friend = 'Low health friends',
fade_avoid_execute_hostile = 'Low health enemies',
fade_avoid_tracked = 'Tracked or in combat',
fade_avoid_combat = 'In combat',
fade_avoid_casting_friendly = 'Casting (friendly)',
fade_avoid_casting_hostile = 'Casting (hostile)',
fade_avoid_casting_interruptible = 'Interruptible',
fade_avoid_casting_uninterruptible = 'Uninterruptible',
reaction_colour_sep = 'Colours',
colour_hated = 'Hated',
colour_neutral = 'Neutral',
colour_friendly = 'Friendly',
colour_friendly_pet = 'Friendly player pet',
colour_tapped = 'Tapped',
colour_player_class = 'Class colour friendly players',
colour_player = 'Player',
colour_self_class = 'Class colour self',
colour_self = 'Self',
colour_enemy_class = 'Class colour hostile players',
colour_enemy_player = 'Hostile player',
colour_enemy_pet = 'Hostile player pet',
absorb_enable = 'Show absorbs',
absorb_striped = 'Striped absorb texture',
colour_absorb = 'Absorb overlay',
execute_sep = 'Execute range',
execute_enabled = 'Enable execute range',
execute_auto = 'Auto-detect range',
execute_colour = 'Execute colour',
execute_percent = 'Execute range',
font_face = 'Font face',
font_style = 'Font style',
dd_font_style_none = 'None',
dd_font_style_outline = 'Outline',
dd_font_style_shadow = 'Shadow',
dd_font_style_shadowandoutline = 'Shadow+Outline',
dd_font_style_monochrome = 'Monochrome',
font_size_normal = 'Normal font size',
font_size_small = 'Small font size',
name_text = 'Show name text',
hide_names = 'Hide non-tracked names',
level_text = 'Show level text',
level_nameonly = 'Show level',
health_text = 'Show health text',
name_vertical_offset = 'Name v.offset',
bot_vertical_offset = 'Level/health v.offset',
name_colour_sep = 'Name text colour',
name_colour_white_in_bar_mode = 'White names on health bar',
class_colour_friendly_names = 'Class colour friendly names',
class_colour_enemy_names = 'Class colour enemy names',
name_colour_player_friendly = 'Friendly player',
name_colour_player_hostile = 'Hostile player',
name_colour_npc_hostile = 'Hostile',
name_colour_npc_neutral = 'Neutral',
name_colour_npc_friendly = 'Friendly',
health_text_sep = 'Health text',
health_text_friend_max = 'Max. health friend',
health_text_friend_dmg = 'Damaged friend',
health_text_hostile_max = 'Max. health hostile',
health_text_hostile_dmg = 'Damaged hostile',
dd_health_text_current = 'Current',
dd_health_text_maximum = 'Maximum',
dd_health_text_percent = 'Percent',
dd_health_text_deficit = 'Deficit',
dd_health_text_blank = 'Blank',
dd_health_text_current_percent = 'Current + percent',
dd_health_text_current_deficit = 'Current + deficit',
frame_width_personal = 'Personal width',
frame_height_personal = 'Personal height',
frame_target_size = 'Target size',
frame_minus_size = 'Minus size',
powerbar_height = 'Power bar height',
global_scale = 'Global scale',
frame_glow_size_shadow = 'Shadow size',
frame_glow_size_target = 'Target glow size',
frame_glow_size_threat = 'Threat glow size',
frame_padding_x = 'Clickbox padding width',
frame_padding_y = 'Clickbox padding height',
auras_enabled = 'Show auras',
auras_on_personal = 'Show on personal frame',
auras_pulsate = 'Pulsate',
auras_centre = 'Centre align',
auras_sort = 'Sorting method',
dd_auras_sort_index = 'Aura index',
dd_auras_sort_time = 'Time remaining',
auras_show_all_self = 'Whitelist all own auras',
auras_hide_all_other = 'Blacklist all other auras',
auras_filtering_sep = 'Filtering',
auras_time_threshold = 'Timer threshold',
auras_kslc_hint = 'KuiSpellListConfig from Curse can be used to whitelist or blacklist auras from any caster.',
auras_icons_sep = 'Icons',
auras_icon_normal_size = 'Icon size (normal)',
auras_icon_minus_size = 'Icon size (minus)',
auras_icon_squareness = 'Icon squareness',
auras_colour_short = 'Short timer',
auras_colour_medium = 'Medium timer',
auras_colour_long = 'Long timer',
auras_show_purge = 'Show purge',
auras_purge_size = 'Icon size (purge)',
auras_purge_opposite = 'Purge on opposite',
auras_side = 'Side',
auras_offset = 'Vertical offset',
auras_cd_movable = 'Cooldown',
auras_count_movable = 'Count',
castbar_enable = 'Enable',
castbar_colour = 'Bar colour',
castbar_unin_colour = 'Uninterruptible colour',
castbar_showpersonal = 'On personal',
castbar_icon = 'Spell icon',
castbar_name = 'Spell name',
castbar_shield = 'Uninterruptible shield',
castbar_showall = 'On all nameplates',
castbar_showfriend = 'Friendly',
castbar_showenemy = 'Hostile',
castbar_animate = 'Animate',
castbar_animate_change_colour = 'Change colour',
castbar_height = 'Bar height',
castbar_name_vertical_offset = 'Spell name offset',
castbar_detach = 'Detach',
castbar_detach_combine = 'Overlay spell icon',
castbar_detach_nameonly = 'Show in name-only mode',
castbar_icon_side = 'Spell icon side',
tank_mode = 'Enable tank mode',
tankmode_force_enable = 'Force tank mode',
tankmode_force_offtank = 'Force off-tank detection',
threat_brackets = 'Threat indicators',
frame_glow_threat = 'Threat glow',
tankmode_colour_sep = 'Tank mode colours',
tankmode_tank_colour = 'Tanking',
tankmode_trans_colour = 'Transition',
tankmode_other_colour = 'Off-tank',
tankmode_glow_colour_sep = 'Threat colours',
tankmode_tank_glow_colour = 'Tanking',
tankmode_trans_glow_colour = 'Transition',
classpowers_enable = 'Show class resources',
classpowers_on_target = 'Show on target',
classpowers_on_friends = 'On friends',
classpowers_on_enemies = 'On enemies',
classpowers_size = 'Icon size',
classpowers_bar_width = 'Stagger bar width',
classpowers_bar_height = 'Stagger bar height',
classpowers_colour = 'Icon colour',
classpowers_colour_overflow = 'Overflow colour',
classpowers_colour_inactive = 'Inactive colour',
classpowers_colour_animacharged = 'Anima charged colour',
classpowers_colour_animacharged_active = 'Anima charged colour active',
bossmod_enable = 'Enable boss mod communication',
bossmod_control_visibility = 'Allow boss mods to control nameplate visibility',
bossmod_icon_size = 'Icon size',
bossmod_x_offset = 'Horizontal offset',
bossmod_y_offset = 'Vertical offset',
bossmod_clickthrough = 'Enable clickthrough when automatically shown',
cvar_enable = 'Allow Kui Nameplates to modify CVars',
cvar_show_friendly_npcs = 'Always show friendly NPCs\' nameplates',
cvar_name_only = 'Hide default health bar',
cvar_personal_show_always = 'Always show personal nameplate',
cvar_personal_show_combat = 'Show personal nameplate when in combat',
cvar_personal_show_target = 'Show personal nameplate with a target',
cvar_max_distance = 'Max render distance',
cvar_clamp_top = 'Clamp top',
cvar_clamp_bottom = 'Clamp bottom',
cvar_self_clamp_top = 'Self clamp top',
cvar_self_clamp_bottom = 'Self clamp bottom',
cvar_overlap_v = 'Vertical overlap',
cvar_disable_scale = 'Disable scaling',
cvar_disable_alpha = 'Disable fading',
cvar_self_alpha = 'Self alpha',
cvar_occluded_mult = 'Line-of-sight alpha',
show_quest_icon = 'Quest icon',
show_raid_icon = 'Raid icon',
}
L.tooltips = {
reload_hint = 'Requires a UI reload.',
bar_texture = 'The texture used for status bars (provided by LibSharedMedia)',
bar_animation = 'The style of animation to use on health/power bars',
combat_hostile = 'Action to take on hostile frames upon entering and leaving combat.',
combat_friendly = 'Action to take on friendly frames upon entering and leaving combat.',
ignore_uiscale = 'Fix pixel alignment issues related to interface scaling. Compensate for the size difference by adjusting /knp > frame sizes > global scale.|n|nYou\'ll also need to disable the nameplate scaling CVars.|n|nThis may be necessary even if you do not have UI scale enabled.',
use_blizzard_personal = 'Don\'t skin the personal resource display, which can be enabled in Interface > Names.',
state_icons = '(Hidden if level text is enabled)',
clickthrough_self = 'Disable the click-box of the personal nameplate',
clickthrough_friend = 'Disable the click-box of friendly nameplates',
clickthrough_enemy = 'Disable the click-box of enemy nameplates',
nameonly_no_font_style = 'Hide text outline when in name-only mode',
nameonly_health_colour = 'Partially colour text to represent health percentage',
nameonly_target = 'Allow your target to remain in name-only mode',
nameonly_all_enemies = 'Only applies to hostile NPCs',
nameonly_combat_hostile = 'Note that this doesn\'t apply to training dummies or other units which don\'t have a threat table',
guild_text_npcs = 'Such as Flight Master, Quartermaster, etc.',
target_indicators = 'Show indicators around your current target. These inherit the target glow colour set above.',
fade_non_target_alpha = 'Opacity other frames will fade to when you have a target.|n|nInvisible nameplates can still be clicked.',
fade_conditional_alpha = 'Opacity frames will fade to when matching one of the conditions below',
fade_speed = 'Speed of the frame fading animation, where 1 is slowest and 0 is instant',
fade_all = 'Fade all frames to the non-target alpha by default',
fade_friendly_npc = 'Fade friendly NPC nameplates by default (including those in name-only mode)',
fade_neutral_enemy = 'Fade attackable neutral nameplates by default (including those in name-only mode)',
fade_untracked = 'Fade non-tracked nameplates by default (including those in name-only mode).|n|nWhether or not a unit is tracked can by set by changing the "NPC Names" dropdown and other checkboxes in Interface > Names',
fade_avoid_execute_friend = 'Friendly nameplates in execute range',
fade_avoid_execute_hostile = 'Hostile nameplates in execute range',
fade_avoid_tracked = 'Whether or not a unit is tracked can by set by changing the "NPC Names" dropdown and other checkboxes in Interface > Names',
colour_self_class = 'Use your class colour on your personal nameplate',
colour_self = 'The health bar colour of your personal nameplate',
absorb_enable = 'Show an absorb overlay on health bars',
absorb_striped = 'Use a striped texture for the absorb overlay. If unchecked, inherit the health bar texture',
execute_enabled = 'Recolour health bars when units are within execute range',
execute_auto = 'Automatically detect the appropriate execute range from your talents, defaulting to 20% on a character with no execute',
execute_colour = 'Colour to use within execute range',
execute_percent = 'Manually set execute range',
colour_friendly_pet = 'Note that friendly pets do not generally have nameplates rendered',
colour_player = 'The colour of other friendly players\' health bars',
hide_names = 'Whether or not a unit is tracked can be set by changing the "NPC Names" dropdown and other checkboxes in Interface > Names.|n|nThis does not affect name-only mode.',
font_face = 'Fonts are provided by LibSharedMedia.',
font_size_normal = 'Used for name, level, health and auras.',
font_size_small = 'Used for guild and spell name.',
name_colour_white_in_bar_mode = '(Excluding player class colours)',
health_text_friend_max = 'Health text format used on friendly units at full health',
health_text_friend_dmg = 'Health text format used on damaged friendly units',
health_text_hostile_max = 'Health text format used on hostile units at full health',
health_text_hostile_dmg = 'Health text format used on damaged hostile units',
frame_minus_size = 'Alternate frame size for small mobs flagged as "minus"',
frame_target_size = 'Alternate frame size for the current target',
frame_width_personal = 'Width of personal resource display (enabled in Interface > Names)',
powerbar_height = 'Height of the power bar on the personal resource display',
global_scale = 'Scale all nameplates by this amount (obeying the pixel grid)',
auras_enabled = 'Buffs on friends, debuffs on enemies',
auras_on_personal = 'Show buffs on the personal resource display',
auras_pulsate = 'Pulsate icons when they are about to expire',
auras_show_all_self = 'Show all auras which you cast, rather than just those flagged as important by Blizzard',
auras_hide_all_other = 'Do not show auras cast by other players in the main aura frame (such as CC or slows)',
auras_time_threshold = 'Hide the timer above this number of seconds. Set to -1 to always show.',
auras_icon_normal_size = 'Icon size on normal-size frames',
auras_icon_minus_size = 'Icon size on smaller frames',
auras_icon_squareness = 'Size ratio of the aura icons, where 1 means a perfect square',
auras_colour_short = 'Under 5 seconds',
auras_colour_medium = 'Under 20 seconds',
auras_colour_long = 'Over 20 seconds',
auras_show_purge = 'Show buffs on enemies which you can spell steal, dispel, or purge',
auras_cd_size = 'Set to 0 to inherit \'normal\' font size',
auras_count_size = 'Set to 0 to inherit \'small\' font size',
castbar_enable = 'Enable the cast bar element',
castbar_showpersonal = 'Show the cast bar on the personal nameplate',
castbar_shield = 'Show a shield icon on the cast bar during casts which cannot be interrupted',
castbar_showall = 'Show cast bars on all nameplates, rather than on just the current target',
castbar_showfriend = 'Show cast bars on friendly nameplates (note that cast bars are not shown on frames which have name-only mode active)',
castbar_showenemy = 'Show cast bars on enemy nameplates',
castbar_colour = 'Colour of the cast bar.|n|nAlso used to indicate a successful cast if animation is enabled.',
castbar_unin_colour = 'Colour of the cast bar when a cast cannot be interrupted.|n|nAlso used to indicate an interrupted cast if animation is enabled.',
castbar_name_vertical_offset = 'Vertical offset of the spell name text',
castbar_animate = 'Fade out the cast bar when a cast ends.',
castbar_animate_change_colour = 'Change the colour of the cast bar when a cast ends, making it easier to tell the difference between successful, stopped, and interrupted casts.',
tank_mode = 'Recolour the health bars of units you are actively tanking when in a tanking specialisation',
tankmode_force_enable = 'Always use tank mode, even if you\'re not currently in a tanking specialisation',
tankmode_force_offtank = 'Colour bars being tanked by other tanks in your group, even if you\'re not currently in a tanking specialisation',
frame_glow_threat = 'Change the colour of the frame glow to indicate threat status',
tankmode_tank_colour = 'Health bar colour for enemies you are securely tanking',
tankmode_trans_colour = 'Health bar colour for enemies which are about to change targets',
tankmode_other_colour = 'Health bar colour for enemies being tanked by another tank in your group (or a player controlled pet, vehicle or totem).|n|nThis is only used if you are currently in a tanking specialisation, and requires the other tank to be in your group and to have their group role set to tank.',
classpowers_enable = 'Show class-specific special powers, like combo points, holy power, ...',
classpowers_on_target = 'Show class powers on the target\'s nameplate',
bossmod_enable = 'Supported boss mods can communicate with KNP to show encounter-specific auras and draw lines to nameplates.',
bossmod_control_visibility = 'Allow boss mods to show nameplates if they are used for auras in an encounter.',
bossmod_clickthrough = 'Disable the click-box of nameplates which are automatically enabled',
cvar_enable = 'When enabled, Kui Nameplates will attempt to lock the CVars on this page to the values set here.',
cvar_show_friendly_npcs = '|cffffcc00nameplateShowFriendlyNPCs|r',
cvar_name_only = '|cffffcc00nameplateShowOnlyNames|r|n|nHide the health bar of the default nameplates in situations where friendly nameplates cannot be otherwise modified by addons.',
cvar_personal_show_always = '|cffffcc00nameplatePersonalShowAlways|r',
cvar_personal_show_combat = '|cffffcc00nameplatePersonalShowInCombat|r',
cvar_personal_show_target = '|cffffcc00nameplatePersonalShowWithTarget|r|n|nShow the personal nameplate whenever you have an attackable target.',
cvar_max_distance = '|cffffcc00nameplateMaxDistance|r|n|nMaximum distance at which to render nameplates (not including your current target).',
cvar_clamp_top = '|cffffcc00nameplateOtherTopInset|nnameplateLargeTopInset|r|n|nHow close nameplates will be rendered to the top edge of the screen, where 0 means on the edge. Set to -0.1 to disable clamping on the top of the screen.|n|nClamping only affects your current target.',
cvar_clamp_bottom = '|cffffcc00nameplateOtherBottomInset|nnameplateLargeBottomInset|r',
cvar_self_clamp_top = '|cffffcc00nameplateSelfTopInset|r',
cvar_self_clamp_bottom = '|cffffcc00nameplateSelfBottomInset|r',
cvar_overlap_v = '|cffffcc00nameplateOverlapV|r|n|nVertical distance between nameplates (only valid when motion type is set to stacking in the default interface options).',
cvar_disable_scale = '|cffffcc00nameplateMinScale|nnameplateMaxScale|nnameplateLargerScale|nnameplateSelectedScale|nnameplateSelfScale|r|n|nDisable the nameplate distance scaling CVars which break pixel-correction.',
cvar_disable_alpha = '|cffffcc00nameplateMinAlpha|nnameplateMaxAlpha|nnameplateSelectedAlpha|r|n|nDisable the nameplate alpha CVars (except those below) so that they don\'t interfere with KNP\'s fade rules.',
cvar_self_alpha = '|cffffcc00nameplateSelfAlpha|r|n|nMaximum alpha of the personal nameplate.',
cvar_occluded_mult = '|cffffcc00nameplateOccludedAlphaMult|r|n|nAlpha multiplier applied to nameplates which are out of the character\'s line-of-sight.',
}
KuiNameplatesCoreConfig:LocaleLoaded()
| 412 | 0.909885 | 1 | 0.909885 | game-dev | MEDIA | 0.811244 | game-dev,desktop-app | 0.916622 | 1 | 0.916622 |
ratrecommends/dice-heroes | 3,945 | main/src/com/vlaaad/dice/game/world/view/visualizers/actions/PoisonAreaVisualizer.java | /*
* Dice heroes is a turn based rpg-strategy game where characters are dice.
* Copyright (C) 2016 Vladislav Protsenko
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.vlaaad.dice.game.world.view.visualizers.actions;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.vlaaad.common.gdx.scene2d.ParticleActor;
import com.vlaaad.common.util.CountDown;
import com.vlaaad.common.util.futures.Future;
import com.vlaaad.common.util.futures.IFuture;
import com.vlaaad.dice.game.actions.results.imp.PoisonAreaResult;
import com.vlaaad.dice.game.objects.Creature;
import com.vlaaad.dice.game.world.controllers.ViewController;
import com.vlaaad.dice.game.world.view.IVisualizer;
import com.vlaaad.dice.game.world.view.ResultVisualizer;
import com.vlaaad.dice.managers.SoundManager;
import static com.badlogic.gdx.scenes.scene2d.actions.Actions.*;
/**
* Created 14.05.14 by vlaaad
*/
public class PoisonAreaVisualizer implements IVisualizer<PoisonAreaResult> {
private static final Vector2 tmp = new Vector2();
private final ResultVisualizer visualizer;
public PoisonAreaVisualizer(ResultVisualizer visualizer) {this.visualizer = visualizer;}
@Override public IFuture<Void> visualize(final PoisonAreaResult result) {
final Future<Void> future = Future.make();
final ParticleActor actor = new ParticleActor("ability-" + result.ability.name);
actor.setPosition(
(result.creature.getX() + 0.5f) * ViewController.CELL_SIZE,
(result.creature.getY() + 0.5f) * ViewController.CELL_SIZE + 3
);
SoundManager.instance.playMusicAsSound("ability-" + result.ability.name);
float time = tmp.set(result.creature.getX(), result.creature.getY()).sub(result.coordinate.x(), result.coordinate.y()).len() * 0.2f;
actor.freeOnComplete();
actor.addAction(sequence(
moveTo(
(result.coordinate.x() + 0.5f) * ViewController.CELL_SIZE,
(result.coordinate.y() + 0.5f) * ViewController.CELL_SIZE,
time
),
run(new Runnable() {
@Override public void run() {
actor.effect.allowCompletion();
final CountDown countDown = new CountDown(result.targets.size, future);
for (Creature creature : result.targets) {
ParticleActor hit = new ParticleActor("ability-" + result.ability.name + "-hit");
visualizer.viewController.effectLayer.addActor(hit);
hit.setPosition(
(creature.getX() + 0.5f) * ViewController.CELL_SIZE,
(creature.getY() + 0.5f) * ViewController.CELL_SIZE + 3
);
hit.freeOnComplete();
hit.addListener(new ChangeListener() {
@Override public void changed(ChangeEvent event, Actor actor) {
countDown.tick();
}
});
}
}
})
));
visualizer.viewController.effectLayer.addActor(actor);
return future;
}
}
| 412 | 0.953605 | 1 | 0.953605 | game-dev | MEDIA | 0.948566 | game-dev | 0.994851 | 1 | 0.994851 |
devcxx/PlottingSymbol | 6,286 | sdk/include/osg/osgParticle/RadialShooter | /* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
//osgParticle - Copyright (C) 2002 Marco Jez
#ifndef OSGPARTICLE_RADIAL_SHOOTER
#define OSGPARTICLE_RADIAL_SHOOTER 1
#include <osgParticle/Shooter>
#include <osgParticle/Particle>
#include <osgParticle/range>
#include <osg/CopyOp>
#include <osg/Object>
#include <osg/Math>
namespace osgParticle
{
/** A shooter class that shoots particles radially.
This shooter computes the velocity vector of incoming particles by choosing a
random direction and a random speed. Both direction and speed are chosen within
specified ranges. The direction is defined by two angles: <B>theta</B>, which
is the angle between the velocity vector and the Z axis, and <B>phi</B>, which is
the angle between the X axis and the velocity vector projected onto the X-Y plane.
*/
class RadialShooter: public Shooter {
public:
inline RadialShooter();
inline RadialShooter(const RadialShooter& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY);
META_Object(osgParticle, RadialShooter);
/// Get the range of possible values for <B>theta</B> angle.
inline const rangef& getThetaRange() const;
/// Set the range of possible values for <B>theta</B> angle.
inline void setThetaRange(const rangef& r);
/// Set the range of possible values for <B>theta</B> angle.
inline void setThetaRange(float r1, float r2);
/// Get the range of possible values for <B>phi</B> angle.
inline const rangef& getPhiRange() const;
/// Set the range of possible values for <B>phi</B> angle.
inline void setPhiRange(const rangef& r);
/// Set the range of possible values for <B>phi</B> angle.
inline void setPhiRange(float r1, float r2);
/// Get the range of possible values for initial speed of particles.
inline const rangef& getInitialSpeedRange() const;
/// Set the range of possible values for initial speed of particles.
inline void setInitialSpeedRange(const rangef& r);
/// Set the range of possible values for initial speed of particles.
inline void setInitialSpeedRange(float r1, float r2);
/// Get the range of possible values for initial rotational speed of particles.
inline const rangev3& getInitialRotationalSpeedRange() const;
/// Set the range of possible values for initial rotational speed of particles.
inline void setInitialRotationalSpeedRange(const rangev3& r);
/// Set the range of possible values for initial rotational speed of particles.
inline void setInitialRotationalSpeedRange(const osg::Vec3& r1, const osg::Vec3& r2);
/// Shoot a particle. Do not call this method manually.
inline void shoot(Particle* P) const;
protected:
virtual ~RadialShooter() {}
RadialShooter& operator=(const RadialShooter&) { return *this; }
private:
rangef _theta_range;
rangef _phi_range;
rangef _speed_range;
rangev3 _rot_speed_range;
};
// INLINE FUNCTIONS
inline RadialShooter::RadialShooter()
: Shooter(),
_theta_range(0, 0.5f*osg::PI_4),
_phi_range(0, 2*osg::PI),
_speed_range(10, 10),
_rot_speed_range(osg::Vec3(0,0,0), osg::Vec3(0,0,0))
{
}
inline RadialShooter::RadialShooter(const RadialShooter& copy, const osg::CopyOp& copyop)
: Shooter(copy, copyop),
_theta_range(copy._theta_range),
_phi_range(copy._phi_range),
_speed_range(copy._speed_range),
_rot_speed_range(copy._rot_speed_range)
{
}
inline const rangef& RadialShooter::getThetaRange() const
{
return _theta_range;
}
inline const rangef& RadialShooter::getPhiRange() const
{
return _phi_range;
}
inline const rangef& RadialShooter::getInitialSpeedRange() const
{
return _speed_range;
}
inline const rangev3& RadialShooter::getInitialRotationalSpeedRange() const
{
return _rot_speed_range;
}
inline void RadialShooter::setThetaRange(const rangef& r)
{
_theta_range = r;
}
inline void RadialShooter::setThetaRange(float r1, float r2)
{
_theta_range.minimum = r1;
_theta_range.maximum = r2;
}
inline void RadialShooter::setPhiRange(const rangef& r)
{
_phi_range = r;
}
inline void RadialShooter::setPhiRange(float r1, float r2)
{
_phi_range.minimum = r1;
_phi_range.maximum = r2;
}
inline void RadialShooter::setInitialSpeedRange(const rangef& r)
{
_speed_range = r;
}
inline void RadialShooter::setInitialSpeedRange(float r1, float r2)
{
_speed_range.minimum = r1;
_speed_range.maximum = r2;
}
inline void RadialShooter::setInitialRotationalSpeedRange(const rangev3& r)
{
_rot_speed_range = r;
}
inline void RadialShooter::setInitialRotationalSpeedRange(const osg::Vec3& r1, const osg::Vec3& r2)
{
_rot_speed_range.minimum = r1;
_rot_speed_range.maximum = r2;
}
inline void RadialShooter::shoot(Particle* P) const
{
float theta = _theta_range.get_random();
float phi = _phi_range.get_random();
float speed = _speed_range.get_random();
osg::Vec3 rot_speed = _rot_speed_range.get_random();
P->setVelocity(osg::Vec3(
speed * sinf(theta) * cosf(phi),
speed * sinf(theta) * sinf(phi),
speed * cosf(theta)
));
P->setAngularVelocity(rot_speed);
}
}
#endif
| 412 | 0.821596 | 1 | 0.821596 | game-dev | MEDIA | 0.771228 | game-dev | 0.687148 | 1 | 0.687148 |
Nebukam/PCGExtendedToolkit | 4,077 | Source/PCGExtendedToolkit/Private/Transform/Tensors/PCGExTensorFactoryProvider.cpp | // Copyright 2025 Timothé Lapetite and contributors
// Released under the MIT license https://opensource.org/license/MIT/
#include "Transform/Tensors/PCGExTensorFactoryProvider.h"
#include "Paths/PCGExSplineToPath.h"
#include "Transform/Tensors/PCGExTensorOperation.h"
#define LOCTEXT_NAMESPACE "PCGExCreateTensor"
#define PCGEX_NAMESPACE CreateTensor
PCG_DEFINE_TYPE_INFO(FPCGExDataTypeInfoTensor, UPCGExTensorFactoryData)
TSharedPtr<PCGExTensorOperation> UPCGExTensorFactoryData::CreateOperation(FPCGExContext* InContext) const
{
return nullptr; // Create shape builder operation
}
PCGExFactories::EPreparationResult UPCGExTensorFactoryData::Prepare(FPCGExContext* InContext, const TSharedPtr<PCGExMT::FTaskManager>& AsyncManager)
{
PCGExFactories::EPreparationResult Result = Super::Prepare(InContext, AsyncManager);
if (Result != PCGExFactories::EPreparationResult::Success) { return Result; }
return InitInternalData(InContext);
}
PCGExFactories::EPreparationResult UPCGExTensorFactoryData::InitInternalData(FPCGExContext* InContext)
{
return PCGExFactories::EPreparationResult::Success;
}
void UPCGExTensorFactoryData::InheritFromOtherTensor(const UPCGExTensorFactoryData* InOtherTensor)
{
const TSet<FString> Exclusions = {TEXT("Points"), TEXT("Splines"), TEXT("ManagedSplines")};
PCGExHelpers::CopyProperties(this, InOtherTensor, &Exclusions);
if (InOtherTensor->GetClass() == GetClass())
{
// Same type let's automate
}
else
{
// We can only attempt to inherit a few settings
}
}
TArray<FPCGPinProperties> UPCGExTensorFactoryProviderSettings::InputPinProperties() const
{
TArray<FPCGPinProperties> PinProperties = Super::InputPinProperties();
PCGEX_PIN_FACTORY(PCGExTensor::SourceTensorConfigSourceLabel, "A tensor that already exist which settings will be used to override the settings of this one. This is to streamline re-using params between tensors, or to 'fake' the ability to transform tensors.", Advanced, FPCGExDataTypeInfoTensor::AsId())
return PinProperties;
}
UPCGExFactoryData* UPCGExTensorFactoryProviderSettings::CreateFactory(FPCGExContext* InContext, UPCGExFactoryData* InFactory) const
{
TArray<FPCGTaggedData> Collection = InContext->InputData.GetInputsByPin(PCGExTensor::SourceTensorConfigSourceLabel);
const UPCGExTensorFactoryData* InTensorReference = Collection.IsEmpty() ? nullptr : Cast<UPCGExTensorFactoryData>(Collection[0].Data);
if (InTensorReference) { Cast<UPCGExTensorFactoryData>(InFactory)->InheritFromOtherTensor(InTensorReference); }
return Super::CreateFactory(InContext, InFactory);
}
PCGExFactories::EPreparationResult UPCGExTensorPointFactoryData::InitInternalData(FPCGExContext* InContext)
{
PCGExFactories::EPreparationResult Result = Super::InitInternalData(InContext);
if (Result != PCGExFactories::EPreparationResult::Success) { return Result; }
if (!InitInternalFacade(InContext)) { return PCGExFactories::EPreparationResult::Fail; }
EffectorsArray = GetEffectorsArray();
// Bulk of the work happens here
if (!EffectorsArray->Init(InContext, this)) { return PCGExFactories::EPreparationResult::Fail; }
InputDataFacade->Flush(); // Flush cached buffers
InputDataFacade.Reset();
return Result;
}
TSharedPtr<PCGExTensor::FEffectorsArray> UPCGExTensorPointFactoryData::GetEffectorsArray() const
{
return MakeShared<PCGExTensor::FEffectorsArray>();
}
bool UPCGExTensorPointFactoryData::InitInternalFacade(FPCGExContext* InContext)
{
InputDataFacade = PCGExData::TryGetSingleFacade(InContext, PCGExTensor::SourceEffectorsLabel, false, true);
if (!InputDataFacade) { return false; }
return true;
}
void UPCGExTensorPointFactoryData::PrepareSinglePoint(const int32 Index) const
{
}
TArray<FPCGPinProperties> UPCGExTensorPointFactoryProviderSettings::InputPinProperties() const
{
TArray<FPCGPinProperties> PinProperties = Super::InputPinProperties();
PCGEX_PIN_POINT(PCGExTensor::SourceEffectorsLabel, "Single point collection that represent individual effectors within that tensor", Required)
return PinProperties;
}
#undef LOCTEXT_NAMESPACE
#undef PCGEX_NAMESPACE
| 412 | 0.718954 | 1 | 0.718954 | game-dev | MEDIA | 0.816485 | game-dev | 0.725652 | 1 | 0.725652 |
MegaMek/megamek | 6,315 | megamek/src/megamek/common/autoResolve/acar/manager/InitiativeHelper.java | /*
* Copyright (C) 2025 The MegaMek Team. All Rights Reserved.
*
* This file is part of MegaMek.
*
* MegaMek is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License (GPL),
* version 3 or (at your option) any later version,
* as published by the Free Software Foundation.
*
* MegaMek 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.
*
* A copy of the GPL should have been included with this project;
* if not, see <https://www.gnu.org/licenses/>.
*
* NOTICE: The MegaMek organization is a non-profit group of volunteers
* creating free software for the BattleTech community.
*
* MechWarrior, BattleMech, `Mech and AeroTech are registered trademarks
* of The Topps Company, Inc. All Rights Reserved.
*
* Catalyst Game Labs and the Catalyst Game Labs logo are trademarks of
* InMediaRes Productions, LLC.
*
* MechWarrior Copyright Microsoft Corporation. MegaMek was created under
* Microsoft's "Game Content Usage Rules"
* <https://www.xbox.com/en-US/developers/rules> and it is not endorsed by or
* affiliated with Microsoft.
*/
package megamek.common.autoResolve.acar.manager;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import megamek.common.Player;
import megamek.common.Team;
import megamek.common.autoResolve.acar.SimulationManager;
import megamek.common.autoResolve.component.AcTurn;
import megamek.common.autoResolve.component.Formation;
import megamek.common.autoResolve.component.FormationTurn;
import megamek.common.enums.GamePhase;
import megamek.common.game.AbstractGame;
/**
* @author Luana Coppio
*/
public record InitiativeHelper(SimulationManager simulationManager) implements SimulationManagerHelper {
public void resetInitiative() {
for (var player : game().getPlayersList()) {
player.getInitiative().clear();
}
}
private record InitiativeFormationTurn(int initiativeValue, AcTurn acTurn)
implements Comparable<InitiativeFormationTurn> {
@Override
public int compareTo(InitiativeFormationTurn o) {
if (initiativeValue > o.initiativeValue) {
return -1;
} else if (initiativeValue < o.initiativeValue) {
return 1;
}
return 0;
}
}
/**
* Determines the turn order for a given phase, setting the game's turn list and sending it to the Clients. Also
* resets the turn index.
*
* @param phase The phase to find the turns for
*
* @see AbstractGame#resetTurnIndex()
*/
void determineTurnOrder(GamePhase phase) {
List<InitiativeFormationTurn> formationTurns = new ArrayList<>();
if (phase.isFiring() || phase.isMovement()) {
for (var player : game().getPlayersList()) {
var actionsForThisTurn = game().getActiveFormations(player)
.stream()
.filter(Formation::isDeployed)
.filter(unit -> unit.isEligibleForPhase(phase))
.count();
var turnsForPlayer = (int) Math.min(actionsForThisTurn, player.getInitiative().size());
for (int i = 0; i < turnsForPlayer; i++) {
var initiative = player.getInitiative().getRoll(i);
formationTurns.add(new InitiativeFormationTurn(initiative, new FormationTurn(player.getId())));
}
}
} else if (phase.isDeployment()) {
for (var player : game().getPlayersList()) {
var actionsForThisTurn = game().getActiveFormations(player)
.stream()
.filter(Formation::isDeployed)
.filter(unit -> !unit.isDeployed())
.count();
var turnsForPlayer = (int) Math.min(actionsForThisTurn, player.getInitiative().size());
for (int i = 0; i < turnsForPlayer; i++) {
var initiative = player.getInitiative().getRoll(i);
formationTurns.add(new InitiativeFormationTurn(initiative, new FormationTurn(player.getId())));
}
}
} else {
for (var player : game().getPlayersList()) {
var actionsForThisTurn = game().getActiveFormations(player)
.stream()
.filter(unit -> unit.isEligibleForPhase(phase))
.filter(Formation::isDeployed)
.count();
var turnsForPlayer = (int) Math.min(actionsForThisTurn, player.getInitiative().size());
for (int i = 0; i < turnsForPlayer; i++) {
var initiative = player.getInitiative().getRoll(i);
formationTurns.add(new InitiativeFormationTurn(initiative, new FormationTurn(player.getId())));
}
}
}
final List<AcTurn> turns = formationTurns.stream()
.sorted()
.map(InitiativeFormationTurn::acTurn)
.collect(Collectors.toList());
game().setTurns(turns);
game().resetTurnIndex();
}
private Team getTeamForPlayerId(int id) {
return game().getTeams()
.stream()
.filter(t -> t.players().stream().anyMatch(p -> p.getId() == id))
.findFirst()
.orElse(null);
}
private Player getPlayerForFormation(Formation formation) {
return game().getPlayer(formation.getOwnerId());
}
public void rollInitiativeForFormations(List<Formation> formations) {
for (var formation : formations) {
int bonus = 0;
final Team team = getTeamForPlayerId(formation.getOwnerId());
if (team != null) {
bonus = team.getTotalInitBonus(false);
}
var player = this.getPlayerForFormation(formation);
// Due to the abstract nature of the simulation, we don't track initiative aptitude SPAs
player.getInitiative().addRoll(bonus, "");
}
}
}
| 412 | 0.830918 | 1 | 0.830918 | game-dev | MEDIA | 0.899591 | game-dev | 0.83843 | 1 | 0.83843 |
rerun-io/revy | 14,146 | examples/alien_cake_addict.rs | //! Example from <https://github.com/bevyengine/bevy/blob/release-0.15.0/examples/games/breakout.rs>
//! with minimal changes to inject revy.
//!
//! This is part of the Bevy project and licensed separately from Revy under MIT & Apache-2.0.
//! For details see <https://github.com/bevyengine/bevy/tree/release-0.15.0?tab=readme-ov-file#license>
//!
//! ------------------------------------------------------------------------------------------------
//!
//! Eat the cakes. Eat them all. An example 3D game.
#![allow(clippy::unwrap_used)]
#![allow(clippy::needless_pass_by_value)]
#![allow(elided_lifetimes_in_paths)]
#![allow(clippy::missing_assert_message)]
#![allow(clippy::disallowed_methods)]
#![allow(clippy::str_to_string)]
#![allow(clippy::type_complexity)]
#![allow(clippy::explicit_iter_loop)]
use std::f32::consts::PI;
use bevy::prelude::*;
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha8Rng;
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default, States)]
enum GameState {
#[default]
Playing,
GameOver,
}
#[derive(Resource)]
struct BonusSpawnTimer(Timer);
fn main() {
App::new()
.add_plugins(DefaultPlugins)
// ==== Instantiating the Rerun plugin ===========================================
//
// This is the only modification that was applied to this example.
//
// This will start a Rerun Viewer in the background and stream the recording data to it.
// Check out the `RecordingStreamBuilder` (<https://docs.rs/rerun/latest/rerun/struct.RecordingStreamBuilder.html>)
// docs for other options (saving to file, connecting to a remote viewer, etc).
.add_plugins({
let rec = revy::RecordingStreamBuilder::new("alien_cake_addict")
.spawn()
.unwrap();
revy::RerunPlugin { rec }
})
// ===============================================================================
.init_resource::<Game>()
.insert_resource(BonusSpawnTimer(Timer::from_seconds(
5.0,
TimerMode::Repeating,
)))
.init_state::<GameState>()
.enable_state_scoped_entities::<GameState>()
.add_systems(Startup, setup_cameras)
.add_systems(OnEnter(GameState::Playing), setup)
.add_systems(
Update,
(
move_player,
focus_camera,
rotate_bonus,
scoreboard_system,
spawn_bonus,
)
.run_if(in_state(GameState::Playing)),
)
.add_systems(OnEnter(GameState::GameOver), display_score)
.add_systems(
Update,
gameover_keyboard.run_if(in_state(GameState::GameOver)),
)
.run();
}
struct Cell {
height: f32,
}
#[derive(Default)]
struct Player {
entity: Option<Entity>,
i: usize,
j: usize,
move_cooldown: Timer,
}
#[derive(Default)]
struct Bonus {
entity: Option<Entity>,
i: usize,
j: usize,
handle: Handle<Scene>,
}
#[derive(Resource, Default)]
struct Game {
board: Vec<Vec<Cell>>,
player: Player,
bonus: Bonus,
score: i32,
cake_eaten: u32,
camera_should_focus: Vec3,
camera_is_focus: Vec3,
}
#[derive(Resource, Deref, DerefMut)]
struct Random(ChaCha8Rng);
const BOARD_SIZE_I: usize = 14;
const BOARD_SIZE_J: usize = 21;
const RESET_FOCUS: [f32; 3] = [
BOARD_SIZE_I as f32 / 2.0,
0.0,
BOARD_SIZE_J as f32 / 2.0 - 0.5,
];
fn setup_cameras(mut commands: Commands, mut game: ResMut<Game>) {
game.camera_should_focus = Vec3::from(RESET_FOCUS);
game.camera_is_focus = game.camera_should_focus;
commands.spawn((
Camera3d::default(),
Transform::from_xyz(
-(BOARD_SIZE_I as f32 / 2.0),
2.0 * BOARD_SIZE_J as f32 / 3.0,
BOARD_SIZE_J as f32 / 2.0 - 0.5,
)
.looking_at(game.camera_is_focus, Vec3::Y),
));
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>, mut game: ResMut<Game>) {
let mut rng = if std::env::var("GITHUB_ACTIONS") == Ok("true".to_string()) {
// We're seeding the PRNG here to make this example deterministic for testing purposes.
// This isn't strictly required in practical use unless you need your app to be deterministic.
ChaCha8Rng::seed_from_u64(19878367467713)
} else {
ChaCha8Rng::from_entropy()
};
// reset the game state
game.cake_eaten = 0;
game.score = 0;
game.player.i = BOARD_SIZE_I / 2;
game.player.j = BOARD_SIZE_J / 2;
game.player.move_cooldown = Timer::from_seconds(0.3, TimerMode::Once);
commands.spawn((
StateScoped(GameState::Playing),
PointLight {
intensity: 2_000_000.0,
shadows_enabled: true,
range: 30.0,
..default()
},
Transform::from_xyz(4.0, 10.0, 4.0),
));
// spawn the game board
let cell_scene =
asset_server.load(GltfAssetLabel::Scene(0).from_asset("models/AlienCake/tile.glb"));
game.board = (0..BOARD_SIZE_J)
.map(|j| {
(0..BOARD_SIZE_I)
.map(|i| {
let height = rng.gen_range(-0.1..0.1);
commands.spawn((
StateScoped(GameState::Playing),
Transform::from_xyz(i as f32, height - 0.2, j as f32),
SceneRoot(cell_scene.clone()),
));
Cell { height }
})
.collect()
})
.collect();
// spawn the game character
game.player.entity = Some(
commands
.spawn((
StateScoped(GameState::Playing),
Transform {
translation: Vec3::new(
game.player.i as f32,
game.board[game.player.j][game.player.i].height,
game.player.j as f32,
),
rotation: Quat::from_rotation_y(-PI / 2.),
..default()
},
SceneRoot(
asset_server
.load(GltfAssetLabel::Scene(0).from_asset("models/AlienCake/alien.glb")),
),
))
.id(),
);
// load the scene for the cake
game.bonus.handle =
asset_server.load(GltfAssetLabel::Scene(0).from_asset("models/AlienCake/cakeBirthday.glb"));
// scoreboard
commands.spawn((
StateScoped(GameState::Playing),
Text::new("Score:"),
TextFont {
font_size: 33.0,
..default()
},
TextColor(Color::srgb(0.5, 0.5, 1.0)),
Node {
position_type: PositionType::Absolute,
top: Val::Px(5.0),
left: Val::Px(5.0),
..default()
},
));
commands.insert_resource(Random(rng));
}
// control the game character
fn move_player(
mut commands: Commands,
keyboard_input: Res<ButtonInput<KeyCode>>,
mut game: ResMut<Game>,
mut transforms: Query<&mut Transform>,
time: Res<Time>,
) {
if game.player.move_cooldown.tick(time.delta()).finished() {
let mut moved = false;
let mut rotation = 0.0;
if keyboard_input.pressed(KeyCode::ArrowUp) {
if game.player.i < BOARD_SIZE_I - 1 {
game.player.i += 1;
}
rotation = -PI / 2.;
moved = true;
}
if keyboard_input.pressed(KeyCode::ArrowDown) {
if game.player.i > 0 {
game.player.i -= 1;
}
rotation = PI / 2.;
moved = true;
}
if keyboard_input.pressed(KeyCode::ArrowRight) {
if game.player.j < BOARD_SIZE_J - 1 {
game.player.j += 1;
}
rotation = PI;
moved = true;
}
if keyboard_input.pressed(KeyCode::ArrowLeft) {
if game.player.j > 0 {
game.player.j -= 1;
}
rotation = 0.0;
moved = true;
}
// move on the board
if moved {
game.player.move_cooldown.reset();
*transforms.get_mut(game.player.entity.unwrap()).unwrap() = Transform {
translation: Vec3::new(
game.player.i as f32,
game.board[game.player.j][game.player.i].height,
game.player.j as f32,
),
rotation: Quat::from_rotation_y(rotation),
..default()
};
}
}
// eat the cake!
if let Some(entity) = game.bonus.entity {
if game.player.i == game.bonus.i && game.player.j == game.bonus.j {
game.score += 2;
game.cake_eaten += 1;
commands.entity(entity).despawn_recursive();
game.bonus.entity = None;
}
}
}
// change the focus of the camera
fn focus_camera(
time: Res<Time>,
mut game: ResMut<Game>,
mut transforms: ParamSet<(Query<&mut Transform, With<Camera3d>>, Query<&Transform>)>,
) {
const SPEED: f32 = 2.0;
// if there is both a player and a bonus, target the mid-point of them
if let (Some(player_entity), Some(bonus_entity)) = (game.player.entity, game.bonus.entity) {
let transform_query = transforms.p1();
if let (Ok(player_transform), Ok(bonus_transform)) = (
transform_query.get(player_entity),
transform_query.get(bonus_entity),
) {
game.camera_should_focus = player_transform
.translation
.lerp(bonus_transform.translation, 0.5);
}
// otherwise, if there is only a player, target the player
} else if let Some(player_entity) = game.player.entity {
if let Ok(player_transform) = transforms.p1().get(player_entity) {
game.camera_should_focus = player_transform.translation;
}
// otherwise, target the middle
} else {
game.camera_should_focus = Vec3::from(RESET_FOCUS);
}
// calculate the camera motion based on the difference between where the camera is looking
// and where it should be looking; the greater the distance, the faster the motion;
// smooth out the camera movement using the frame time
let mut camera_motion = game.camera_should_focus - game.camera_is_focus;
if camera_motion.length() > 0.2 {
camera_motion *= SPEED * time.delta_secs();
// set the new camera's actual focus
game.camera_is_focus += camera_motion;
}
// look at that new camera's actual focus
for mut transform in transforms.p0().iter_mut() {
*transform = transform.looking_at(game.camera_is_focus, Vec3::Y);
}
}
// despawn the bonus if there is one, then spawn a new one at a random location
fn spawn_bonus(
time: Res<Time>,
mut timer: ResMut<BonusSpawnTimer>,
mut next_state: ResMut<NextState<GameState>>,
mut commands: Commands,
mut game: ResMut<Game>,
mut rng: ResMut<Random>,
) {
// make sure we wait enough time before spawning the next cake
if !timer.0.tick(time.delta()).finished() {
return;
}
if let Some(entity) = game.bonus.entity {
game.score -= 3;
commands.entity(entity).despawn_recursive();
game.bonus.entity = None;
if game.score <= -5 {
next_state.set(GameState::GameOver);
return;
}
}
// ensure bonus doesn't spawn on the player
loop {
game.bonus.i = rng.gen_range(0..BOARD_SIZE_I);
game.bonus.j = rng.gen_range(0..BOARD_SIZE_J);
if game.bonus.i != game.player.i || game.bonus.j != game.player.j {
break;
}
}
game.bonus.entity = Some(
commands
.spawn((
StateScoped(GameState::Playing),
Transform::from_xyz(
game.bonus.i as f32,
game.board[game.bonus.j][game.bonus.i].height + 0.2,
game.bonus.j as f32,
),
SceneRoot(game.bonus.handle.clone()),
))
.with_child((
PointLight {
color: Color::srgb(1.0, 1.0, 0.0),
intensity: 500_000.0,
range: 10.0,
..default()
},
Transform::from_xyz(0.0, 2.0, 0.0),
))
.id(),
);
}
// let the cake turn on itself
fn rotate_bonus(game: Res<Game>, time: Res<Time>, mut transforms: Query<&mut Transform>) {
if let Some(entity) = game.bonus.entity {
if let Ok(mut cake_transform) = transforms.get_mut(entity) {
cake_transform.rotate_y(time.delta_secs());
cake_transform.scale =
Vec3::splat(1.0 + (game.score as f32 / 10.0 * ops::sin(time.elapsed_secs())).abs());
}
}
}
// update the score displayed during the game
fn scoreboard_system(game: Res<Game>, mut display: Single<&mut Text>) {
display.0 = format!("Sugar Rush: {}", game.score);
}
// restart the game when pressing spacebar
fn gameover_keyboard(
mut next_state: ResMut<NextState<GameState>>,
keyboard_input: Res<ButtonInput<KeyCode>>,
) {
if keyboard_input.just_pressed(KeyCode::Space) {
next_state.set(GameState::Playing);
}
}
// display the number of cake eaten before losing
fn display_score(mut commands: Commands, game: Res<Game>) {
commands
.spawn((
StateScoped(GameState::GameOver),
Node {
width: Val::Percent(100.),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..default()
},
))
.with_child((
Text::new(format!("Cake eaten: {}", game.cake_eaten)),
TextFont {
font_size: 67.0,
..default()
},
TextColor(Color::srgb(0.5, 0.5, 1.0)),
));
}
| 412 | 0.718245 | 1 | 0.718245 | game-dev | MEDIA | 0.963006 | game-dev | 0.941392 | 1 | 0.941392 |
Lexxie9952/fcw.org-server | 45,684 | freeciv/freeciv/data/alien/game.ruleset | ; This is Alien World game ruleset.
; Modifying this file:
; You should not modify this file except to make bugfixes or
; for other "maintenance". If you want to make custom changes,
; you should create a new datadir subdirectory and copy this file
; into that directory, and then modify that copy. Then use the
; command "rulesetdir <mysubdir>" in the server to have freeciv
; use your new customized file.
; Note that the freeciv AI may not cope well with anything more
; than minor changes.
[datafile]
description="Alien World game rules for Freeciv"
options="+Freeciv-ruleset-Devel-2017.Jan.02"
format_version=20
; This section contains meta information for freeciv-ruledit to recreate the ruleset
; file in a form wanted. These have no in-game effect whatsoever
[ruledit]
; Which file to read description in from.
description_file = "alien/README.alien"
[about]
; Ruleset name
name = _("Alien World")
; There`s no separate versioning in rulesets part of main freeciv distribution
;version = ""
; When about to migrate ruleset under a new name in the future version, set
; alt_dir to the name of that future directory. Then savegames saved with this
; version of freeciv can find the ruleset from the correct place when loading
; the savegame to the future version.
;alt_dir = ""
; Summary of the ruleset
; /* TRANS: In the client, this is displayed alongside the contents of
; README.alien, which are not localized. */
summary = _("\
One of the design goals of this ruleset was that it has to \
provide gameplay different from standard rules. Do not assume that any rules \
you know from classic rules apply with this ruleset.\n\n\
See http://www.freeciv.org/wiki/Alien_World and \
http://www.cazfi.net/freeciv/alien/ for additional ruleset info.\
")
; Detailed description
; When updating this, update also desciption_file in [ruledit] section to match
description = *alien/README.alien*
; What capabilities ruleset provides for the scenarios.
capabilities = ""
[options]
global_init_techs=""
global_init_buildings="Headquarters", "Basic Infrastructure"
popup_tech_help = TRUE
[tileset]
; Clients that support the feature will suggest
; using Alio tileset with this ruleset.
preferred = "alio"
[soundset]
; If preferred soundset is set, clients that support the feature will suggest
; using that soundset with the ruleset.
; preferred = ""
[musicset]
; If preferred musicset is set, clients that support the feature will suggest
; using that musicset with the ruleset.
; preferred = ""
[civstyle]
; Value added to city pollution
base_pollution = -20
; Cost in luxuries of making one citizen happier
happy_cost = 2
; Cost in food of upkeeping a single citizen
food_cost = 2
; Parameters used to generalize the calculation of city granary size:
; if city_size <= num_inis:
; city_granary_size = (granary_food_ini[city_size] * foodbox / 100)
; if city_size > num_inis;
; city_granary_size = (granary_food_ini[num_inis] +
; granary_food_inc * (city_size - num_inis)) * foodbox / 100
granary_food_ini = 20
granary_food_inc = 10
; City center minimum outputs
min_city_center_food = 1
min_city_center_shield = 1
min_city_center_trade = 1
; Square of initial city radius
init_city_radius_sq = 3
; Square of initially visible radius (true distance).
init_vis_radius_sq = 5
; A base bribe cost, modified heavily by other factors
base_bribe_cost = 750
; Barbarian leader ransom in gold
ransom_gold = 100
; Number of veteran levels lost when upgrading a unit
upgrade_veteran_loss = 0
; Number of veteran levels lost when auto-upgrading a unit
autoupgrade_veteran_loss = 0
; Whether player gets to select which terrain improvement to pillage.
pillage_select = TRUE
; Whether one can steal a tech for which prereqs are not known
tech_steal_allow_holes = TRUE
; Whether one can get a tech for which prereqs are not known via
; diplomatic trading
tech_trade_allow_holes = TRUE
; ...and whether one can lose a tech which is prereq for another known
; tech via trade, if techlost_donor is nonzero
tech_trade_loss_allow_holes = TRUE
; Whether one can get a tech for which prereqs are not known via
; parasite effect (Great Library)
tech_parasite_allow_holes = TRUE
; Whether one can lose a tech which is prereq for another known tech
; due to negative bulbs, if techlossforgiveness allows loss
tech_loss_allow_holes = TRUE
; Whether civil war is possible at all
civil_war_enabled = FALSE
; How many percents each celebrating city affects chance of civil war
civil_war_bonus_celebrating = 0
; How many percents each unhappy city affects chance of civil war
civil_war_bonus_unhappy = 0
; Comma separated list of things to happen, in addition to death
; of owner, when gameloss unit dies
; "CivilWar" - Part of the empire remains, controlled by a new player
; "Barbarians" - Depending on if there`s also "CivilWar", all or part
; or half of the dead players empire gets under barbarian
; control.
; "Loot" - Player who killed the gameloss unit gets loot:
; Partial map, gold, techs, cities
gameloss_style = ""
; Whether units may safely paradrop to transport on non-native terrain
paradrop_to_transport = FALSE
; Method of paying unit and improvement gold upkeep
; "City" - The player`s total gold must be non-negative after paying upkeep
; costs associated with each city. If for any city the player`s
; gold is negative, random buildings in the city are sold off. If
; the gold is still negative, then supported units with gold upkeep
; are disbanded.
; "Mixed" - In the first step, the player`s total gold must be non-negative
; after paying upkeep for all buildings within a city. If for any
; city the player`s gold is negative, random buildings in the city
; are sold off.
; In the second step, gold upkeep for all units is paid in a lump
; sum. If the player does not have enough gold, random units with
; gold upkeep are disbanded.
; "Nation" - Gold upkeep for all buildings and units is paid in a lump sum
; after all cities have been processed. If the player does not
; have enough gold, random buildings from random cities are sold.
; If still more gold is needed, then random units with gold
; upkeep are disbanded.
gold_upkeep_style = "Nation"
; How many points of output one basic unit consists of. Typically you
; want this to be some 10^n.
output_granularity = 1
[illness]
; Whether plagues (illness) are possible
illness_on = FALSE
; the base factor for illness (of percent)
illness_base_factor = 50
; minimum city size for illness
illness_min_size = 2
; factor for how much trading with a plagued city increases our city`s
; chance for plague (in percent)
illness_trade_infection = 0
; factor for how much pollution within a city increases its chance for
; plague (in percent)
illness_pollution_factor = 0
[incite_cost]
; city_incite_cost =
; total_factor * (city_size) *
; (base_incite_cost + (units_cost) * unit_factor +
; (improvements_cost) * improvement_factor)
; / (distance * 100)
; See city_incite_cost() for more details
base_incite_cost = 1000
improvement_factor = 1
unit_factor = 2
total_factor = 100
[global_unit_options]
; Shore landing style
; FALSE - normal movement
; TRUE - (default) slow invasions by removing all
; movement points from ground units moving
; from ocean tile to land
slow_invasions = TRUE
[combat_rules]
; If tired_attack is set to TRUE, units that attack with less than a single
; move point (per move_fragments in terrain.ruleset) will have their attack
; power reduced accordingly. For instance, if move_fragments=3, a unit with
; 2/3 move points will have attack power 2/3 of normal.
; If this is set to FALSE units will attack with full strength even if they
; have only fractional moves left.
tired_attack = TRUE
; With some rules it`s possible that neither side of a combat dies.
; Set this to TRUE if unit should never gain veterancy from such a combat.
only_killing_makes_veteran = FALSE
; Percentage of population lost by a city after nuclear attak. If set to
; 100 city is destroyed along with all the units. If set to 0 city does not
; loose population. Any value below 100 means the city can never be
; destroyed completely using nuclear
nuke_pop_loss_pct = 50
; Percentage chance of a city defender surviving nuclear attack. When set
; to 50 roughly half of defenders will survive nuclear attack. When set to
; 0 no defenders will survive. When set to 100 all defenders will survive.
nuke_defender_survival_chance_pct = 0
[auto_attack]
; An auto attack may be triggered when another unit moves to an adjacent
; tile and the autoattack server setting is enabled. The following details
; are ruleset controlled.
; attack_actions - the actions to try during an auto attack in the order
; they should be tried.
; if_attacker - this requirement vector must be true before a unit even
; considers to auto attack.
attack_actions= "Capture Units", "Bombard", "Attack", "Suicide Attack"
if_attacker =
{ "type", "name", "range", "present"
"DiplRel", "War", "Local", TRUE
"MinMoveFrags", "1", "Local", TRUE
}
[actions]
; If force_trade_route is set to TRUE it is illegal for an actor unit to
; enter the marketplace of a city if it can establish a trade route to it
; in stead.
force_trade_route = TRUE
; If force_capture_units is set to TRUE it is illegal for an actor unit to
; bombard, explode nuclear or perform a regular attack against a tile if
; it can capture units on it in stead.
force_capture_units = TRUE
; If force_bombard is set to TRUE it is illegal for an actor unit to
; explode nuclear or perform a regular attack against a tile if it can
; bombard it in stead.
force_bombard = TRUE
; If force_explode_nuclear is set to TRUE it is illegal for an actor unit
; to perform a regular attack against a tile if it can do explode nuclear
; in stead.
force_explode_nuclear = FALSE
; If poison_empties_food_stock is set to TRUE a successful "Poison City"
; or "Poison City Escape" will empty the food stock.
;poison_empties_food_stock = FALSE
; The maximum distance from the actor unit to the target of the "Bombard"
; action. The value 1 means that the targets must be on a tile adjacent to
; the actor unit. The special value "unlimited" lifts the maximum distance
; restriction. The maximum distance can`t be smaller than the minimum
; distance.
bombard_max_range = 1
; The maximum distance from the actor unit to the target of the "Bombard 2"
; action. The value 1 means that the targets must be on a tile adjacent to
; the actor unit. The special value "unlimited" lifts the maximum distance
; restriction. The maximum distance can`t be smaller than the minimum
; distance.
bombard_2_max_range = 1
; The maximum distance from the actor unit to the target of the "Bombard 3"
; action. The value 1 means that the targets must be on a tile adjacent to
; the actor unit. The special value "unlimited" lifts the maximum distance
; restriction. The maximum distance can`t be smaller than the minimum
; distance.
bombard_3_max_range = 1
; The maximum distance from the actor unit to the target of the
; "Explode Nuclear" action. The value 0 means that the target tile must be
; the tile of the actor unit. The value 1 means that the tile must be a tile
; adjacent to the actor unit. The special value "unlimited" lifts the
; maximum distance restriction. The maximum distance can`t be smaller than
; the minimum distance.
explode_nuclear_max_range = 0
; The maximum distance from the actor unit to the target of the
; "Nuke City" action. The value 1 means that the tile must be a tile
; adjacent to the actor unit. The special value "unlimited" lifts the
; maximum distance restriction. The maximum distance can`t be smaller than
; the minimum distance.
nuke_city_max_range = 1
; The maximum distance from the actor unit to the target of the
; "Nuke Units" action. The value 1 means that the tile must be a tile
; adjacent to the actor unit. The special value "unlimited" lifts the
; maximum distance restriction. The maximum distance can`t be smaller than
; the minimum distance.
nuke_units_max_range = 1
; The maximum distance from the actor unit to the target of the "Airlift Unit"
; action. The value 1 means that the targets must be on a tile adjacent to
; the actor unit. The special value "unlimited" lifts the maximum distance
; restriction. The maximum distance can`t be smaller than the minimum
; distance.
airlift_max_range = "unlimited"
; What each action should be called when showing them to the player.
; The first %s should be before the mnemonic of the action. A Freeciv client
; that supports mnemonics will replace it with the in-band signal that marks
; the following character as a mnemonic in its graphical toolkit.
; The second %s marks where extra details should be inserted.
; /* TRANS: _Bribe Enemy Unit (3% chance of success). */
ui_name_bribe_unit = _("%sBribe Enemy Unit%s")
; /* TRANS: _Sabotage City (3% chance of success). */
ui_name_sabotage_city = _("%sSabotage City%s")
; /* TRANS: Incite a _Revolt (3% chance of success). */
ui_name_incite_city = _("Incite a %sRevolt%s")
; /* TRANS: Copy Research _Data (3% chance of success). */
ui_name_steal_tech = _("Copy Research %sData%s")
; /* TRANS: _Investigate City (spends the unit) (100% chance of success). */
ui_name_investigate_city_spend_unit = _("%sInvestigate City (spends the unit)%s")
; /* TRANS: Establish Trade _Route (100% chance of success). */
ui_name_establish_trade_route = _("Establish Trade %sRoute%s")
; /* TRANS: Monetize Containers (100% chance of success). */
ui_name_enter_marketplace = _("Monetize %sContainers%s")
; /* TRANS: Help _build Wonder (100% chance of success). */
ui_name_help_wonder = _("Help %sbuild Wonder%s")
; /* TRANS: Rec_ycle Unit (100% chance of success). */
ui_name_recycle_unit = _("Rec%sycle Unit%s")
; /* TRANS: _You're Fired (100% chance of success). */
ui_name_disband_unit = _("%sYou're Fired%s")
; /* TRANS: _Capture Units (100% chance of success). */
ui_name_capture_units = _("%sCapture Units%s")
; /* TRANS: _Build City (100% chance of success). */
ui_name_found_city = _("%sBuild City%s")
; /* TRANS: _Add to City (100% chance of success). */
ui_name_join_city = _("%sAdd to City%s")
; /* TRANS: _Bombard (100% chance of success). */
ui_name_bombard = _("%sBombard%s")
; /* TRANS: Set _Home City (100% chance of success). */
ui_name_home_city = _("Set %sHome City%s")
; /* TRANS: _Upgrade Unit (100% chance of success). */
ui_name_upgrade_unit = _("%sUpgrade Unit%s")
; /* TRANS: Drop _Paratrooper (100% chance of success). */
ui_name_paradrop_unit = _("Drop %sParatrooper%s")
; /* TRANS: _Airlift to City (100% chance of success). */
ui_name_airlift_unit = _("%sAirlift to City%s")
; /* TRANS: _Attack (100% chance of success). */
ui_name_attack = _("%sAttack%s")
; /* TRANS: _Explode Missile (100% chance of success). */
ui_name_suicide_attack = _("%sExplode Missile%s")
; /* TRANS: _Conquer City (100% chance of success). */
ui_name_conquer_city = _("%sConquer City%s")
; /* TRANS: _Transform Terrain (3% chance of success). */
ui_name_transform_terrain = _("%sTransform Terrain%s")
; /* TRANS: Transform by _Cultivating (3% chance of success). */
ui_name_cultivate = _("Transform by %sCultivating%s")
; /* TRANS: Transform by _Planting (3% chance of success). */
ui_name_plant = _("Transform by %sPlanting%s")
; /* TRANS: Pilla_ge (100% chance of success). */
ui_name_pillage = _("Pilla%sge%s")
; /* TRANS: _Fortify (100% chance of success). */
ui_name_fortify = _("%sFortify%s")
; /* TRANS: Build _Road (100% chance of success). */
ui_name_road = _("Build %sRoad%s")
; /* TRANS: _Build Base (100% chance of success). */
ui_name_build_base = _("%sBuild Base%s")
; /* TRANS: Build _Mine (100% chance of success). */
ui_name_build_mine = _("Build %sMine%s")
; /* TRANS: Build _Irrigation (100% chance of success). */
ui_name_irrigate = _("Build %sIrrigation%s")
; /* TRANS: _Deboard (100% chance of success). */
ui_name_transport_deboard = _("%sDeboard%s")
; /* TRANS: _Board (100% chance of success). */
ui_name_transport_board = _("%sBoard%s")
; /* TRANS: _Unload (100% chance of success). */
ui_name_transport_unload = _("%sUnload%s")
; /* TRANS: _Disembark (100% chance of success). */
ui_name_transport_disembark = _("%sDisembark%s")
; /* TRANS: _Embark (100% chance of success). */
ui_name_transport_embark = _("%sEmbark%s")
; Blank ruleset defined user actions.
; See the section "Ruleset defined actions" is doc/README.actions
; Example: set up "User Action 1"
;ui_name_user_action_1 = _("%sDisrupt Supply Lines%s")
;user_action_1_target_kind = "individual units"
;user_action_1_min_range = 1
;user_action_1_max_range = 3
;user_action_1_actor_consuming_always = FALSE
; Suppress automatic help text generation about what enables and/or
; disables the following actions.
;
; Can make the help text less redundant when you document it your self.
;quiet_actions = "Targeted Sabotage City", "Targeted Steal Tech"
; /* <-- avoid gettext warnings
;
; Action enablers:
;
; action = the action to enable.
; actor_reqs = requirements that apply to the actor.
; target_reqs = requirements that apply to the target.
;
; README.actions lists the possible actions and their hard coded
; requirements.
;
; An action enabler is active when its actor_reqs AND its target_reqs are
; satisfied.
;
; */ <-- avoid gettext warnings
[actionenabler_sabotage_city]
action = "Sabotage City"
actor_reqs =
{ "type", "name", "range"
"UnitFlag", "Diplomat", "Local"
"DiplRel", "War", "Local"
"UnitState", "OnLivableTile", "Local"
"MinMoveFrags", "1", "Local"
}
[actionenabler_investigate_city]
action = "Investigate City Spend Unit"
actor_reqs =
{ "type", "name", "range"
"UnitFlag", "Diplomat", "Local"
"UnitState", "OnLivableTile", "Local"
"MinMoveFrags", "1", "Local"
"DiplRel", "Foreign", "Local"
}
[actionenabler_steal_tech_random]
action = "Steal Tech"
actor_reqs =
{ "type", "name", "range"
"UnitFlag", "Diplomat", "Local"
"UnitState", "OnLivableTile", "Local"
"MinMoveFrags", "1", "Local"
"DiplRel", "Foreign", "Local"
}
target_reqs =
{ "type", "name", "range", "present"
"NationGroup", "Barbarian", "Player", FALSE
}
[actionenabler_incite_city]
action = "Incite City"
actor_reqs =
{ "type", "name", "range", "present"
"UnitFlag", "Diplomat", "Local", TRUE
"DiplRel", "Alliance", "Local", FALSE
"DiplRel", "Team", "Local", FALSE
"UnitState", "OnLivableTile", "Local", TRUE
"MinMoveFrags", "1", "Local", TRUE
"DiplRel", "Foreign", "Local", TRUE
}
target_reqs =
{ "type", "name", "range", "present"
"Building", "Bunker", "City", FALSE
"Building", "Headquarters", "City", FALSE
}
[actionenabler_bribe_unit]
action = "Bribe Unit"
actor_reqs =
{ "type", "name", "range", "present"
"UnitFlag", "Diplomat", "Local", TRUE
"DiplRel", "Alliance", "Local", FALSE
"DiplRel", "Team", "Local", FALSE
"UnitState", "OnLivableTile", "Local", TRUE
"MinMoveFrags", "1", "Local", TRUE
"DiplRel", "Foreign", "Local", TRUE
}
target_reqs =
{ "type", "name", "range", "present"
"CityTile", "Center", "Local", FALSE
"MaxUnitsOnTile", "1", "Local", TRUE
}
[actionenabler_traderoute]
action = "Establish Trade Route"
actor_reqs =
{ "type", "name", "range", "present"
"UnitFlag", "TradeRoute", "Local", TRUE
}
[actionenabler_marketplace]
action = "Enter Marketplace"
actor_reqs =
{ "type", "name", "range", "present"
"UnitFlag", "TradeRoute", "Local", TRUE
}
[actionenabler_help_build_wonder]
action = "Help Wonder"
actor_reqs =
{ "type", "name", "range", "present"
"UnitFlag", "HelpWonder", "Local", TRUE
"DiplRel", "Foreign", "Local", FALSE
}
target_reqs =
{ "type", "name", "range"
"BuildingGenus", "GreatWonder", "Local"
}
[actionenabler_recycle_unit]
action = "Recycle Unit"
actor_reqs =
{ "type", "name", "range", "present"
"UnitFlag", "EvacuateFirst", "Local", FALSE
"DiplRel", "War", "Local", FALSE
"DiplRel", "Cease-fire", "Local", FALSE
"DiplRel", "Armistice", "Local", FALSE
"DiplRel", "Peace", "Local", FALSE
}
[actionenabler_disband_unit]
action = "Disband Unit"
actor_reqs =
{ "type", "name", "range", "present"
"UnitFlag", "EvacuateFirst", "Local", FALSE
}
[actionenabler_capture]
action = "Capture Units"
actor_reqs =
{ "type", "name", "range", "present"
"UnitFlag", "Capturer", "Local", TRUE
"DiplRel", "War", "Local", TRUE
"MinMoveFrags", "1", "Local", TRUE
"DiplRel", "Foreign", "Local", TRUE
}
target_reqs =
{ "type", "name", "range", "present"
"UnitFlag", "Capturable", "Local", TRUE
"UnitState", "Transporting", "Local", FALSE
"CityTile", "Center", "Local", FALSE
}
[actionenabler_bombard]
action = "Bombard"
actor_reqs =
{ "type", "name", "range", "present"
"UnitFlag", "Bombarder", "Local", TRUE
"UnitState", "Transported", "Local", FALSE
"MinMoveFrags", "1", "Local", TRUE
"DiplRel", "War", "Local", TRUE
}
target_reqs =
{ "type", "name", "range", "present"
"TerrainClass", "Oceanic", "Local", FALSE
}
[actionenabler_build_city_pioneer]
action = "Found City"
actor_reqs =
{ "type", "name", "range"
"UnitFlag", "Cities", "Local"
"UnitState", "OnLivableTile", "Local"
"MinMoveFrags", "1", "Local"
}
target_reqs =
{ "type", "name", "range", "present"
"CityTile", "Claimed", "Local", FALSE
}
[actionenabler_build_city_domestic]
action = "Found City"
actor_reqs =
{ "type", "name", "range", "present"
"UnitFlag", "Cities", "Local", TRUE
"UnitState", "OnLivableTile", "Local", TRUE
"MinMoveFrags", "1", "Local", TRUE
"DiplRel", "Foreign", "Local", FALSE
}
[actionenabler_join_city]
action = "Join City"
actor_reqs =
{ "type", "name", "range", "present"
"UnitFlag", "AddToCity", "Local", TRUE
"DiplRel", "Foreign", "Local", FALSE
"MinMoveFrags", "1", "Local", TRUE
}
[actionenabler_attack_native]
action = "Attack"
actor_reqs =
{ "type", "name", "range", "present"
"UnitFlag", "NonMil", "Local", FALSE
"UnitClassFlag", "Missile", "Local", FALSE
"MinMoveFrags", "1", "Local", TRUE
"UnitState", "OnNativeTile", "Local", TRUE
"DiplRel", "War", "Local", TRUE
}
[actionenabler_attack_att_from_non_native]
action = "Attack"
actor_reqs =
{ "type", "name", "range", "present"
"UnitFlag", "NonMil", "Local", FALSE
"UnitClassFlag", "Missile", "Local", FALSE
"MinMoveFrags", "1", "Local", TRUE
"UnitClass", "Sea", "Local", TRUE
"DiplRel", "War", "Local", TRUE
}
[actionenabler_explode_missile]
action = "Suicide Attack"
actor_reqs =
{ "type", "name", "range", "present"
"UnitFlag", "NonMil", "Local", FALSE
"UnitClassFlag", "Missile", "Local", TRUE
"MinMoveFrags", "1", "Local", TRUE
"DiplRel", "War", "Local", TRUE
}
[actionenabler_conquer_city_native]
action = "Conquer City"
actor_reqs =
{ "type", "name", "range", "present"
"UnitClassFlag", "CanOccupyCity", "Local", TRUE
"UnitFlag", "NonMil", "Local", FALSE
"DiplRel", "War", "Local", TRUE
"MinMoveFrags", "1", "Local", TRUE
"UnitState", "OnLivableTile", "Local", TRUE
}
target_reqs =
{ "type", "name", "range", "present"
"MaxUnitsOnTile", "0", "Local", TRUE
}
[actionenabler_conquer_city_att_from_non_native]
action = "Conquer City"
actor_reqs =
{ "type", "name", "range", "present"
"UnitClassFlag", "CanOccupyCity", "Local", TRUE
"UnitFlag", "NonMil", "Local", FALSE
"DiplRel", "War", "Local", TRUE
"MinMoveFrags", "1", "Local", TRUE
"UnitClass", "Sea", "Local", TRUE
}
target_reqs =
{ "type", "name", "range", "present"
"MaxUnitsOnTile", "0", "Local", TRUE
}
[actionenabler_change_home_city]
action = "Home City"
actor_reqs =
{ "type", "name", "range", "present"
"UnitFlag", "NoHome", "Local", FALSE
"UnitState", "HasHomeCity", "Local", TRUE
"DiplRel", "Foreign", "Local", FALSE
}
[actionenabler_paradrop_base]
action = "Paradrop Unit"
actor_reqs =
{ "type", "name", "range", "present"
"UnitFlag", "Paratroopers", "Local", TRUE
"UnitState", "Transporting", "Local", FALSE
"Extra", "Antigrav Base","Local", TRUE
}
[actionenabler_paradrop_city]
action = "Paradrop Unit"
actor_reqs =
{ "type", "name", "range", "present"
"UnitFlag", "Paratroopers", "Local", TRUE
"UnitState", "Transporting", "Local", FALSE
"CityTile", "Center", "Local", TRUE
}
[actionenabler_upgrade_unit]
action = "Upgrade Unit"
actor_reqs =
{ "type", "name", "range", "present"
"DiplRel", "Foreign", "Local", FALSE
}
[actionenabler_airlift_unit]
action = "Airlift Unit"
actor_reqs =
{ "type", "name", "range", "present"
"UnitClassFlag", "Airliftable", "Local", TRUE
"UnitState", "Transporting", "Local", FALSE
"MinMoveFrags", "1", "Local", TRUE
}
[actionenabler_cultivate]
action = "Cultivate"
actor_reqs =
{ "type", "name", "range", "present"
"UnitFlag", "Settlers", "Local", TRUE
}
[actionenabler_plant]
action = "Plant"
actor_reqs =
{ "type", "name", "range", "present"
"UnitFlag", "Settlers", "Local", TRUE
}
[actionenabler_pillage]
action = "Pillage"
actor_reqs =
{ "type", "name", "range"
"UnitClassFlag", "CanPillage", "Local"
}
[actionenabler_fortify]
action = "Fortify"
actor_reqs =
{ "type", "name", "range", "present"
"UnitClassFlag", "CanFortify", "Local", TRUE
"UnitFlag", "Cant_Fortify", "Local", FALSE
}
[actionenabler_road]
action = "Build Road"
actor_reqs =
{ "type", "name", "range"
"UnitFlag", "Settlers", "Local"
}
[actionenabler_base]
action = "Build Base"
actor_reqs =
{ "type", "name", "range"
"UnitFlag", "Settlers", "Local"
}
[actionenabler_mining]
action = "Build Mine"
actor_reqs =
{ "type", "name", "range"
"UnitFlag", "Settlers", "Local"
}
target_reqs =
{ "type", "name", "range", "present"
"Terrain", "Thick Mountains", "Local", FALSE
}
[actionenabler_mine_mountains]
action = "Build Mine"
actor_reqs =
{ "type", "name", "range"
"UnitFlag", "Settlers", "Local"
"Tech", "Burrowing", "Player"
}
target_reqs =
{ "type", "name", "range"
"Terrain", "Thick Mountains", "Local"
}
[actionenabler_irrigate_src_ocean]
action = "Build Irrigation"
actor_reqs =
{ "type", "name", "range"
"UnitFlag", "Settlers" , "Local"
"Tech", "Manufacturing", "Player"
}
target_reqs =
{ "type", "name", "range"
"TerrainClass", "Oceanic", "CAdjacent"
}
[actionenabler_irrigate_src_green_river]
action = "Build Irrigation"
actor_reqs =
{ "type", "name", "range"
"UnitFlag", "Settlers", "Local"
"Tech", "Manufacturing", "Player"
}
target_reqs =
{ "type", "name", "range"
"Extra", "Green River", "Local"
}
[actionenabler_irrigate_src_brown_river]
action = "Build Irrigation"
actor_reqs =
{ "type", "name", "range"
"UnitFlag", "Settlers", "Local"
"Tech", "Manufacturing", "Player"
}
target_reqs =
{ "type", "name", "range"
"Extra", "Brown River", "Local"
}
[actionenabler_irrigate_src_green_river_adjacent]
action = "Build Irrigation"
actor_reqs =
{ "type", "name", "range"
"UnitFlag", "Settlers", "Local"
"Tech", "Water Flow", "Player"
}
target_reqs =
{ "type", "name", "range"
"Extra", "Green River", "CAdjacent"
}
[actionenabler_irrigate_src_brown_river_adjacent]
action = "Build Irrigation"
actor_reqs =
{ "type", "name", "range"
"UnitFlag", "Settlers", "Local"
"Tech", "Water Flow", "Player"
}
target_reqs =
{ "type", "name", "range"
"Extra", "Brown River", "CAdjacent"
}
[actionenabler_irrigate_src_citycenter]
action = "Build Irrigation"
actor_reqs =
{ "type", "name", "range"
"UnitFlag", "Settlers", "Local"
"Tech", "Water Flow", "Player"
}
target_reqs =
{ "type", "name", "range"
"CityTile", "Center", "Adjacent"
}
[actionenabler_irrigate_src_deep_pumping]
action = "Build Irrigation"
actor_reqs =
{ "type", "name", "range"
"UnitFlag", "Settlers", "Local"
"Tech", "Deep Pumping", "Player"
}
[actionenabler_deboard]
action = "Transport Deboard"
actor_reqs =
{ "type", "name", "range"
"UnitState", "OnLivableTile", "Local"
"UnitState", "Transported", "Local"
}
target_reqs =
{ "type", "name", "range"
"UnitState", "Transporting", "Local"
}
[actionenabler_board]
action = "Transport Board"
actor_reqs =
{ "type", "name", "range", "present"
"DiplRel", "Armistice", "Local", FALSE
"DiplRel", "War", "Local", FALSE
"DiplRel", "Cease-fire", "Local", FALSE
"DiplRel", "Peace", "Local", FALSE
"DiplRel", "Never met", "Local", FALSE
}
[actionenabler_unload]
action = "Transport Unload"
actor_reqs =
{ "type", "name", "range"
"UnitState", "Transporting", "Local"
}
target_reqs =
{ "type", "name", "range"
"UnitState", "OnLivableTile", "Local"
"UnitState", "Transported", "Local"
}
[actionenabler_disembark]
action = "Transport Disembark"
actor_reqs =
{ "type", "name", "range"
"UnitState", "Transported", "Local"
"MinMoveFrags", "1", "Local"
}
[actionenabler_embark]
action = "Transport Embark"
actor_reqs =
{ "type", "name", "range", "present"
"MinMoveFrags", "1", "Local", TRUE
"DiplRel", "Armistice", "Local", FALSE
"DiplRel", "War", "Local", FALSE
"DiplRel", "Cease-fire", "Local", FALSE
"DiplRel", "Peace", "Local", FALSE
"DiplRel", "Never met", "Local", FALSE
}
[borders]
; Base border radius from city.
radius_sq_city = 4
; Border radius square increased by this amount / point of city size
size_effect = 1
; Difference between city workable area and area permanently claimed by
; city (these tiles cannot be stolen by stronger border sources).
; 0 means exactly city workable area is immune to border stealing.
; Negative value means outer workable tiles can be stolen; highly negative
; value (more than max city radius_sq) means any workable tile can be stolen.
; If City_Radius_Sq is variable, so is the set of locked tiles; this is
; a squared value, so the radius of the ring of tiles which are workable
; but not locked (or vice versa) varies but the area is constant.
radius_sq_city_permanent = 0
[research]
; Method of calculating technology costs
; "Civ I|II" - Civ (I|II) style. Every new tech add base_tech_cost to
; cost of next tech.
; "Classic" - Cost of technology is:
; base_tech_cost * (1 + reqs) * sqrt(1 + reqs) / 2
; where reqs == number of requirement for tech, counted
; recursively.
; "Classic+" - Cost are read from tech.ruleset. Missing costs are
; generated by style "Classic".
; "Experimental" - Cost of technology is:
; base_tech_cost * (reqs^2 / (1 + sqrt(sqrt(reqs + 1)))
; - 0.5)
; where reqs == number of requirement for tech, counted
; recursively. Initial techs` cost will be base_tech_cost.
; "Experimental+" - Cost are read from tech.ruleset. Missing costs are
; generated by style "Experimental".
; "Linear" - Cost of technology is:
; base_tech_cost * reqs
; where reqs == number of requirement for tech, counted
; recursively.
tech_cost_style = "Classic"
; Base research cost. Used in tech cost styles where tech cost is generated.
; In other words: used everywhere unless the cost of *all* techs are
; specified and the tech cost style is "Experimental+" or "Classic+".
base_tech_cost = 20
; Technology leak from other civilizations
; "None" - No reduction of the technology cost.
; "Embassies" - Technology cost is reduced depending on the number of
; players which already know the tech and you have an
; embassy with.
; "All Players" - Technology cost is reduced depending on the number of
; all players (human, AI and barbarians) which already
; know the tech.
; "Normal Players" - Technology cost is reduced depending on the number of
; normal players (human and AI) which already know the
; tech.
tech_leakage = "None"
; Method of paying tech upkeep
; "None" - no upkeep
; "Basic" - upkeep is calculated as:
; <Cost of technology> / tech_upkeep_divider - tech_upkeep_free
; "Cities" - upkeep is calculated like "Basic", but multiplied by number of cities
tech_upkeep_style = "None"
; upkeep cost is divided by this value
tech_upkeep_divider = 2000
; Method of selecting techs given for free
; "Goal" - Towards player`s goal, random if no goal
; "Random" - Random researchable tech
; "Cheapest" - Cheapest researchable tech, random among equal cost ones
free_tech_method = "Goal"
[culture]
; Minimum culture points for cultural domination victory
victory_min_points = 1000
; How big lead relative to second best player is needed for victory
victory_lead_pct = 200
; How much existing history grows each turn. This makes older history
; of the same original value more valuable as newer history, as it has
; gained more interest.
history_interest_pml = 0
; How much each culture point affects the migration
; from/to the city. Each culture point count as this many permilles
; of a migration point.
migration_pml = 50
[calendar]
; Year in the beginning of the game
start_year = 250
; Year 1 instead of 0.
skip_year_0 = FALSE
; How many fragments each year has. In addition to this, "Turn_Fragments" effects are
; needed to control fragment accumulation.
; Value 0 here disables year advancement by fragment accumulation.
fragments = 4
; Calendar fragment names. If name is missing, only a fragment number +1 (so human readable
; numbers begin from 1 and not 0) is shown.
fragment_name0 = _("Q1")
fragment_name1 = _("Q2")
fragment_name2 = _("Q3")
fragment_name3 = _("Q4")
; What labels are used of positive and negative years.
positive_label = _("GE")
negative_label = _("BGE")
; /* <-- avoid gettext warnings
;
; Disaster types:
;
; name = translatable name as seen by user
; reqs = requirements for disaster to happen (see effects.ruleset
; and README.effects for help on requirements)
; frequency = how likely disaster is to occur
; effects
; - "DestroyBuilding" = Random building is destroyed
; - "ReducePopulation" = Reduce city size by one unless it's already 1
; - "ReducePopDestroy" = Reduce city size by one, possibly destroying the city
; - "EmptyFoodStock" = Remove all food from food stock
; - "EmptyProdStock" = Destroy current production
; - "Pollution" = One tile surrounding city polluted
; - "Fallout" = One tile surrounding city polluted with fallout
;
; */ <-- avoid gettext warnings
[disaster_earthquake]
name = _("Earthquake")
frequency = 10
effects = "DestroyBuilding"
[disaster_fire]
name = _("Fire")
frequency = 10
effects = "DestroyBuilding"
[disaster_radiation_burst]
name = _("Radiation Burst")
frequency = 10
effects = "ReducePopulation"
[disaster_rebels]
name = _("Rebels")
frequency = 10
effects = "EmptyfoodStock", "EmptyProdStock", "Fallout"
[disaster_alien_microbes]
name = _("Alien Microbes")
frequency = 10
effects = "ReducePopulation"
; /* <-- avoid gettext warnings
;
; Achievement types:
;
; name = translatable name as seen by user
; rule_name = (optional) internal name for savegames, rulesets
; etc; if not present, "name" is used for this
; purpose too. Since the name used in savegames must
; not change, if you want to rename an item after a
; ruleset has been released, you should set
; "rule_name" to the original value of "name".
; type = What event grants the achievement to player.
; See README.achievements for list of these types.
; unique = If TRUE, only first one reaching the achievement will
; get it. Defaults to TRUE
; value = Value to reach. Exact meaning of this depends on
; achievement type.
; culture = Amount of culture granted to player who gets achievement
; granted.
; first_msg = Message shown to first player gaining the achievement
; cons_msg = Message shown to consecutive players gaining the achievement
;
; */ <-- avoid gettext warnings
; No achievements in alien ruleset
;
; Trade settings
;
; IN = international, IC = intercontinental.
; For each of the trade route types:
; "pct" - Trade income %. If this is 0, trade route cannot be
; established at all
; "cancelling" - What to do to previously established traderoutes when they
; turn illegal
; "Active" - Keep them active (although they will only
; provide nonzero income if illegal due to
; trademindist rather than pct==0)
; "Inactive" - Keep them inactive
; "Cancel" - Cancel them altogether
; "bonus" - One-time bonuses granted when traderoute established
; "None" - No one-time bonus
; "Gold" - Bonus to gold
; "Science" - Bonus to research
; "Both" - Bonus to gold and research
;
[trade]
settings =
{ "type", "pct", "cancelling", "bonus"
"National", 100, "Cancel", "Both"
"NationalIC", 100, "Cancel", "Both"
"IN", 300, "Cancel", "Both"
"INIC", 300, "Cancel", "Both"
"Ally", 300, "Cancel", "Both"
"AllyIC", 300, "Cancel", "Both"
"Enemy", 300, "Cancel", "Both"
"EnemyIC", 300, "Cancel", "Both"
"Team", 300, "Cancel", "Both"
"TeamIC", 300, "Cancel", "Both"
}
; When are goods for the trade route chosen.
; "Leaving" - Goods to carry are assigned to unit when it`s built, or it changes homecity
; "Arrival" - Goods are chosen when trade route is established, when unit arrives to destination
goods_selection = "Arrival"
; /* <-- avoid gettext warnings
;
; Goods types:
;
; name = translatable name as seen by user
; rule_name = (optional) internal name for savegames, rulesets
; etc; if not present, "name" is used for this
; purpose too. Since the name used in savegames must
; not change, if you want to rename an item after a
; ruleset has been released, you should set
; "rule_name" to the original value of "name".
; reqs = requirements for a city to provide goods (see effects.ruleset
; and README.effects for help on requirements)
; from_pct = Income for the sending end of the trade route. Default is 100%
; This value is applied to both ends of bidirectional routes.
; to_pct = Income for the receiving end of the trade route. Default is 100%
; This value is not used at all in case of bidirectional routes.
; onetime_pct = Onetime bonuses when traderoute is established. Default is 100%
; flags
; - "Bidirectional" = Trade route carrying the goods does not have "from" and "to"
; ends, but both ends are considered the same.
; - "Depletes" = Trade route gets cancelled when the source city cannot provide
; goods any more. Bidirectional routes gets cancelled if either
; one of the involved cities cannot provide goods.
; helptext = Optional help text string; should escape all raw
; newlines so that xgettext parsing works
;
; */ <-- avoid gettext warnings
[goods_good]
name = _("Commodities")
; /* <-- avoid gettext warnings
;
; Clause types
;
; Clause types that are not listed here, are not enabled at all.
;
; type = Type of the clause, one of "Advance", "Gold", "Map", "Seamap",
; "City", "Ceasefire", "Peace", "Alliance", "Vision", "Embassy"
; giver_reqs = requirements that the giving side of the clause needs to fulfill
; (see effects.ruleset and README.effects for help on requirements)
; receiver_reqs = requirements that the receiving side of the clause needs to fulfill
;
; */ <-- avoid gettext warnings
[clause_advance]
type = "Advance"
[clause_gold]
type = "Gold"
[clause_map]
type = "Map"
[clause_seamap]
type = "Seamap"
[clause_city]
type = "City"
[clause_ceasefire]
type = "Ceasefire"
[clause_peace]
type = "Peace"
[clause_alliance]
type = "Alliance"
[clause_vision]
type = "Vision"
[clause_embassy]
type = "Embassy"
[playercolors]
background.r = 86
background.g = 86
background.b = 86
; Player colors for 32 players are defined below.
; Avoid greens, blues, and white / very pale colors (too easy to confuse
; with terrain).
; Avoid dark colors.
colorlist =
{ "r", "g", "b"
255, 0, 0
255, 255, 0
0, 255, 255
138, 43, 226
255, 165, 0
255, 0, 255
173, 216, 230
0, 255, 127
250, 128, 114
124, 252, 0
139, 0, 0
255, 192, 203
211, 211, 211
218, 112, 214
255, 20, 147
100, 149, 237
255, 215, 0
245, 222, 179
255, 255, 128
192, 255, 128
204, 255, 0
255, 211, 140
255, 79, 0
240, 145, 169
255, 219, 88
153, 17, 153
184, 134, 11
255, 102, 0
102, 205, 170
195, 33, 72
168, 153, 230
255, 250, 205
}
[teams]
; freeciv optional team names definition.
;
; names =
; _("Team 1"),
; _("Team 2"),
; _("Team 3"),
; _("Team 4"),
; etc...
[settings]
; freeciv game settings for the alien ruleset
set =
{ "name", "value", "lock"
"topology", "WRAPX|WRAPY|ISO|HEX", FALSE
"mapsize", "PLAYER", FALSE
"tilesperplayer", 300, FALSE
"aifill", 7, FALSE
"sciencebox", 150, FALSE
"foodbox", 150, FALSE
"revolen", 7, FALSE
"citymindist", 3, FALSE
"startunits", "cx", FALSE
"plrcolormode", "NATION_ORDER", FALSE
; Ruleset has no trait ranges, so player choosing EVEN would have
; no effect anyway
"traitdistribution", "FIXED", TRUE
}
| 412 | 0.844542 | 1 | 0.844542 | game-dev | MEDIA | 0.983093 | game-dev | 0.655812 | 1 | 0.655812 |
renaissance-benchmarks/renaissance | 2,389 | benchmarks/actors-reactors/reactors/reactors-container/shared/src/test/scala/io/reactors/container/r-catamorph-tests.scala | package io.reactors
package container
import org.scalacheck._
import org.scalacheck.Gen._
import org.scalacheck.Prop._
import io.reactors.algebra._
import io.reactors.test._
class RCatamorphCheck extends Properties("RCatamorph") with ExtendedProperties {
val sizes = detChoose(0, 500)
property("balanced CommuteCatamorph") = forAllNoShrink(sizes) { sz =>
val tree = CommuteCatamorph(Commute(0)(_ + _))
for (i <- 0 until sz) tree += i
def check(node: CommuteCatamorph.Node[Int]): Prop = node match {
case in: CommuteCatamorph.Inner[Int] =>
val locallyBalanced = s"locally balanced: ${node.localString}" |:
in.height == (1 + math.max(in.left.height, in.right.height))
val leftBalanced = s"left balanced: ${node.localString}" |:
(in.left.height == (in.height - 1) || in.left.height == (in.height - 2))
val rightBalanced = s"right balanced: ${node.localString}" |:
(in.right.height == (in.height - 1) || in.right.height == (in.height - 2))
locallyBalanced && leftBalanced && rightBalanced && check(in.left) &&
check(in.right)
case leaf: CommuteCatamorph.Leaf[Int] =>
"leaf height 0" |: leaf.height == 0
case empty: CommuteCatamorph.Empty[Int] =>
"empty height 0" |: empty.height == 0
}
check(tree.root)
}
property("balanced MonoidCatamorph") = forAllNoShrink(sizes) { sz =>
val tree = MonoidCatamorph(Monoid(0)(_ + _))
for (i <- 0 until sz) tree += i
def check(node: MonoidCatamorph.Node[Int]): Prop = node match {
case in: MonoidCatamorph.Inner[Int] =>
val locallyBalanced = s"locally balanced: ${node.localString}" |:
in.height == (1 + math.max(in.left.height, in.right.height))
val leftBalanced = s"left balanced: ${node.localString}" |:
(in.left.height == (in.height - 1) || in.left.height == (in.height - 2))
val rightBalanced = s"right balanced: ${node.localString}" |:
(in.right.height == (in.height - 1) || in.right.height == (in.height - 2))
locallyBalanced && leftBalanced && rightBalanced && check(in.left) &&
check(in.right)
case leaf: MonoidCatamorph.Leaf[Int] =>
"leaf height 0" |: leaf.height == 0
case empty: MonoidCatamorph.Empty[Int] =>
"empty height 0" |: empty.height == 0
}
check(tree.root)
}
} | 412 | 0.6867 | 1 | 0.6867 | game-dev | MEDIA | 0.191234 | game-dev | 0.946738 | 1 | 0.946738 |
dotnet/dotnet | 3,248 | src/runtime/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/DependentHandle.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Runtime
{
public struct DependentHandle : IDisposable
{
private IntPtr _handle;
public DependentHandle(object? target, object? dependent) =>
_handle = RuntimeImports.RhHandleAllocDependent(target, dependent);
public bool IsAllocated => _handle != IntPtr.Zero;
public object? Target
{
get
{
IntPtr handle = _handle;
if ((nint)handle == 0)
{
ThrowHelper.ThrowInvalidOperationException();
}
return RuntimeImports.RhHandleGet(handle);
}
set
{
IntPtr handle = _handle;
if ((nint)handle == 0 || value is not null)
{
ThrowHelper.ThrowInvalidOperationException();
}
RuntimeImports.RhHandleSet(handle, null);
}
}
public object? Dependent
{
get
{
IntPtr handle = _handle;
if ((nint)handle == 0)
{
ThrowHelper.ThrowInvalidOperationException();
}
RuntimeImports.RhHandleGetDependent(handle, out object? dependent);
return dependent;
}
set
{
IntPtr handle = _handle;
if ((nint)handle == 0)
{
ThrowHelper.ThrowInvalidOperationException();
}
RuntimeImports.RhHandleSetDependentSecondary(handle, value);
}
}
public (object? Target, object? Dependent) TargetAndDependent
{
get
{
IntPtr handle = _handle;
if ((nint)handle == 0)
{
ThrowHelper.ThrowInvalidOperationException();
}
object? target = RuntimeImports.RhHandleGetDependent(handle, out object? dependent);
return (target, dependent);
}
}
internal object? UnsafeGetTarget()
{
return RuntimeImports.RhHandleGet(_handle);
}
internal object? UnsafeGetTargetAndDependent(out object? dependent)
{
return RuntimeImports.RhHandleGetDependent(_handle, out dependent);
}
internal void UnsafeSetTargetToNull()
{
RuntimeImports.RhHandleSet(_handle, null);
}
internal void UnsafeSetDependent(object? dependent)
{
RuntimeImports.RhHandleSetDependentSecondary(_handle, dependent);
}
public void Dispose()
{
// Forces the DependentHandle back to non-allocated state
// (if not already there) and frees the handle if needed.
IntPtr handle = _handle;
if ((nint)handle != 0)
{
_handle = IntPtr.Zero;
RuntimeImports.RhHandleFree(handle);
}
}
}
}
| 412 | 0.854056 | 1 | 0.854056 | game-dev | MEDIA | 0.627576 | game-dev | 0.705295 | 1 | 0.705295 |
lewislepton/kha-tutorial-series | 1,314 | 109_reflectRefineLibrary/Libraries/lkl/Sources/lkl/particle/Emitter.hx | package lkl.particle;
import kha.graphics2.Graphics;
using kha.graphics2.GraphicsExtension;
import kha.Color;
import kha.Assets;
import lkl.Entity;
import lkl.particle.Particle;
import lkl.tool.Util;
class Emitter extends Entity {
public var arParticle:Array<Particle>;
public var amount:Int;
public var power = 3.0;
public function new(?amount:Int = 3, ?power:Float = 3.0){
super(0, 0, 0, 0);
this.amount = amount;
this.power = power;
arParticle = [];
}
override public function update(){
super.update();
var p = arParticle.length;
while (p --> 0){
arParticle[p].update();
if (arParticle[p].position.x <= 0 || arParticle[p].position.x >= Main.WIDTH || arParticle[p].position.y <= 0 || arParticle[p].position.y >= Main.HEIGHT){
arParticle.splice(p, 1);
}
}
}
override public function render(graphics:Graphics){
super.render(graphics);
for (particle in arParticle){
particle.render(graphics);
}
}
public function spawn(?x:Float, ?y:Float, ?width:Float = 2.0, ?height:Float = 2.0){
for (i in 0 ... amount){
var particle = new Particle(x, y, width, height);
particle.acceleration = -0.5;
particle.velocity.x = Util.randomRangeFloat(-power, power);
particle.velocity.y = Util.randomRangeFloat(-power, power);
arParticle.push(particle);
}
}
} | 412 | 0.655564 | 1 | 0.655564 | game-dev | MEDIA | 0.871348 | game-dev,graphics-rendering | 0.969814 | 1 | 0.969814 |
rathena/rathena | 44,556 | src/map/battleground.cpp | // Copyright (c) rAthena Dev Teams - Licensed under GNU GPL
// For more information, see LICENCE in the main folder
#include "battleground.hpp"
#include <unordered_map>
#include <common/cbasetypes.hpp>
#include <common/malloc.hpp>
#include <common/nullpo.hpp>
#include <common/random.hpp>
#include <common/showmsg.hpp>
#include <common/strlib.hpp>
#include <common/timer.hpp>
#include <common/utilities.hpp>
#include "battle.hpp"
#include "clif.hpp"
#include "guild.hpp"
#include "homunculus.hpp"
#include "mapreg.hpp"
#include "mercenary.hpp"
#include "mob.hpp"
#include "npc.hpp"
#include "party.hpp"
#include "pc.hpp"
#include "pet.hpp"
using namespace rathena;
BattlegroundDatabase battleground_db;
std::unordered_map<int32, std::shared_ptr<s_battleground_data>> bg_team_db;
std::vector<std::shared_ptr<s_battleground_queue>> bg_queues;
int32 bg_queue_count = 1;
const std::string BattlegroundDatabase::getDefaultLocation() {
return std::string(db_path) + "/battleground_db.yml";
}
/**
* Reads and parses an entry from the battleground_db
* @param node: The YAML node containing the entry
* @return count of successfully parsed rows
*/
uint64 BattlegroundDatabase::parseBodyNode(const ryml::NodeRef& node) {
uint32 id;
if (!this->asUInt32(node, "Id", id))
return 0;
std::shared_ptr<s_battleground_type> bg = this->find(id);
bool exists = bg != nullptr;
if (!exists) {
if (!this->nodesExist(node, { "Name", "Locations" }))
return 0;
bg = std::make_shared<s_battleground_type>();
bg->id = id;
}
if (this->nodeExists(node, "Name")) {
std::string name;
if (!this->asString(node, "Name", name))
return 0;
name.resize(NAME_LENGTH);
bg->name = name;
}
if (this->nodeExists(node, "MinPlayers")) {
int32 min;
if (!this->asInt32(node, "MinPlayers", min))
return 0;
if (min < 1) {
this->invalidWarning(node["MinPlayers"], "Minimum players %d cannot be less than 1, capping to 1.\n", min);
min = 1;
}
if (min * 2 > MAX_BG_MEMBERS) {
this->invalidWarning(node["MinPlayers"], "Minimum players %d exceeds MAX_BG_MEMBERS, capping to %d.\n", min, MAX_BG_MEMBERS / 2);
min = MAX_BG_MEMBERS / 2;
}
bg->required_players = min;
} else {
if (!exists)
bg->required_players = 1;
}
if (this->nodeExists(node, "MaxPlayers")) {
int32 max;
if (!this->asInt32(node, "MaxPlayers", max))
return 0;
if (max < 1) {
this->invalidWarning(node["MaxPlayers"], "Maximum players %d cannot be less than 1, capping to 1.\n", max);
max = 1;
}
if (max * 2 > MAX_BG_MEMBERS) {
this->invalidWarning(node["MaxPlayers"], "Maximum players %d exceeds MAX_BG_MEMBERS, capping to %d.\n", max, MAX_BG_MEMBERS / 2);
max = MAX_BG_MEMBERS / 2;
}
bg->max_players = max;
} else {
if (!exists)
bg->max_players = MAX_BG_MEMBERS / 2;
}
if (this->nodeExists(node, "MinLevel")) {
int32 min;
if (!this->asInt32(node, "MinLevel", min))
return 0;
if (min > MAX_LEVEL) {
this->invalidWarning(node["MinLevel"], "Minimum level %d exceeds MAX_LEVEL, capping to %d.\n", min, MAX_LEVEL);
min = MAX_LEVEL;
}
bg->min_lvl = min;
} else {
if (!exists)
bg->min_lvl = 1;
}
if (this->nodeExists(node, "MaxLevel")) {
int32 max;
if (!this->asInt32(node, "MaxLevel", max))
return 0;
if (max > MAX_LEVEL) {
this->invalidWarning(node["MaxLevel"], "Maximum level %d exceeds MAX_LEVEL, capping to %d.\n", max, MAX_LEVEL);
max = MAX_LEVEL;
}
bg->max_lvl = max;
} else {
if (!exists)
bg->max_lvl = MAX_LEVEL;
}
if (this->nodeExists(node, "Deserter")) {
uint32 deserter;
if (!this->asUInt32(node, "Deserter", deserter))
return 0;
bg->deserter_time = deserter;
} else {
if (!exists)
bg->deserter_time = 600;
}
if (this->nodeExists(node, "StartDelay")) {
uint32 delay;
if (!this->asUInt32(node, "StartDelay", delay))
return 0;
bg->start_delay = delay;
} else {
if (!exists)
bg->start_delay = 0;
}
if (this->nodeExists(node, "Join")) {
const auto& joinNode = node["Join"];
if (this->nodeExists(joinNode, "Solo")) {
bool active;
if (!this->asBool(joinNode, "Solo", active))
return 0;
bg->solo = active;
} else {
if (!exists)
bg->solo = true;
}
if (this->nodeExists(joinNode, "Party")) {
bool active;
if (!this->asBool(joinNode, "Party", active))
return 0;
bg->party = active;
} else {
if (!exists)
bg->party = true;
}
if (this->nodeExists(joinNode, "Guild")) {
bool active;
if (!this->asBool(joinNode, "Guild", active))
return 0;
bg->guild = active;
} else {
if (!exists)
bg->guild = true;
}
} else {
if (!exists) {
bg->solo = true;
bg->party = true;
bg->guild = true;
}
}
if (this->nodeExists(node, "JobRestrictions")) {
const auto& jobsNode = node["JobRestrictions"];
for (const auto& jobit : jobsNode) {
std::string job_name;
c4::from_chars(jobit.key(), &job_name);
std::string job_name_constant = "JOB_" + job_name;
int64 constant;
if (!script_get_constant(job_name_constant.c_str(), &constant)) {
this->invalidWarning(node["JobRestrictions"], "Job %s does not exist.\n", job_name.c_str());
continue;
}
bool active;
if (!this->asBool(jobsNode, job_name, active))
return 0;
if (active)
bg->job_restrictions.push_back(static_cast<int32>(constant));
else
util::vector_erase_if_exists(bg->job_restrictions, static_cast<int32>(constant));
}
}
if (this->nodeExists(node, "Locations")) {
int32 count = 0;
for (const auto& location : node["Locations"]) {
s_battleground_map map_entry;
if (this->nodeExists(location, "Map")) {
std::string map_name;
if (!this->asString(location, "Map", map_name))
return 0;
map_entry.mapindex = mapindex_name2id(map_name.c_str());
if (map_entry.mapindex == 0) {
this->invalidWarning(location["Map"], "Invalid battleground map name %s, skipping.\n", map_name.c_str());
return 0;
}
if( map_mapindex2mapid( map_entry.mapindex ) < 0 ){
// Ignore silently, the map is on another mapserver
return 0;
}
}
if (this->nodeExists(location, "StartEvent")) {
if (!this->asString(location, "StartEvent", map_entry.bgcallscript))
return 0;
if (map_entry.bgcallscript.length() > EVENT_NAME_LENGTH) {
this->invalidWarning(location["StartEvent"], "StartEvent \"%s\" exceeds maximum of %d characters, capping...\n", map_entry.bgcallscript.c_str(), EVENT_NAME_LENGTH - 1);
}
map_entry.bgcallscript.resize(EVENT_NAME_LENGTH);
if (map_entry.bgcallscript.find("::On") == std::string::npos) {
this->invalidWarning(location["StartEvent"], "Battleground StartEvent label %s should begin with '::On', skipping.\n", map_entry.bgcallscript.c_str());
return 0;
}
}
std::vector<std::string> team_list = { "TeamA", "TeamB" };
for (const auto &it : team_list) {
c4::csubstr team_name = c4::to_csubstr(it);
const ryml::NodeRef& team = location;
if (this->nodeExists(team, it)) {
s_battleground_team *team_ptr;
if (it.find("TeamA") != std::string::npos)
team_ptr = &map_entry.team1;
else if (it.find("TeamB") != std::string::npos)
team_ptr = &map_entry.team2;
else {
this->invalidWarning(team[team_name], "An invalid Team is defined.\n");
return 0;
}
if (this->nodeExists(team[team_name], "RespawnX")) {
uint16 warp_x;
if (!this->asUInt16(team[team_name], "RespawnX", warp_x))
return 0;
if (warp_x == 0) {
this->invalidWarning(node["RespawnX"], "RespawnX has to be greater than zero.\n");
return 0;
}
map_data *md = map_getmapdata(map_mapindex2mapid(map_entry.mapindex));
if (warp_x >= md->xs) {
this->invalidWarning(node["RespawnX"], "RespawnX has to be smaller than %hu.\n", md->xs);
return 0;
}
team_ptr->warp_x = warp_x;
}
if (this->nodeExists(team[team_name], "RespawnY")) {
uint16 warp_y;
if (!this->asUInt16(team[team_name], "RespawnY", warp_y))
return 0;
if (warp_y == 0) {
this->invalidWarning(node["RespawnY"], "RespawnY has to be greater than zero.\n");
return 0;
}
map_data *md = map_getmapdata(map_mapindex2mapid(map_entry.mapindex));
if (warp_y >= md->ys) {
this->invalidWarning(node["RespawnY"], "RespawnY has to be smaller than %hu.\n", md->ys);
return 0;
}
team_ptr->warp_y = warp_y;
}
if (this->nodeExists(team[team_name], "DeathEvent")) {
if (!this->asString(team[team_name], "DeathEvent", team_ptr->death_event))
return 0;
team_ptr->death_event.resize(EVENT_NAME_LENGTH);
if (team_ptr->death_event.find("::On") == std::string::npos) {
this->invalidWarning(team["DeathEvent"], "Battleground DeathEvent label %s should begin with '::On', skipping.\n", team_ptr->death_event.c_str());
return 0;
}
}
if (this->nodeExists(team[team_name], "QuitEvent")) {
if (!this->asString(team[team_name], "QuitEvent", team_ptr->quit_event))
return 0;
team_ptr->quit_event.resize(EVENT_NAME_LENGTH);
if (team_ptr->quit_event.find("::On") == std::string::npos) {
this->invalidWarning(team["QuitEvent"], "Battleground QuitEvent label %s should begin with '::On', skipping.\n", team_ptr->quit_event.c_str());
return 0;
}
}
if (this->nodeExists(team[team_name], "ActiveEvent")) {
if (!this->asString(team[team_name], "ActiveEvent", team_ptr->active_event))
return 0;
team_ptr->active_event.resize(EVENT_NAME_LENGTH);
if (team_ptr->active_event.find("::On") == std::string::npos) {
this->invalidWarning(team["ActiveEvent"], "Battleground ActiveEvent label %s should begin with '::On', skipping.\n", team_ptr->active_event.c_str());
return 0;
}
}
if (this->nodeExists(team[team_name], "Variable")) {
if (!this->asString(team[team_name], "Variable", team_ptr->bg_id_var))
return 0;
team_ptr->bg_id_var.resize(NAME_LENGTH);
}
map_entry.id = count++;
map_entry.isReserved = false;
}
}
bg->maps.push_back(map_entry);
}
}
if (!exists)
this->put(id, bg);
return 1;
}
/**
* Search for a battleground based on the given name
* @param name: Battleground name
* @return s_battleground_type on success or nullptr on failure
*/
std::shared_ptr<s_battleground_type> bg_search_name(const char *name)
{
for (const auto &entry : battleground_db) {
auto bg = entry.second;
if (!stricmp(bg->name.c_str(), name))
return bg;
}
return nullptr;
}
/**
* Search for a Battleground queue based on the given queue ID
* @param queue_id: Queue ID
* @return s_battleground_queue on success or nullptr on failure
*/
std::shared_ptr<s_battleground_queue> bg_search_queue(int32 queue_id)
{
for (const auto &queue : bg_queues) {
if (queue_id == queue->queue_id)
return queue;
}
return nullptr;
}
/**
* Search for an available player in Battleground
* @param bg: Battleground data
* @return map_session_data
*/
map_session_data* bg_getavailablesd(s_battleground_data *bg)
{
nullpo_retr(nullptr, bg);
for (const auto &member : bg->members) {
if (member.sd != nullptr)
return member.sd;
}
return nullptr;
}
/**
* Delete a Battleground team from the db
* @param bg_id: Battleground ID
* @return True on success or false otherwise
*/
bool bg_team_delete(int32 bg_id)
{
std::shared_ptr<s_battleground_data> bgteam = util::umap_find(bg_team_db, bg_id);
if (bgteam) {
for (const auto &pl_sd : bgteam->members) {
bg_send_dot_remove(pl_sd.sd);
pl_sd.sd->bg_id = 0;
}
bg_team_db.erase(bg_id);
return true;
}
return false;
}
/**
* Warps a Battleground team
* @param bg_id: Battleground ID
* @param mapindex: Map Index
* @param x: X coordinate
* @param y: Y coordinate
* @return True on success or false otherwise
*/
bool bg_team_warp(int32 bg_id, uint16 mapindex, int16 x, int16 y)
{
std::shared_ptr<s_battleground_data> bgteam = util::umap_find(bg_team_db, bg_id);
if (bgteam) {
for (const auto &pl_sd : bgteam->members)
pc_setpos(pl_sd.sd, mapindex, x, y, CLR_TELEPORT);
return true;
}
return false;
}
/**
* Remove a player's Battleground map marker
* @param sd: Player data
*/
void bg_send_dot_remove(map_session_data *sd)
{
nullpo_retv(sd);
if( sd && sd->bg_id )
clif_bg_xy_remove(sd);
return;
}
/**
* Join a player to a Battleground team
* @param bg_id: Battleground ID
* @param sd: Player data
* @param is_queue: Joined from queue
* @return True on success or false otherwise
*/
bool bg_team_join(int32 bg_id, map_session_data *sd, bool is_queue)
{
if (!sd || sd->bg_id)
return false;
std::shared_ptr<s_battleground_data> bgteam = util::umap_find(bg_team_db, bg_id);
if (bgteam) {
if (bgteam->members.size() == MAX_BG_MEMBERS)
return false; // No free slots
s_battleground_member_data member = {};
sd->bg_id = bg_id;
member.sd = sd;
member.x = sd->x;
member.y = sd->y;
if (is_queue) { // Save the location from where the person entered the battleground
member.entry_point.map = sd->mapindex;
member.entry_point.x = sd->x;
member.entry_point.y = sd->y;
}
bgteam->members.push_back(member);
guild_send_dot_remove(sd);
for (const auto &pl_sd : bgteam->members) {
if (pl_sd.sd != sd)
clif_hpmeter_single( *sd, pl_sd.sd->id, pl_sd.sd->battle_status.hp, pl_sd.sd->battle_status.max_hp );
}
clif_bg_hp(sd);
clif_bg_xy(sd);
return true;
}
return false;
}
/**
* Remove a player from Battleground team
* @param sd: Player data
* @param quit: True if closed client or false otherwise
* @param deserter: Whether to apply the deserter status or not
* @return Remaining count in Battleground team or -1 on failure
*/
int32 bg_team_leave(map_session_data *sd, bool quit, bool deserter)
{
if (!sd || !sd->bg_id)
return -1;
bg_send_dot_remove(sd);
int32 bg_id = sd->bg_id;
std::shared_ptr<s_battleground_data> bgteam = util::umap_find(bg_team_db, bg_id);
sd->bg_id = 0;
if (bgteam) {
// Warping members out only applies to the Battleground Queue System
if (battle_config.feature_bgqueue) {
auto member = bgteam->members.begin();
while (member != bgteam->members.end()) {
if (member->sd == sd) {
if (member->entry_point.map != 0 && !map_getmapflag(map_mapindex2mapid(member->entry_point.map), MF_NOSAVE))
pc_setpos(sd, member->entry_point.map, member->entry_point.x, member->entry_point.y, CLR_TELEPORT);
else
pc_setpos( sd, mapindex_name2id( sd->status.save_point.map ), sd->status.save_point.x, sd->status.save_point.y, CLR_TELEPORT ); // Warp to save point if the entry map has no save flag.
bgteam->members.erase(member);
break;
} else
member++;
}
}
char output[CHAT_SIZE_MAX];
if (quit)
sprintf(output, "Server: %s has quit the game...", sd->status.name);
else
sprintf(output, "Server: %s is leaving the battlefield...", sd->status.name);
clif_bg_message(bgteam.get(), 0, "Server", output, strlen(output) + 1);
if (!bgteam->logout_event.empty() && quit)
npc_event(sd, bgteam->logout_event.c_str(), 0);
if (deserter) {
std::shared_ptr<s_battleground_type> bg = battleground_db.find(bg_id);
if (bg)
sc_start(nullptr, sd, SC_ENTRY_QUEUE_NOTIFY_ADMISSION_TIME_OUT, 100, 1, static_cast<t_tick>(bg->deserter_time) * 1000); // Deserter timer
}
return static_cast<int32>( bgteam->members.size() );
}
return -1;
}
/**
* Respawn a Battleground player
* @param sd: Player data
* @return True on success or false otherwise
*/
bool bg_member_respawn(map_session_data *sd)
{
if (!sd || !sd->bg_id || !pc_isdead(sd))
return false;
std::shared_ptr<s_battleground_data> bgteam = util::umap_find(bg_team_db, sd->bg_id);
if (bgteam) {
if (bgteam->cemetery.map == 0)
return false; // Respawn not handled by Core
pc_setpos(sd, bgteam->cemetery.map, bgteam->cemetery.x, bgteam->cemetery.y, CLR_OUTSIGHT);
status_revive(sd, 1, 100);
return true; // Warped
}
return false;
}
/**
* Initialize Battleground data
* @param mapindex: Map Index
* @param rx: Return X coordinate (on death)
* @param ry: Return Y coordinate (on death)
* @param ev: Logout NPC Event
* @param dev: Death NPC Event
* @return Battleground ID
*/
int32 bg_create(uint16 mapindex, s_battleground_team* team)
{
int32 bg_team_counter = 1;
while (bg_team_db.find(bg_team_counter) != bg_team_db.end())
bg_team_counter++;
bg_team_db[bg_team_counter] = std::make_shared<s_battleground_data>();
std::shared_ptr<s_battleground_data> bg = util::umap_find(bg_team_db, bg_team_counter);
bg->id = bg_team_counter;
bg->cemetery.map = mapindex;
bg->cemetery.x = team->warp_x;
bg->cemetery.y = team->warp_y;
bg->logout_event = team->quit_event.c_str();
bg->die_event = team->death_event.c_str();
bg->active_event = team->active_event.c_str();
return bg->id;
}
/**
* Get an object's Battleground ID
* @param bl: Object
* @return Battleground ID
*/
int32 bg_team_get_id(block_list *bl)
{
nullpo_ret(bl);
switch( bl->type ) {
case BL_PC:
return ((TBL_PC*)bl)->bg_id;
case BL_PET:
if( ((TBL_PET*)bl)->master )
return ((TBL_PET*)bl)->master->bg_id;
break;
case BL_MOB: {
map_session_data *msd;
mob_data *md = (TBL_MOB*)bl;
if( md->special_state.ai && (msd = map_id2sd(md->master_id)) != nullptr )
return msd->bg_id;
return md->bg_id;
}
case BL_HOM:
if( ((TBL_HOM*)bl)->master )
return ((TBL_HOM*)bl)->master->bg_id;
break;
case BL_MER:
if( ((TBL_MER*)bl)->master )
return ((TBL_MER*)bl)->master->bg_id;
break;
case BL_SKILL:
return ((TBL_SKILL*)bl)->group->bg_id;
}
return 0;
}
/**
* Send a Battleground chat message
* @param sd: Player data
* @param mes: Message
* @param len: Message length
*/
void bg_send_message(map_session_data *sd, const char *mes, size_t len)
{
nullpo_retv(sd);
if (sd->bg_id == 0)
return;
std::shared_ptr<s_battleground_data> bgteam = util::umap_find(bg_team_db, sd->bg_id);
if (bgteam)
clif_bg_message(bgteam.get(), sd->id, sd->status.name, mes, len);
return;
}
/**
* Update a player's Battleground minimap icon
* @see DBApply
*/
int32 bg_send_xy_timer_sub(std::shared_ptr<s_battleground_data> bg)
{
map_session_data *sd;
for (auto &pl_sd : bg->members) {
sd = pl_sd.sd;
if (sd->x != pl_sd.x || sd->y != pl_sd.y) { // xy update
pl_sd.x = sd->x;
pl_sd.y = sd->y;
clif_bg_xy(sd);
}
}
return 0;
}
/**
* Update a player's Battleground minimap icon
* @param tid: Timer ID
* @param tick: Timer
* @param id: ID
* @return 0 on success or 1 otherwise
*/
TIMER_FUNC(bg_send_xy_timer)
{
for (const auto &entry : bg_team_db)
bg_send_xy_timer_sub(entry.second);
return 0;
}
/**
* Mark a Battleground as ready to begin queuing for a free map
* @param tid: Timer ID
* @param tick: Timer
* @param id: ID
* @return 0 on success or 1 otherwise
*/
static TIMER_FUNC(bg_on_ready_loopback)
{
int32 queue_id = (int32)data;
std::shared_ptr<s_battleground_queue> queue = bg_search_queue(queue_id);
if (queue == nullptr) {
ShowError("bg_on_ready_loopback: Invalid battleground queue %d.\n", queue_id);
return 1;
}
std::shared_ptr<s_battleground_type> bg = battleground_db.find(queue->id);
if (bg) {
bg_queue_on_ready(bg->name.c_str(), queue);
return 0;
} else {
ShowError("bg_on_ready_loopback: Can't find battleground %d in the battlegrounds database.\n", queue->id);
return 1;
}
}
/**
* Reset Battleground queue data if players don't accept in time
* @param tid: Timer ID
* @param tick: Timer
* @param id: ID
* @return 0 on success or 1 otherwise
*/
static TIMER_FUNC(bg_on_ready_expire)
{
int32 queue_id = (int32)data;
std::shared_ptr<s_battleground_queue> queue = bg_search_queue(queue_id);
if (queue == nullptr) {
ShowError("bg_on_ready_expire: Invalid battleground queue %d.\n", queue_id);
return 1;
}
std::string bg_name = battleground_db.find(queue->id)->name;
for (const auto &sd : queue->teama_members) {
clif_bg_queue_apply_result(BG_APPLY_QUEUE_FINISHED, bg_name.c_str(), sd);
clif_bg_queue_entry_init(sd);
}
for (const auto &sd : queue->teamb_members) {
clif_bg_queue_apply_result(BG_APPLY_QUEUE_FINISHED, bg_name.c_str(), sd);
clif_bg_queue_entry_init(sd);
}
bg_queue_clear(queue, true);
return 0;
}
/**
* Start a Battleground when all players have accepted
* @param tid: Timer ID
* @param tick: Timer
* @param id: ID
* @return 0 on success or 1 otherwise
*/
static TIMER_FUNC(bg_on_ready_start)
{
int32 queue_id = (int32)data;
std::shared_ptr<s_battleground_queue> queue = bg_search_queue(queue_id);
if (queue == nullptr) {
ShowError("bg_on_ready_start: Invalid battleground queue %d.\n", queue_id);
return 1;
}
queue->tid_start = INVALID_TIMER;
bg_queue_start_battleground(queue);
return 0;
}
/**
* Check if the given player is in a battleground
* @param sd: Player data
* @return True if in a battleground or false otherwise
*/
bool bg_player_is_in_bg_map(map_session_data *sd)
{
nullpo_retr(false, sd);
for (const auto &pair : battleground_db) {
for (const auto &it : pair.second->maps) {
if (it.mapindex == sd->mapindex)
return true;
}
}
return false;
}
/**
* Battleground status change check
* @param sd: Player data
* @param name: Battleground name
* @return True if the player is good to join a queue or false otherwise
*/
static bool bg_queue_check_status(map_session_data* sd, const char *name)
{
nullpo_retr(false, sd);
if (!sd->sc.empty()) {
if (sd->sc.getSCE(SC_ENTRY_QUEUE_APPLY_DELAY)) { // Exclude any player who's recently left a battleground queue
char buf[CHAT_SIZE_MAX];
sprintf(buf, msg_txt(sd, 339), static_cast<int32>((get_timer(sd->sc.getSCE(SC_ENTRY_QUEUE_APPLY_DELAY)->timer)->tick - gettick()) / 1000)); // You can't apply to a battleground queue for %d seconds due to recently leaving one.
clif_bg_queue_apply_result(BG_APPLY_NONE, name, sd);
clif_messagecolor(sd, color_table[COLOR_LIGHT_GREEN], buf, false, SELF);
return false;
}
if (sd->sc.getSCE(SC_ENTRY_QUEUE_NOTIFY_ADMISSION_TIME_OUT)) { // Exclude any player who's recently deserted a battleground
char buf[CHAT_SIZE_MAX];
int32 status_tick = static_cast<int32>(DIFF_TICK(get_timer(sd->sc.getSCE(SC_ENTRY_QUEUE_NOTIFY_ADMISSION_TIME_OUT)->timer)->tick, gettick()) / 1000);
sprintf(buf, msg_txt(sd, 338), status_tick / 60, status_tick % 60); // You can't apply to a battleground queue due to recently deserting a battleground. Time remaining: %d minutes and %d seconds.
clif_bg_queue_apply_result(BG_APPLY_NONE, name, sd);
clif_messagecolor(sd, color_table[COLOR_LIGHT_GREEN], buf, false, SELF);
return false;
}
}
return true;
}
/**
* Check to see if a Battleground is joinable
* @param bg: Battleground data
* @param sd: Player data
* @param name: Battleground name
* @return True on success or false otherwise
*/
bool bg_queue_check_joinable(std::shared_ptr<s_battleground_type> bg, map_session_data *sd, const char *name)
{
nullpo_retr(false, sd);
for (const auto &job : bg->job_restrictions) { // Check class requirement
if (sd->status.class_ == job) {
clif_bg_queue_apply_result(BG_APPLY_PLAYER_CLASS, name, sd);
return false;
}
}
if (bg->min_lvl > 0 && sd->status.base_level < bg->min_lvl) { // Check minimum level requirement
clif_bg_queue_apply_result(BG_APPLY_PLAYER_LEVEL, name, sd);
return false;
}
if (bg->max_lvl > 0 && sd->status.base_level > bg->max_lvl) { // Check maximum level requirement
clif_bg_queue_apply_result(BG_APPLY_PLAYER_LEVEL, name, sd);
return false;
}
if (!bg_queue_check_status(sd, name)) // Check status blocks
return false;
if (bg_player_is_in_bg_map(sd)) { // Is the player currently in a battleground map? Reject them.
clif_bg_queue_apply_result(BG_APPLY_NONE, name, sd);
clif_messagecolor(sd, color_table[COLOR_LIGHT_GREEN], msg_txt(sd, 337), false, SELF); // You can't apply to a battleground queue from this map.
return false;
}
if (battle_config.bgqueue_nowarp_mapflag > 0 && map_getmapflag(sd->m, MF_NOWARP)) { // Check player's current position for mapflag check
clif_bg_queue_apply_result(BG_APPLY_NONE, name, sd);
clif_messagecolor(sd, color_table[COLOR_LIGHT_GREEN], msg_txt(sd, 337), false, SELF); // You can't apply to a battleground queue from this map.
return false;
}
return true;
}
/**
* Mark a map as reserved for a Battleground
* @param name: Battleground map name
* @param state: Whether to mark reserved or not
* @param ended: Whether the Battleground event is complete; players getting prize
* @return True on success or false otherwise
*/
bool bg_queue_reservation(const char *name, bool state, bool ended)
{
uint16 mapindex = mapindex_name2id(name);
for (auto &pair : battleground_db) {
for (auto &map : pair.second->maps) {
if (map.mapindex == mapindex) {
map.isReserved = state;
for (auto &queue : bg_queues) {
if (queue->map == &map) {
if (ended) // The ended flag is applied from bg_reserve (bg_unbook clears it for the next queue)
queue->state = QUEUE_STATE_ENDED;
if (!state)
bg_queue_clear(queue, true);
}
}
return true;
}
}
}
return false;
}
/**
* Join as an individual into a Battleground
* @param name: Battleground name
* @param sd: Player who requested to join the battlegrounds
*/
void bg_queue_join_solo(const char *name, map_session_data *sd)
{
if (!sd) {
ShowError("bg_queue_join_solo: Tried to join non-existent player\n.");
return;
}
std::shared_ptr<s_battleground_type> bg = bg_search_name(name);
if (!bg) {
ShowWarning("bq_queue_join_solo: Could not find battleground \"%s\" requested by %s (AID: %d / CID: %d)\n", name, sd->status.name, sd->status.account_id, sd->status.char_id);
return;
}
if (!bg->solo) {
clif_bg_queue_apply_result(BG_APPLY_INVALID_APP, name, sd);
return;
}
bg_queue_join_multi(name, sd, { sd }); // Join as solo
}
/**
* Join a party onto the same side of a Battleground
* @param name: Battleground name
* @param sd: Player who requested to join the battlegrounds
*/
void bg_queue_join_party(const char *name, map_session_data *sd)
{
if (!sd) {
ShowError("bg_queue_join_party: Tried to join non-existent player\n.");
return;
}
struct party_data *p = party_search(sd->status.party_id);
if (!p) {
clif_bg_queue_apply_result(BG_APPLY_INVALID_APP, name, sd);
return; // Someone has bypassed the client check for being in a party
}
for (const auto &it : p->party.member) {
if (it.leader && sd->status.char_id != it.char_id) {
clif_bg_queue_apply_result(BG_APPLY_PARTYGUILD_LEADER, name, sd);
return; // Not the party leader
}
}
std::shared_ptr<s_battleground_type> bg = bg_search_name(name);
if (bg) {
if (!bg->party) {
clif_bg_queue_apply_result(BG_APPLY_INVALID_APP, name, sd);
return;
}
int32 p_online = 0;
for (const auto &it : p->party.member) {
if (it.online)
p_online++;
}
if (p_online > bg->max_players) {
clif_bg_queue_apply_result(BG_APPLY_PLAYER_COUNT, name, sd);
return; // Too many party members online
}
std::vector<map_session_data *> list;
for (const auto &it : p->party.member) {
if (list.size() == bg->max_players)
break;
if (it.online) {
map_session_data *pl_sd = map_charid2sd(it.char_id);
if (pl_sd)
list.push_back(pl_sd);
}
}
bg_queue_join_multi(name, sd, list); // Join as party, all on the same side of the BG
} else {
ShowWarning("clif_parse_bg_queue_apply_request: Could not find Battleground: \"%s\" requested by player: %s (AID:%d CID:%d)\n", name, sd->status.name, sd->status.account_id, sd->status.char_id);
clif_bg_queue_apply_result(BG_APPLY_INVALID_NAME, name, sd);
return; // Invalid BG name
}
}
/**
* Join a guild onto the same side of a Battleground
* @param name: Battleground name
* @param sd: Player who requested to join the battlegrounds
*/
void bg_queue_join_guild(const char *name, map_session_data *sd)
{
if (!sd) {
ShowError("bg_queue_join_guild: Tried to join non-existent player\n.");
return;
}
if (!sd->guild) {
clif_bg_queue_apply_result(BG_APPLY_INVALID_APP, name, sd);
return; // Someone has bypassed the client check for being in a guild
}
if (strcmp(sd->status.name, sd->guild->guild.master) != 0) {
clif_bg_queue_apply_result(BG_APPLY_PARTYGUILD_LEADER, name, sd);
return; // Not the guild leader
}
std::shared_ptr<s_battleground_type> bg = bg_search_name(name);
if (bg) {
if (!bg->guild) {
clif_bg_queue_apply_result(BG_APPLY_INVALID_APP, name, sd);
return;
}
auto &g = sd->guild;
if (g->guild.connect_member > bg->max_players) {
clif_bg_queue_apply_result(BG_APPLY_PLAYER_COUNT, name, sd);
return; // Too many guild members online
}
std::vector<map_session_data *> list;
for (const auto &it : g->guild.member) {
if (list.size() == bg->max_players)
break;
if (it.online) {
map_session_data *pl_sd = map_charid2sd(it.char_id);
if (pl_sd)
list.push_back(pl_sd);
}
}
bg_queue_join_multi(name, sd, list); // Join as guild, all on the same side of the BG
} else {
ShowWarning("clif_parse_bg_queue_apply_request: Could not find Battleground: \"%s\" requested by player: %s (AID:%d CID:%d)\n", name, sd->status.name, sd->status.account_id, sd->status.char_id);
clif_bg_queue_apply_result(BG_APPLY_INVALID_NAME, name, sd);
return; // Invalid BG name
}
}
/**
* Join multiple players onto the same side of a Battleground
* @param name: Battleground name
* @param sd: Player who requested to join the battlegrounds
* @param list: Contains all players including the player who requested to join
*/
void bg_queue_join_multi(const char *name, map_session_data *sd, std::vector <map_session_data *> list)
{
if (!sd) {
ShowError("bg_queue_join_multi: Tried to join non-existent player\n.");
return;
}
std::shared_ptr<s_battleground_type> bg = bg_search_name(name);
if (!bg) {
ShowWarning("bq_queue_join_multi: Could not find battleground \"%s\" requested by %s (AID: %d / CID: %d)\n", name, sd->status.name, sd->status.account_id, sd->status.char_id);
return;
}
if (!bg_queue_check_joinable(bg, sd, name)){
return;
}
for (const auto &queue : bg_queues) {
if (queue->id != bg->id || queue->state == QUEUE_STATE_SETUP_DELAY || queue->state == QUEUE_STATE_ENDED)
continue;
// Make sure there's enough space on one side to join as a party/guild in this queue
if (queue->teama_members.size() + list.size() > bg->max_players && queue->teamb_members.size() + list.size() > bg->max_players) {
break;
}
bool r = rnd_chance(50, 100);
std::vector<map_session_data *> *team = r ? &queue->teamb_members : &queue->teama_members;
if (queue->state == QUEUE_STATE_ACTIVE) {
// If one team has lesser members try to balance (on an active BG)
if (r && queue->teama_members.size() < queue->teamb_members.size())
team = &queue->teama_members;
else if (!r && queue->teamb_members.size() < queue->teama_members.size())
team = &queue->teamb_members;
} else {
// If the designated team is full, put the player into the other team
if (team->size() + list.size() > bg->required_players)
team = r ? &queue->teama_members : &queue->teamb_members;
}
while (!list.empty() && team->size() < bg->max_players) {
map_session_data *sd2 = list.back();
list.pop_back();
if (!sd2 || sd2->bg_queue_id > 0)
continue;
if (!bg_queue_check_joinable(bg, sd2, name))
continue;
sd2->bg_queue_id = queue->queue_id;
team->push_back(sd2);
clif_bg_queue_apply_result(BG_APPLY_ACCEPT, name, sd2);
clif_bg_queue_apply_notify(name, sd2);
}
if (queue->state == QUEUE_STATE_ACTIVE) { // Battleground is already active
for (auto &pl_sd : *team) {
if (queue->map->mapindex == pl_sd->mapindex)
continue;
pc_set_bg_queue_timer(pl_sd);
clif_bg_queue_lobby_notify(name, pl_sd);
}
} else if (queue->state == QUEUE_STATE_SETUP && queue->teamb_members.size() >= bg->required_players && queue->teama_members.size() >= bg->required_players) // Enough players have joined
bg_queue_on_ready(name, queue);
return;
}
// Something went wrong, sends reconnect and then reapply message to client.
clif_bg_queue_apply_result(BG_APPLY_RECONNECT, name, sd);
}
/**
* Clear Battleground queue for next one
* @param queue: Queue to clean up
* @param ended: If a Battleground has ended through normal means (by script command bg_unbook)
*/
void bg_queue_clear(std::shared_ptr<s_battleground_queue> queue, bool ended)
{
if (queue == nullptr)
return;
if (queue->tid_requeue != INVALID_TIMER) {
delete_timer(queue->tid_requeue, bg_on_ready_loopback);
queue->tid_requeue = INVALID_TIMER;
}
if (queue->tid_expire != INVALID_TIMER) {
delete_timer(queue->tid_expire, bg_on_ready_expire);
queue->tid_expire = INVALID_TIMER;
}
if (queue->tid_start != INVALID_TIMER) {
delete_timer(queue->tid_start, bg_on_ready_start);
queue->tid_start = INVALID_TIMER;
}
if (ended) {
if (queue->map != nullptr) {
queue->map->isReserved = false; // Remove reservation to free up for future queue
queue->map = nullptr;
}
for (const auto &sd : queue->teama_members)
sd->bg_queue_id = 0;
for (const auto &sd : queue->teamb_members)
sd->bg_queue_id = 0;
queue->teama_members.clear();
queue->teamb_members.clear();
queue->teama_members.shrink_to_fit();
queue->teamb_members.shrink_to_fit();
queue->accepted_players = 0;
queue->state = QUEUE_STATE_SETUP;
}
}
/**
* Sub function for leaving a Battleground queue
* @param sd: Player leaving
* @param members: List of players in queue data
* @param apply_sc: Apply the SC_ENTRY_QUEUE_APPLY_DELAY status on queue leave (default: true)
* @return True on success or false otherwise
*/
static bool bg_queue_leave_sub(map_session_data *sd, std::vector<map_session_data *> &members, bool apply_sc)
{
if (!sd)
return false;
auto list_it = members.begin();
while (list_it != members.end()) {
if (*list_it == sd) {
members.erase(list_it);
if (apply_sc)
sc_start(nullptr, sd, SC_ENTRY_QUEUE_APPLY_DELAY, 100, 1, 60000);
sd->bg_queue_id = 0;
pc_delete_bg_queue_timer(sd);
return true;
} else {
list_it++;
}
}
return false;
}
/**
* Leave a Battleground queue
* @param sd: Player data
* @param apply_sc: Apply the SC_ENTRY_QUEUE_APPLY_DELAY status on queue leave (default: true)
* @return True on success or false otherwise
*/
bool bg_queue_leave(map_session_data *sd, bool apply_sc)
{
if (!sd || sd->bg_queue_id == 0)
return false;
pc_delete_bg_queue_timer(sd);
for (auto &queue : bg_queues) {
if (sd->bg_queue_id == queue->queue_id) {
if (!bg_queue_leave_sub(sd, queue->teama_members, apply_sc) && !bg_queue_leave_sub(sd, queue->teamb_members, apply_sc)) {
ShowError("bg_queue_leave: Couldn't find player %s in battlegrounds queue.\n", sd->status.name);
return false;
} else {
if ((queue->state == QUEUE_STATE_SETUP || queue->state == QUEUE_STATE_SETUP_DELAY) && queue->teama_members.empty() && queue->teamb_members.empty()) // If there are no players left in the queue (that hasn't started), discard it
bg_queue_clear(queue, true);
return true;
}
}
}
return false;
}
/**
* Send packets to all clients in queue to notify them that the battleground is ready to be joined
* @param name: Battleground name
* @param queue: Battleground queue
* @return True on success or false otherwise
*/
bool bg_queue_on_ready(const char *name, std::shared_ptr<s_battleground_queue> queue)
{
std::shared_ptr<s_battleground_type> bg = battleground_db.find(queue->id);
if (!bg) {
ShowError("bg_queue_on_ready: Couldn't find battleground ID %d in battlegrounds database.\n", queue->id);
return false;
}
if (queue->teama_members.size() < queue->required_players || queue->teamb_members.size() < queue->required_players)
return false; // Return players to the queue and stop reapplying the timer
bool map_reserved = false;
for (auto &map : bg->maps) {
if (!map.isReserved) {
map.isReserved = true;
map_reserved = true;
queue->map = ↦
break;
}
}
if (!map_reserved) { // All the battleground maps are reserved. Set a timer to check for an open battleground every 10 seconds.
queue->tid_requeue = add_timer(gettick() + 10000, bg_on_ready_loopback, 0, (intptr_t)queue->queue_id);
return false;
}
queue->state = QUEUE_STATE_SETUP_DELAY;
queue->tid_expire = add_timer(gettick() + 20000, bg_on_ready_expire, 0, (intptr_t)queue->queue_id);
for (const auto &sd : queue->teama_members)
clif_bg_queue_lobby_notify(name, sd);
for (const auto &sd : queue->teamb_members)
clif_bg_queue_lobby_notify(name, sd);
return true;
}
/**
* Send a player into an active Battleground
* @param sd: Player to send in
* @param queue: Queue data
*/
void bg_join_active(map_session_data *sd, std::shared_ptr<s_battleground_queue> queue)
{
if (sd == nullptr || queue == nullptr)
return;
// Check player's current position for mapflag check
if (battle_config.bgqueue_nowarp_mapflag > 0 && map_getmapflag(sd->m, MF_NOWARP)) {
clif_messagecolor(sd, color_table[COLOR_LIGHT_GREEN], msg_txt(sd, 337), false, SELF); // You can't apply to a battleground queue from this map.
bg_queue_leave(sd);
clif_bg_queue_entry_init(sd);
return;
}
pc_delete_bg_queue_timer(sd); // Cancel timer so player doesn't leave the queue.
int32 bg_id_team_1 = static_cast<int32>(mapreg_readreg(add_str(queue->map->team1.bg_id_var.c_str())));
std::shared_ptr<s_battleground_data> bgteam_1 = util::umap_find(bg_team_db, bg_id_team_1);
for (auto &pl_sd : queue->teama_members) {
if (sd != pl_sd)
continue;
if (bgteam_1 == nullptr) {
bg_queue_leave(sd);
clif_bg_queue_apply_result(BG_APPLY_RECONNECT, battleground_db.find(queue->id)->name.c_str(), sd);
clif_bg_queue_entry_init(sd);
return;
}
clif_bg_queue_entry_init(pl_sd);
bg_team_join(bg_id_team_1, pl_sd, true);
npc_event(pl_sd, bgteam_1->active_event.c_str(), 0);
return;
}
int32 bg_id_team_2 = static_cast<int32>(mapreg_readreg(add_str(queue->map->team2.bg_id_var.c_str())));
std::shared_ptr<s_battleground_data> bgteam_2 = util::umap_find(bg_team_db, bg_id_team_2);
for (auto &pl_sd : queue->teamb_members) {
if (sd != pl_sd)
continue;
if (bgteam_2 == nullptr) {
bg_queue_leave(sd);
clif_bg_queue_apply_result(BG_APPLY_RECONNECT, battleground_db.find(queue->id)->name.c_str(), sd);
clif_bg_queue_entry_init(sd);
return;
}
clif_bg_queue_entry_init(pl_sd);
bg_team_join(bg_id_team_2, pl_sd, true);
npc_event(pl_sd, bgteam_2->active_event.c_str(), 0);
return;
}
return;
}
/**
* Check to see if any players in the queue are on a map with MF_NOWARP and remove them from the queue
* @param queue: Queue data
* @return True if the player is on a map with MF_NOWARP or false otherwise
*/
bool bg_mapflag_check(std::shared_ptr<s_battleground_queue> queue) {
if (queue == nullptr || battle_config.bgqueue_nowarp_mapflag == 0)
return false;
bool found = false;
for (const auto &sd : queue->teama_members) {
if (map_getmapflag(sd->m, MF_NOWARP)) {
clif_messagecolor(sd, color_table[COLOR_LIGHT_GREEN], msg_txt(sd, 337), false, SELF); // You can't apply to a battleground queue from this map.
bg_queue_leave(sd);
clif_bg_queue_entry_init(sd);
found = true;
}
}
for (const auto &sd : queue->teamb_members) {
if (map_getmapflag(sd->m, MF_NOWARP)) {
clif_messagecolor(sd, color_table[COLOR_LIGHT_GREEN], msg_txt(sd, 337), false, SELF); // You can't apply to a battleground queue from this map.
bg_queue_leave(sd);
clif_bg_queue_entry_init(sd);
found = true;
}
}
if (found) {
queue->state = QUEUE_STATE_SETUP; // Set back to queueing state
queue->accepted_players = 0; // Reset acceptance count
// Free map to avoid creating a reservation delay
if (queue->map != nullptr) {
queue->map->isReserved = false;
queue->map = nullptr;
}
// Announce failure to remaining players
for (const auto &sd : queue->teama_members)
clif_messagecolor(sd, color_table[COLOR_LIGHT_GREEN], msg_txt(sd, 340), false, SELF); // Participants were unable to join. Delaying entry for more participants.
for (const auto &sd : queue->teamb_members)
clif_messagecolor(sd, color_table[COLOR_LIGHT_GREEN], msg_txt(sd, 340), false, SELF); // Participants were unable to join. Delaying entry for more participants.
}
return found;
}
/**
* Update the Battleground queue when the player accepts the invite
* @param queue: Battleground queue
* @param sd: Player data
*/
void bg_queue_on_accept_invite(map_session_data *sd)
{
nullpo_retv(sd);
std::shared_ptr<s_battleground_queue> queue = bg_search_queue(sd->bg_queue_id);
if (queue == nullptr) {
ShowError("bg_queue_on_accept_invite: Couldn't find player %s in battlegrounds queue.\n", sd->status.name);
return;
}
queue->accepted_players++;
clif_bg_queue_ack_lobby(true, mapindex_id2name(queue->map->mapindex), mapindex_id2name(queue->map->mapindex), sd);
if (queue->state == QUEUE_STATE_ACTIVE) // Battleground is already active
bg_join_active(sd, queue);
else if (queue->state == QUEUE_STATE_SETUP_DELAY) {
if (queue->accepted_players == queue->required_players * 2) {
if (queue->tid_expire != INVALID_TIMER) {
delete_timer(queue->tid_expire, bg_on_ready_expire);
queue->tid_expire = INVALID_TIMER;
}
// Check player's current position for mapflag check
if (battle_config.bgqueue_nowarp_mapflag > 0 && bg_mapflag_check(queue))
return;
queue->tid_start = add_timer(gettick() + battleground_db.find(queue->id)->start_delay * 1000, bg_on_ready_start, 0, (intptr_t)queue->queue_id);
}
}
}
/**
* Begin the Battleground from the given queue
* @param queue: Battleground queue
*/
void bg_queue_start_battleground(std::shared_ptr<s_battleground_queue> queue)
{
if (queue == nullptr)
return;
std::shared_ptr<s_battleground_type> bg = battleground_db.find(queue->id);
if (!bg) {
bg_queue_clear(queue, true);
ShowError("bg_queue_start_battleground: Could not find battleground ID %d in battlegrounds database.\n", queue->id);
return;
}
// Check player's current position for mapflag check
if (battle_config.bgqueue_nowarp_mapflag > 0 && bg_mapflag_check(queue))
return;
uint16 map_idx = queue->map->mapindex;
int32 bg_team_1 = bg_create(map_idx, &queue->map->team1);
int32 bg_team_2 = bg_create(map_idx, &queue->map->team2);
for (const auto &sd : queue->teama_members) {
clif_bg_queue_entry_init(sd);
bg_team_join(bg_team_1, sd, true);
}
for (const auto &sd : queue->teamb_members) {
clif_bg_queue_entry_init(sd);
bg_team_join(bg_team_2, sd, true);
}
mapreg_setreg(add_str(queue->map->team1.bg_id_var.c_str()), bg_team_1);
mapreg_setreg(add_str(queue->map->team2.bg_id_var.c_str()), bg_team_2);
npc_event_do(queue->map->bgcallscript.c_str());
queue->state = QUEUE_STATE_ACTIVE;
bg_queue_clear(queue, false);
}
/**
* Initialize a Battleground queue
* @param bg_id: Battleground ID
* @param req_players: Required amount of players
* @return s_battleground_queue*
*/
static void bg_queue_create(int32 bg_id, int32 req_players)
{
auto queue = std::make_shared<s_battleground_queue>();
queue->queue_id = bg_queue_count++;
queue->id = bg_id;
queue->required_players = req_players;
queue->accepted_players = 0;
queue->tid_expire = INVALID_TIMER;
queue->tid_start = INVALID_TIMER;
queue->tid_requeue = INVALID_TIMER;
queue->state = QUEUE_STATE_SETUP;
bg_queues.push_back(queue);
}
/**
* Initialize the Battleground data
*/
void do_init_battleground(void)
{
if (battle_config.feature_bgqueue) {
battleground_db.load();
for (const auto &bg : battleground_db)
bg_queue_create(bg.first, bg.second->required_players);
}
add_timer_func_list(bg_send_xy_timer, "bg_send_xy_timer");
add_timer_func_list(bg_on_ready_loopback, "bg_on_ready_loopback");
add_timer_func_list(bg_on_ready_expire, "bg_on_ready_expire");
add_timer_func_list(bg_on_ready_start, "bg_on_ready_start");
add_timer_interval(gettick() + battle_config.bg_update_interval, bg_send_xy_timer, 0, 0, battle_config.bg_update_interval);
}
/**
* Clear the Battleground data from memory
*/
void do_final_battleground(void)
{
}
| 412 | 0.974128 | 1 | 0.974128 | game-dev | MEDIA | 0.792195 | game-dev | 0.97473 | 1 | 0.97473 |
Deadrik/TFCraft | 2,948 | src/Common/com/bioxx/tfc/GUI/GuiChestTFC.java | package com.bioxx.tfc.GUI;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.InventoryLargeChest;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import org.lwjgl.opengl.GL11;
import com.bioxx.tfc.Reference;
import com.bioxx.tfc.Containers.ContainerChestTFC;
import com.bioxx.tfc.Core.TFC_Core;
import com.bioxx.tfc.Core.Player.PlayerInventory;
import com.bioxx.tfc.TileEntities.TEChest;
public class GuiChestTFC extends GuiContainer
{
private IInventory upperChestInventory;
private IInventory lowerChestInventory;
/**
* window height is calculated with this values, the more rows, the heigher
*/
private int inventoryRows;
public GuiChestTFC(IInventory par1IInventory, IInventory chestInv, World world, int x, int y, int z)
{
super(new ContainerChestTFC(par1IInventory, chestInv, world, x, y, z));
TEChest chest = (TEChest)chestInv;
this.upperChestInventory = par1IInventory;
this.lowerChestInventory = chestInv;
if (chest.adjacentChestXNeg != null)
{
lowerChestInventory = new InventoryLargeChest("Large chest", chest.adjacentChestXNeg, chestInv);
}
if (chest.adjacentChestXPos != null)
{
lowerChestInventory = new InventoryLargeChest("Large chest", chestInv, chest.adjacentChestXPos);
}
if (chest.adjacentChestZNeg != null)
{
lowerChestInventory = new InventoryLargeChest("Large chest", chest.adjacentChestZNeg, chestInv);
}
if (chest.adjacentChestZPos != null)
{
lowerChestInventory = new InventoryLargeChest("Large chest", chestInv, chest.adjacentChestZPos);
}
this.allowUserInput = false;
short var3 = 222;
int var4 = var3 - 108;
this.inventoryRows = lowerChestInventory.getSizeInventory() / 9;
this.ySize = var4 + this.inventoryRows * 18;
}
/**
* Draw the foreground layer for the GuiContainer (everythin in front of the items)
*/
protected void drawGuiContainerForegroundLayer()
{
this.fontRendererObj.drawString(TFC_Core.translate(this.lowerChestInventory.getInventoryName()), 8, 6, 4210752);
this.fontRendererObj.drawString(TFC_Core.translate(this.upperChestInventory.getInventoryName()), 8, this.ySize - 96 + 2, 4210752);
}
/**
* Draw the background layer for the GuiContainer (everything behind the items)
*/
@Override
protected void drawGuiContainerBackgroundLayer(float par1, int par2, int par3)
{
TFC_Core.bindTexture(new ResourceLocation(Reference.MOD_ID, Reference.ASSET_PATH_GUI + "gui_chest.png"));
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
int var5 = (this.width - this.xSize) / 2;
int var6 = (this.height - this.ySize) / 2;
this.drawTexturedModalRect(var5, var6, 0, 0, this.xSize, this.inventoryRows * 18 + 17);
this.drawTexturedModalRect(var5, var6 + this.inventoryRows * 18 + 17, 0, 126, this.xSize, 96);
PlayerInventory.drawInventory(this, width, height, ySize-PlayerInventory.invYSize + 10);
}
}
| 412 | 0.723036 | 1 | 0.723036 | game-dev | MEDIA | 0.818516 | game-dev | 0.854659 | 1 | 0.854659 |
DeanRoddey/CIDLib | 13,851 | Source/AllProjects/AIUtils/CIDAI/CIDAI_BehaviorTree.cpp | //
// FILE NAME: CIDAI_BehaviorTree.cpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 12/24/2017
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2019
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This file implements the actual tree class, which loads and coordiantes all of the
// stuff involved in invoking an behavior tree (and the sub-trees it references as
// well.)
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $_CIDLib_Log_$
//
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include "CIDAI_.hpp"
#include "CIDAI_BTParser_.hpp"
// ---------------------------------------------------------------------------
// Magic macros
// ---------------------------------------------------------------------------
RTTIDecls(TAIBehaviorTree, TObject)
// ---------------------------------------------------------------------------
// Local types and constants
// ---------------------------------------------------------------------------
namespace
{
namespace CIDAI_BehaviorTree
{
// -----------------------------------------------------------------------
// The format version of our overall binary representation of a tree
// -----------------------------------------------------------------------
const tCIDLib::TCard1 c1FmtVersion = 1;
// -----------------------------------------------------------------------
// The format version of the per-tree part of our binary representation
// -----------------------------------------------------------------------
const tCIDLib::TCard1 c1FmtSlotVersion = 1;
// -----------------------------------------------------------------------
// Some marker bytes we put into the header section of the binary file format
// -----------------------------------------------------------------------
const tCIDLib::TCard1 c1Marker1 = 0xC9;
const tCIDLib::TCard1 c1Marker2 = 0xD7;
}
}
// ---------------------------------------------------------------------------
// CLASS: TAIBehaviorTree
// PREFIX: btree
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TAIBehaviorTree: Constructors and Destructor
// ---------------------------------------------------------------------------
TAIBehaviorTree::TAIBehaviorTree(const TString& strName) :
m_bStop(kCIDLib::False)
, m_colCallStack(tCIDLib::EAdoptOpts::NoAdopt)
, m_colTrees
(
tCIDLib::EAdoptOpts::Adopt
, 109
, TStringKeyOps(kCIDLib::False)
, TAIBTRootNode::strRootNodeKey
)
, m_strName(strName)
{
}
TAIBehaviorTree::~TAIBehaviorTree()
{
}
// ---------------------------------------------------------------------------
// TAIBehaviorTree: Public, non-virtual methods
// ---------------------------------------------------------------------------
// Get/set our stop flag
tCIDLib::TBoolean TAIBehaviorTree::bStop() const
{
return m_bStop;
}
tCIDLib::TBoolean TAIBehaviorTree::bStop(const tCIDLib::TBoolean bToSet)
{
m_bStop = bToSet;
return m_bStop;
}
// Provide outside access to our context object in case it's needed
const TAIBTCtx& TAIBehaviorTree::ctxToUse() const
{
return m_ctxToUse;
}
TAIBTCtx& TAIBehaviorTree::ctxToUse()
{
return m_ctxToUse;
}
//
// This method will 'compile' all of the contents of this tree to a binary file. It's
// essentially the original XML files, but in a format that users cannot mess with it,
// and which will be vastly easier to distibute and load (one file) and more efficient.
//
// We have to put them out in order of dependence, so that when we load them, we can
// resolve link references just as when the XML files were loaded. So we search
// each tree to see what other trees are referenced. We process those first, in a
// recursive way, basically a depth first search. We keep a hash set of the names of
// the trees we've done so far, so we don't duplicate any.
//
tCIDLib::TVoid TAIBehaviorTree::CompileToFile(TBinOutStream& strmTar)
{
// Write out our starting bits
strmTar << tCIDLib::EStreamMarkers::StartObject
<< CIDAI_BehaviorTree::c1Marker1
<< CIDAI_BehaviorTree::c1Marker2
<< CIDAI_BehaviorTree::c1FmtVersion
<< m_colTrees.c4ElemCount()
<< tCIDLib::TCard4(m_colTrees.c4ElemCount() ^ kCIDLib::c4MaxCard);
// Set up a cursor over our tree list
tCIDAI::TTreeList::TCursor cursTrees(&m_colTrees);
if (cursTrees.bReset())
{
// We need a string hash set to keep up with the trees we've done so far
tCIDLib::TStrHashSet colTreesDone(109, TStringKeyOps(kCIDLib::False));
//
// Let's now start the process. At this level, we just loop through the trees.
// For each one, we call a recursive helper that processes each one and outputs
// any so far unprocessed trees.
//
for (; cursTrees; ++cursTrees)
{
const TAIBTRootNode& btnodeCur = *cursTrees;
// If this guy is not in the trees done list, call the recursive helper
if (!colTreesDone.bHasElement(btnodeCur.strName()))
CompilerHelper(btnodeCur, colTreesDone, strmTar);
}
}
// Close it off now
strmTar << tCIDLib::EStreamMarkers::EndObject;
}
//
// This is how we start the tree running on a specific tree in our list. The caller
// can pass in initial variables and tree data to be put into the context for this
// run.
//
tCIDAI::ENodeStates
TAIBehaviorTree::eRun(const TString& strTreeName, const tCIDLib::TKValsList& colInitVars)
{
// Reset the context, setting any incoming initial variables
m_ctxToUse.Reset(colInitVars);
// Look for this tree, throwing if not found
TAIBTRootNode* pbtnodeRun = pbtnodeFindTree(strTreeName, kCIDLib::True);
// Clear the stop flag for this round
m_bStop = kCIDLib::False;
// And let's run it and return the result
return pbtnodeRun->eRun(*this);
}
tCIDAI::ENodeStates
TAIBehaviorTree::eRun( const TString& strTreeName
, const tCIDLib::TKValsList& colInitVars
, const tCIDLib::TKNumList& colKNumList)
{
// Reset the context, setting any incoming initial variables and tree content
m_ctxToUse.Reset(colInitVars, colKNumList);
// Look for this tree, throwing if not found
TAIBTRootNode* pbtnodeRun = pbtnodeFindTree(strTreeName, kCIDLib::True);
// And let's run it and return the result
return pbtnodeRun->eRun(*this);
}
//
// We can load a tree from a file, or from a file preloaded into memory. Our file
// based method just preloads the file and calls the other.
//
tCIDLib::TVoid
TAIBehaviorTree::LoadXMLTree(const TMemBuf& mbufData, const tCIDLib::TCard4 c4Bytes)
{
try
{
// Create a parser and ask him to parse the passed file for us
TCIDAIBTParser aibtpLoad;
TAIBTRootNode* pbtnodeNew = aibtpLoad.pbtnodeParse(mbufData, c4Bytes);
// It worked, so make sure the name is unique
if (m_colTrees.bKeyExists(pbtnodeNew->strName()))
{
// Save the name before we trash the node
const TString strSaveName = pbtnodeNew->strName();
try
{
delete pbtnodeNew;
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
facCIDAI().ThrowErr
(
CID_FILE
, CID_LINE
, kAIErrs::errcBTParse_DupTreeName
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Duplicate
, strSaveName
);
}
// Looks ok, so save it
m_colTrees.Add(pbtnodeNew);
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
throw;
}}
tCIDLib::TVoid TAIBehaviorTree::LoadXMLTree(const TString& strToParse)
{
// Try to open the file and read it in
tCIDLib::TCard4 c4Bytes = 0;
THeapBuf mbufFile;
try
{
TBinaryFile bflSrc(strToParse);
bflSrc.Open
(
tCIDLib::EAccessModes::Read
, tCIDLib::ECreateActs::OpenIfExists
, tCIDLib::EFilePerms::Default
, tCIDLib::EFileFlags::None
);
c4Bytes = tCIDLib::TCard4(bflSrc.c8CurSize());
bflSrc.c4ReadBuffer(mbufFile, c4Bytes, tCIDLib::EAllData::FailIfNotAll);
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
throw;
}
// And we can pass it to the other version
LoadXMLTree(mbufFile, c4Bytes);
}
// Get the current top node, or null if none has been run yet
const TAIBTNode* TAIBehaviorTree::pbtnodeCur() const
{
if (m_colCallStack.bIsEmpty())
return nullptr;
return m_colCallStack.pobjPeek();
}
// Look up a tree by its name. We can return null or throw if not found
TAIBTRootNode*
TAIBehaviorTree::pbtnodeFindTree(const TString& strTreeName
, const tCIDLib::TBoolean bThrowIfNot)
{
TAIBTRootNode* pbtnodeRet = m_colTrees.pobjFindByKey(strTreeName, kCIDLib::False);
if (!pbtnodeRet)
{
if (bThrowIfNot)
{
facCIDAI().ThrowErr
(
CID_FILE
, CID_LINE
, kAIErrs::errcBT_TreeNotFound
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::NotFound
, strTreeName
);
}
return nullptr;
}
return pbtnodeRet;
}
// Pop the top node from the call stack
tCIDLib::TVoid TAIBehaviorTree::PopNode()
{
m_colCallStack.TrashTop();
}
// Push a new node onto the call stack
tCIDLib::TVoid TAIBehaviorTree::PushNode(TAIBTNode* const pbtnodePush)
{
m_colCallStack.Push(pbtnodePush);
}
// Reset this tree back to inital state
tCIDLib::TVoid TAIBehaviorTree::Reset()
{
m_colCallStack.RemoveAll();
m_colTrees.RemoveAll();
m_ctxToUse.Reset();
}
// Get the name that was set on this top level tree
const TString& TAIBehaviorTree::strName() const
{
return m_strName;
}
//
// Update the application info. This is useful for nested operations. We don't clear
// the call stack or variables.
//
tCIDLib::TVoid
TAIBehaviorTree::SetAppInfo(const tCIDLib::TKNumList& colKNumList)
{
m_ctxToUse.SetAppInfo(colKNumList);
}
// ---------------------------------------------------------------------------
// TAIBehaviorTree: Private, non-virtual methods
// ---------------------------------------------------------------------------
//
// This is a recursive helper. We scan the incoing tree for other trees that it
// references, i.e. look for link nodes. For each one, we see if it is in the list
// of already done trees. If not, we recurse on it.
//
// For each one that we have not done, and which does not reference any other
// tree, we write out its information and return.
//
tCIDLib::TVoid
TAIBehaviorTree::CompilerHelper(const TAIBTRootNode& btnodeTree
, tCIDLib::TStrHashSet& colTreesDone
, TBinOutStream& strmTar)
{
// Let's scan this guy for link nodes
const tCIDLib::TCard4 c4ChildCnt = btnodeTree.c4ChildCount();
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4ChildCnt; c4Index++)
{
const TAIBTNode* pbtnodeCur = btnodeTree.pbtnodeChildAt(c4Index);
if (pbtnodeCur->strType() == kCIDAI::strDefFact_Link)
{
// Get the link target parameter
const TString& strTar = pbtnodeCur->strFindParam(kCIDAI::strNParam_LinkTarget);
// See if this guy is in the done list. If not, recurse
if (!colTreesDone.bHasElement(strTar))
{
const TAIBTRootNode* pbtnodeRef = pbtnodeFindTree(strTar, kCIDLib::True);
CompilerHelper(*pbtnodeRef, colTreesDone, strmTar);
}
}
}
// Our the incoming tree to the list of done trees
colTreesDone.objAdd(btnodeTree.strName());
// And let's do our guy now, first the overall tree info
strmTar << tCIDLib::EStreamMarkers::Frame
<< CIDAI_BehaviorTree::c1FmtSlotVersion
<< btnodeTree.strName()
<< btnodeTree.c4ChildCount()
<< tCIDLib::TCard4(btnodeTree.c4ChildCount() ^ kCIDLib::c4MaxCard);
// Now write out the children
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4ChildCnt; c4Index++)
{
const TAIBTNode* pbtnodeCur = btnodeTree.pbtnodeChildAt(c4Index);
// Do the basic node info
const tCIDLib::TKVPList& colParams = pbtnodeCur->colParams();
const tCIDLib::TCard4 c4PCnt = colParams.c4ElemCount();
strmTar << tCIDLib::EStreamMarkers::Frame
<< pbtnodeCur->strName()
<< pbtnodeCur->strType()
<< pbtnodeCur->strPath()
<< c4PCnt;
// If any parameters do those
for (tCIDLib::TCard4 c4PInd = 0; c4PInd < c4PCnt; c4PInd++)
{
strmTar << colParams[c4PInd]
<< tCIDLib::EStreamMarkers::Frame;
}
}
// Cap off this tree
strmTar << tCIDLib::EStreamMarkers::Frame;
}
| 412 | 0.969502 | 1 | 0.969502 | game-dev | MEDIA | 0.35584 | game-dev | 0.956264 | 1 | 0.956264 |
KiltMC/Kilt | 3,005 | compat/forge-compats/src/main/java/xyz/bluspring/kilt/compat/forge/mixin/immersiveengineering/ChunkBuilderMeshingTaskMixin.java | package xyz.bluspring.kilt.compat.forge.mixin.immersiveengineering;
import blusunrize.immersiveengineering.client.render.ConnectionRenderer;
import com.llamalad7.mixinextras.sugar.Local;
import com.moulberry.mixinconstraints.annotations.IfModLoaded;
import me.jellysquid.mods.sodium.client.model.quad.properties.ModelQuadFacing;
import me.jellysquid.mods.sodium.client.render.SodiumWorldRenderer;
import me.jellysquid.mods.sodium.client.render.chunk.RenderSection;
import me.jellysquid.mods.sodium.client.render.chunk.compile.ChunkBuildBuffers;
import me.jellysquid.mods.sodium.client.render.chunk.compile.ChunkBuildContext;
import me.jellysquid.mods.sodium.client.render.chunk.compile.ChunkBuildOutput;
import me.jellysquid.mods.sodium.client.render.chunk.compile.tasks.ChunkBuilderMeshingTask;
import me.jellysquid.mods.sodium.client.render.chunk.terrain.material.DefaultMaterials;
import me.jellysquid.mods.sodium.client.util.task.CancellationToken;
import net.minecraft.core.BlockPos;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Pseudo;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import xyz.bluspring.kilt.compat.forge.immersiveengineering.SodiumIEVertexConsumer;
@IfModLoaded(value = "sodium", maxVersion = "0.6.0")
@Pseudo
@Mixin(ChunkBuilderMeshingTask.class)
public abstract class ChunkBuilderMeshingTaskMixin {
@Shadow @Final private RenderSection render;
@Inject(method = "execute(Lme/jellysquid/mods/sodium/client/render/chunk/compile/ChunkBuildContext;Lme/jellysquid/mods/sodium/client/util/task/CancellationToken;)Lme/jellysquid/mods/sodium/client/render/chunk/compile/ChunkBuildOutput;", at = @At(value = "FIELD", target = "Lme/jellysquid/mods/sodium/client/render/chunk/terrain/DefaultTerrainRenderPasses;ALL:[Lme/jellysquid/mods/sodium/client/render/chunk/terrain/TerrainRenderPass;", shift = At.Shift.AFTER, remap = false), remap = false)
private void kilt$tryBuildImmersiveConnections(ChunkBuildContext buildContext, CancellationToken cancellationToken, CallbackInfoReturnable<ChunkBuildOutput> cir, @Local(ordinal = 0) BlockPos.MutableBlockPos blockPos) {
ChunkBuildBuffers buffers = buildContext.buffers;
blockPos.set(this.render.getOriginX(), this.render.getOriginY(), this.render.getOriginZ());
// Kilt: Create an Immersive Engineering handler for Sodium compatibility within Kilt
ConnectionRenderer.renderConnectionsInSection(renderType -> {
var material = DefaultMaterials.forRenderLayer(renderType);
var builder = buffers.get(material).getVertexBuffer(ModelQuadFacing.UNASSIGNED);
return SodiumIEVertexConsumer.grab(builder, material);
}, ((SodiumWorldRendererAccessor) SodiumWorldRenderer.instance()).getWorld(), blockPos);
}
}
| 412 | 0.810356 | 1 | 0.810356 | game-dev | MEDIA | 0.884706 | game-dev,graphics-rendering | 0.69405 | 1 | 0.69405 |
MilosMosovsky/terminator | 3,674 | lib/terminator/role.ex | defmodule Terminator.Role do
@moduledoc ~S"""
Role is grouped representation of multiple abilities.
It allows you to assign or manage multiple roles at once.
"""
use Ecto.Schema
import Ecto.Changeset
alias __MODULE__
@typedoc "A role struct"
@type t :: %Role{}
schema "terminator_roles" do
field(:identifier, :string)
field(:name, :string)
field(:abilities, {:array, :string}, default: [])
many_to_many(:performers, Terminator.Performer, join_through: Terminator.PerformersRoles)
timestamps()
end
@spec changeset(struct :: Role.t(), params :: map() | nil) :: Ecto.Changeset.t()
def changeset(%Role{} = struct, params \\ %{}) do
struct
|> cast(params, [:identifier, :name, :abilities])
|> validate_required([:identifier, :name])
|> unique_constraint(:identifier, message: "Role already exists")
end
@doc """
Builds ecto changeset for a role.
## Examples
iex> changeset = Terminator.Role.build("admin", ["delete_account"], "Administrator of application")
#Ecto.Changeset<
action: nil,
changes: %{
abilities: ["delete_account"],
identifier: "admin",
name: "Administrator of application"
},
errors: [],
data: #Terminator.Role<>,
valid?: true
>
iex> changeset |> Repo.insert
{:ok,
%Terminator.Role{
__meta__: #Ecto.Schema.Metadata<:loaded, "terminator_roles">,
abilities: ["delete_account"],
id: 1,
identifier: "admin",
inserted_at: ~N[2019-01-03 19:50:13],
name: "Administrator of application",
updated_at: ~N[2019-01-03 19:50:13]
}}
"""
@spec build(identifier :: String.t(), abilities :: list(String.t()), name :: String.t()) ::
Ecto.Changeset.t()
def build(identifier, abilities, name) do
changeset(%Role{}, %{
identifier: identifier,
abilities: abilities,
name: name
})
end
@doc """
Grant `Terminator.Ability` to a role.
## Examples
Function accepts `Terminator.Ability` grant.
Function is merging existing grants with the new ones, so calling grant with same
grants will not duplicate entries in table.
To grant particular ability to a role
iex> Terminator.Performer.grant(%Terminator.Role{id: 1}, %Terminator.Ability{identifier: "manage"})
"""
@spec grant(Role.t(), Terminator.Ability.t()) :: Role.t()
def grant(%Role{id: _id} = role, %Terminator.Ability{identifier: _identifier} = ability) do
# Preload performer abilityies
abilities = Enum.uniq(role.abilities ++ [ability.identifier])
changeset =
changeset(role)
|> put_change(:abilities, abilities)
changeset |> Terminator.Repo.update!()
end
def grant(_, _), do: raise(ArgumentError, message: "Bad arguments for giving grant")
@doc """
Revoke `Terminator.Ability` from a role.
## Examples
Function accepts `Terminator.Ability` grant.
Function is directly opposite of `Terminator.Role.grant/2`
To revoke particular ability from a given role
iex> Terminator.Performer.revoke(%Terminator.Role{id: 1}, %Terminator.Ability{identifier: "manage"})
"""
@spec revoke(Role.t(), Terminator.Ability.t()) :: Role.t()
def revoke(%Role{id: _id} = role, %Terminator.Ability{identifier: _identifier} = ability) do
abilities =
Enum.filter(role.abilities, fn grant ->
grant != ability.identifier
end)
changeset =
changeset(role)
|> put_change(:abilities, abilities)
changeset |> Terminator.Repo.update!()
end
def revoke(_, _), do: raise(ArgumentError, message: "Bad arguments for revoking grant")
end
| 412 | 0.842592 | 1 | 0.842592 | game-dev | MEDIA | 0.301928 | game-dev | 0.865501 | 1 | 0.865501 |
nHapiNET/nHapi | 4,425 | src/NHapi.Model.V23/Group/RDR_RDR_ORDER.cs | using NHapi.Base.Parser;
using NHapi.Base;
using NHapi.Base.Log;
using System;
using System.Collections.Generic;
using NHapi.Model.V23.Segment;
using NHapi.Model.V23.Datatype;
using NHapi.Base.Model;
namespace NHapi.Model.V23.Group
{
///<summary>
///Represents the RDR_RDR_ORDER Group. A Group is an ordered collection of message
/// segments that can repeat together or be optionally in/excluded together.
/// This Group contains the following elements:
///<ol>
///<li>0: ORC (Common order segment) </li>
///<li>1: RDR_RDR_ENCODING (a Group object) optional </li>
///<li>2: RDR_RDR_DISPENSE (a Group object) repeating</li>
///</ol>
///</summary>
[Serializable]
public class RDR_RDR_ORDER : AbstractGroup {
///<summary>
/// Creates a new RDR_RDR_ORDER Group.
///</summary>
public RDR_RDR_ORDER(IGroup parent, IModelClassFactory factory) : base(parent, factory){
try {
this.add(typeof(ORC), true, false);
this.add(typeof(RDR_RDR_ENCODING), false, false);
this.add(typeof(RDR_RDR_DISPENSE), true, true);
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating RDR_RDR_ORDER - this is probably a bug in the source code generator.", e);
}
}
///<summary>
/// Returns ORC (Common order segment) - creates it if necessary
///</summary>
public ORC ORC {
get{
ORC ret = null;
try {
ret = (ORC)this.GetStructure("ORC");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
}
///<summary>
/// Returns RDR_RDR_ENCODING (a Group object) - creates it if necessary
///</summary>
public RDR_RDR_ENCODING ENCODING {
get{
RDR_RDR_ENCODING ret = null;
try {
ret = (RDR_RDR_ENCODING)this.GetStructure("ENCODING");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
}
///<summary>
/// Returns first repetition of RDR_RDR_DISPENSE (a Group object) - creates it if necessary
///</summary>
public RDR_RDR_DISPENSE GetDISPENSE() {
RDR_RDR_DISPENSE ret = null;
try {
ret = (RDR_RDR_DISPENSE)this.GetStructure("DISPENSE");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
///<summary>
///Returns a specific repetition of RDR_RDR_DISPENSE
/// * (a Group object) - creates it if necessary
/// throws HL7Exception if the repetition requested is more than one
/// greater than the number of existing repetitions.
///</summary>
public RDR_RDR_DISPENSE GetDISPENSE(int rep) {
return (RDR_RDR_DISPENSE)this.GetStructure("DISPENSE", rep);
}
/**
* Returns the number of existing repetitions of RDR_RDR_DISPENSE
*/
public int DISPENSERepetitionsUsed {
get{
int reps = -1;
try {
reps = this.GetAll("DISPENSE").Length;
} catch (HL7Exception e) {
string message = "Unexpected error accessing data - this is probably a bug in the source code generator.";
HapiLogFactory.GetHapiLog(GetType()).Error(message, e);
throw new System.Exception(message);
}
return reps;
}
}
/**
* Enumerate over the RDR_RDR_DISPENSE results
*/
public IEnumerable<RDR_RDR_DISPENSE> DISPENSEs
{
get
{
for (int rep = 0; rep < DISPENSERepetitionsUsed; rep++)
{
yield return (RDR_RDR_DISPENSE)this.GetStructure("DISPENSE", rep);
}
}
}
///<summary>
///Adds a new RDR_RDR_DISPENSE
///</summary>
public RDR_RDR_DISPENSE AddDISPENSE()
{
return this.AddStructure("DISPENSE") as RDR_RDR_DISPENSE;
}
///<summary>
///Removes the given RDR_RDR_DISPENSE
///</summary>
public void RemoveDISPENSE(RDR_RDR_DISPENSE toRemove)
{
this.RemoveStructure("DISPENSE", toRemove);
}
///<summary>
///Removes the RDR_RDR_DISPENSE at the given index
///</summary>
public void RemoveDISPENSEAt(int index)
{
this.RemoveRepetition("DISPENSE", index);
}
}
}
| 412 | 0.942804 | 1 | 0.942804 | game-dev | MEDIA | 0.564786 | game-dev | 0.712902 | 1 | 0.712902 |
Space-Stories/space-station-14 | 3,802 | Content.IntegrationTests/Tests/GravityGridTest.cs | using Content.Server.Gravity;
using Content.Server.Power.Components;
using Content.Shared.Gravity;
using Robust.Shared.GameObjects;
using Robust.Shared.Map;
using Robust.Shared.Map.Components;
using Robust.Shared.Maths;
namespace Content.IntegrationTests.Tests
{
/// Tests the behavior of GravityGeneratorComponent,
/// making sure that gravity is applied to the correct grids.
[TestFixture]
[TestOf(typeof(GravityGeneratorComponent))]
public sealed class GravityGridTest
{
[TestPrototypes]
private const string Prototypes = @"
- type: entity
name: GridGravityGeneratorDummy
id: GridGravityGeneratorDummy
components:
- type: GravityGenerator
- type: PowerCharge
windowTitle: gravity-generator-window-title
idlePower: 50
chargeRate: 1000000000 # Set this really high so it discharges in a single tick.
activePower: 500
- type: ApcPowerReceiver
- type: UserInterface
";
[Test]
public async Task Test()
{
await using var pair = await PoolManager.GetServerClient();
var server = pair.Server;
var testMap = await pair.CreateTestMap();
var entityMan = server.EntMan;
var mapMan = server.MapMan;
var mapSys = entityMan.System<SharedMapSystem>();
EntityUid generator = default;
Entity<MapGridComponent> grid1 = default;
Entity<MapGridComponent> grid2 = default;
// Create grids
await server.WaitAssertion(() =>
{
var mapId = testMap.MapId;
grid1 = mapMan.CreateGridEntity(mapId);
grid2 = mapMan.CreateGridEntity(mapId);
mapSys.SetTile(grid1, grid1, Vector2i.Zero, new Tile(1));
mapSys.SetTile(grid2, grid2, Vector2i.Zero, new Tile(1));
generator = entityMan.SpawnEntity("GridGravityGeneratorDummy", new EntityCoordinates(grid1, 0.5f, 0.5f));
Assert.Multiple(() =>
{
Assert.That(entityMan.HasComponent<GravityGeneratorComponent>(generator));
Assert.That(entityMan.HasComponent<ApcPowerReceiverComponent>(generator));
});
var powerComponent = entityMan.GetComponent<ApcPowerReceiverComponent>(generator);
powerComponent.NeedsPower = false;
});
await server.WaitRunTicks(5);
await server.WaitAssertion(() =>
{
var generatorComponent = entityMan.GetComponent<GravityGeneratorComponent>(generator);
var powerComponent = entityMan.GetComponent<ApcPowerReceiverComponent>(generator);
Assert.Multiple(() =>
{
Assert.That(generatorComponent.GravityActive, Is.True);
Assert.That(!entityMan.GetComponent<GravityComponent>(grid1).EnabledVV);
Assert.That(entityMan.GetComponent<GravityComponent>(grid2).EnabledVV);
});
// Re-enable needs power so it turns off again.
// Charge rate is ridiculously high so it finishes in one tick.
powerComponent.NeedsPower = true;
});
await server.WaitRunTicks(5);
await server.WaitAssertion(() =>
{
var generatorComponent = entityMan.GetComponent<GravityGeneratorComponent>(generator);
Assert.Multiple(() =>
{
Assert.That(generatorComponent.GravityActive, Is.False);
Assert.That(entityMan.GetComponent<GravityComponent>(grid2).EnabledVV, Is.False);
});
});
await pair.CleanReturnAsync();
}
}
}
| 412 | 0.631369 | 1 | 0.631369 | game-dev | MEDIA | 0.874893 | game-dev | 0.80869 | 1 | 0.80869 |
abdelkader/vCardEditor | 1,631 | vCardEditor/Model/PropertyComparer.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
namespace vCardEditor.Model
{
public class PropertyComparer<T> : IComparer<T>
{
private readonly IComparer comparer;
private PropertyDescriptor propertyDescriptor;
private int reverse;
public PropertyComparer(PropertyDescriptor property, ListSortDirection direction)
{
this.propertyDescriptor = property;
Type comparerForPropertyType = typeof(Comparer<>).MakeGenericType(property.PropertyType);
this.comparer = (IComparer)comparerForPropertyType.InvokeMember("Default", BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.Public, null, null, null);
this.SetListSortDirection(direction);
}
#region IComparer<T> Members
public int Compare(T x, T y)
{
return this.reverse * this.comparer.Compare(this.propertyDescriptor.GetValue(x), this.propertyDescriptor.GetValue(y));
}
#endregion
private void SetPropertyDescriptor(PropertyDescriptor descriptor)
{
this.propertyDescriptor = descriptor;
}
private void SetListSortDirection(ListSortDirection direction)
{
this.reverse = direction == ListSortDirection.Ascending ? 1 : -1;
}
public void SetPropertyAndDirection(PropertyDescriptor descriptor, ListSortDirection direction)
{
this.SetPropertyDescriptor(descriptor);
this.SetListSortDirection(direction);
}
}
}
| 412 | 0.933279 | 1 | 0.933279 | game-dev | MEDIA | 0.267075 | game-dev | 0.93615 | 1 | 0.93615 |
manisha-v/Unity3D | 6,084 | Part2 - 3D Object Intraction/Codes/Library/PackageCache/com.unity.ide.vscode@1.2.4/Editor/ProjectGeneration/AssemblyNameProvider.cs | using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEditor.Compilation;
using UnityEditor.PackageManager;
namespace VSCodeEditor
{
public interface IAssemblyNameProvider
{
string[] ProjectSupportedExtensions { get; }
ProjectGenerationFlag ProjectGenerationFlag { get; }
string GetAssemblyNameFromScriptPath(string path);
IEnumerable<Assembly> GetAssemblies(Func<string, bool> shouldFileBePartOfSolution);
IEnumerable<string> GetAllAssetPaths();
IEnumerable<string> GetRoslynAnalyzerPaths();
UnityEditor.PackageManager.PackageInfo FindForAssetPath(string assetPath);
ResponseFileData ParseResponseFile(string responseFilePath, string projectDirectory, string[] systemReferenceDirectories);
bool IsInternalizedPackagePath(string path);
void ToggleProjectGeneration(ProjectGenerationFlag preference);
}
internal interface IPackageInfoCache{
void ResetPackageInfoCache();
}
internal class AssemblyNameProvider : IAssemblyNameProvider, IPackageInfoCache
{
private readonly Dictionary<string, UnityEditor.PackageManager.PackageInfo> m_PackageInfoCache = new Dictionary<string, UnityEditor.PackageManager.PackageInfo>();
ProjectGenerationFlag m_ProjectGenerationFlag = (ProjectGenerationFlag)EditorPrefs.GetInt("unity_project_generation_flag", 0);
public string[] ProjectSupportedExtensions => EditorSettings.projectGenerationUserExtensions;
public ProjectGenerationFlag ProjectGenerationFlag
{
get => m_ProjectGenerationFlag;
private set
{
EditorPrefs.SetInt("unity_project_generation_flag", (int)value);
m_ProjectGenerationFlag = value;
}
}
public string GetAssemblyNameFromScriptPath(string path)
{
return CompilationPipeline.GetAssemblyNameFromScriptPath(path);
}
public IEnumerable<Assembly> GetAssemblies(Func<string, bool> shouldFileBePartOfSolution)
{
return CompilationPipeline.GetAssemblies()
.Where(i => 0 < i.sourceFiles.Length && i.sourceFiles.Any(shouldFileBePartOfSolution));
}
public IEnumerable<string> GetAllAssetPaths()
{
return AssetDatabase.GetAllAssetPaths();
}
private static string ResolvePotentialParentPackageAssetPath(string assetPath)
{
const string packagesPrefix = "packages/";
if (!assetPath.StartsWith(packagesPrefix, StringComparison.OrdinalIgnoreCase))
{
return null;
}
var followupSeparator = assetPath.IndexOf('/', packagesPrefix.Length);
if (followupSeparator == -1)
{
return assetPath.ToLowerInvariant();
}
return assetPath.Substring(0, followupSeparator).ToLowerInvariant();
}
public void ResetPackageInfoCache()
{
m_PackageInfoCache.Clear();
}
public UnityEditor.PackageManager.PackageInfo FindForAssetPath(string assetPath)
{
var parentPackageAssetPath = ResolvePotentialParentPackageAssetPath(assetPath);
if (parentPackageAssetPath == null)
{
return null;
}
if (m_PackageInfoCache.TryGetValue(parentPackageAssetPath, out var cachedPackageInfo))
{
return cachedPackageInfo;
}
var result = UnityEditor.PackageManager.PackageInfo.FindForAssetPath(parentPackageAssetPath);
m_PackageInfoCache[parentPackageAssetPath] = result;
return result;
}
public ResponseFileData ParseResponseFile(string responseFilePath, string projectDirectory, string[] systemReferenceDirectories)
{
return CompilationPipeline.ParseResponseFile(
responseFilePath,
projectDirectory,
systemReferenceDirectories
);
}
public bool IsInternalizedPackagePath(string path)
{
if (string.IsNullOrWhiteSpace(path))
{
return false;
}
var packageInfo = FindForAssetPath(path);
if (packageInfo == null)
{
return false;
}
var packageSource = packageInfo.source;
switch (packageSource)
{
case PackageSource.Embedded:
return !ProjectGenerationFlag.HasFlag(ProjectGenerationFlag.Embedded);
case PackageSource.Registry:
return !ProjectGenerationFlag.HasFlag(ProjectGenerationFlag.Registry);
case PackageSource.BuiltIn:
return !ProjectGenerationFlag.HasFlag(ProjectGenerationFlag.BuiltIn);
case PackageSource.Unknown:
return !ProjectGenerationFlag.HasFlag(ProjectGenerationFlag.Unknown);
case PackageSource.Local:
return !ProjectGenerationFlag.HasFlag(ProjectGenerationFlag.Local);
case PackageSource.Git:
return !ProjectGenerationFlag.HasFlag(ProjectGenerationFlag.Git);
#if UNITY_2019_3_OR_NEWER
case PackageSource.LocalTarball:
return !ProjectGenerationFlag.HasFlag(ProjectGenerationFlag.LocalTarBall);
#endif
}
return false;
}
public void ToggleProjectGeneration(ProjectGenerationFlag preference)
{
if (ProjectGenerationFlag.HasFlag(preference))
{
ProjectGenerationFlag ^= preference;
}
else
{
ProjectGenerationFlag |= preference;
}
}
public IEnumerable<string> GetRoslynAnalyzerPaths()
{
return PluginImporter.GetAllImporters()
.Where(i => !i.isNativePlugin && AssetDatabase.GetLabels(i).SingleOrDefault(l => l == "RoslynAnalyzer") != null)
.Select(i => i.assetPath);
}
}
}
| 412 | 0.912195 | 1 | 0.912195 | game-dev | MEDIA | 0.572536 | game-dev | 0.873658 | 1 | 0.873658 |
TabooLib/taboolib | 3,468 | module/bukkit-nms/src/main/kotlin/taboolib/module/nms/PacketSender.kt | package taboolib.module.nms
import org.bukkit.entity.Player
import org.bukkit.event.player.PlayerJoinEvent
import org.bukkit.event.player.PlayerQuitEvent
import org.tabooproject.reflex.ClassMethod
import org.tabooproject.reflex.Reflex.Companion.getProperty
import org.tabooproject.reflex.ReflexClass
import taboolib.common.Inject
import taboolib.common.platform.Platform
import taboolib.common.platform.PlatformSide
import taboolib.common.platform.event.SubscribeEvent
import taboolib.common.platform.function.submit
import taboolib.common.reflect.ClassHelper
import java.lang.reflect.Constructor
import java.util.concurrent.ConcurrentHashMap
/**
* TabooLib
* taboolib.module.nms.PacketSender
*
* @author 坏黑
* @since 2022/7/19 16:02
*/
@Inject
@PlatformSide(Platform.BUKKIT)
object PacketSender {
private val playerConnectionMap = ConcurrentHashMap<String, Any>()
private var sendPacketMethod: ClassMethod? = null
private var newPacketBundlePacket: Constructor<*>? = null
private var useMinecraftMethod = false
init {
try {
val bundlePacketClass = ClassHelper.getClass("net.minecraft.network.protocol.game.ClientboundBundlePacket")
newPacketBundlePacket = bundlePacketClass.getDeclaredConstructor(Iterable::class.java)
newPacketBundlePacket?.isAccessible = true
} catch (ignored: Exception) {
}
}
/**
* 使用 Minecraft 方法发送数据包
*/
@Deprecated("没啥用了")
fun useMinecraftMethod() {
useMinecraftMethod = true
}
/**
* 创建混合包(我也不知道这东西应该翻译成什么)
*/
fun createBundlePacket(packets: List<Any>): Any? {
return newPacketBundlePacket?.newInstance(packets)
}
/**
* 发送数据包
* @param player 玩家
* @param packet 数据包实例
*/
fun sendPacket(player: Player, packet: Any) {
// 使用原版方法发送数据包
// 之前通过 TinyProtocol 的 channel.pipeline().writeAndFlush() 暴力发包会有概率出问题
val connection = getConnection(player)
if (sendPacketMethod == null) {
val reflexClass = ReflexClass.of(connection.javaClass)
// 1.18 更名为 send 方法
sendPacketMethod = if (MinecraftVersion.isHigherOrEqual(MinecraftVersion.V1_18)) {
try {
reflexClass.getMethod("send", true, true, packet)
} catch (_: NoSuchMethodException) {
reflexClass.getMethod("sendPacket", true, true, packet)
}
} else {
reflexClass.getMethod("sendPacket", true, true, packet)
}
}
sendPacketMethod!!.invoke(connection, packet)
}
/**
* 获取玩家的连接实例,如果不存在则会抛出 [NullPointerException]
*/
fun getConnection(player: Player): Any {
return if (playerConnectionMap.containsKey(player.name)) {
playerConnectionMap[player.name]!!
} else {
val connection = if (MinecraftVersion.isUniversal) {
player.getProperty<Any>("entity/connection")!!
} else {
player.getProperty<Any>("entity/playerConnection")!!
}
playerConnectionMap[player.name] = connection
connection
}
}
@SubscribeEvent
private fun onJoin(e: PlayerJoinEvent) {
playerConnectionMap.remove(e.player.name)
}
@SubscribeEvent
private fun onQuit(e: PlayerQuitEvent) {
submit(delay = 20) { playerConnectionMap.remove(e.player.name) }
}
} | 412 | 0.84731 | 1 | 0.84731 | game-dev | MEDIA | 0.898353 | game-dev,networking | 0.687351 | 1 | 0.687351 |
Dawn-of-Light/DOLSharp | 3,629 | GameServer/gameutils/LootGeneratorAtlanteanGlass.cs | /*
* DAWN OF LIGHT - The first free open source DAoC server emulator
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
using System;
using System.Reflection;
using DOL.GS;
using DOL.GS.PacketHandler;
using DOL.AI.Brain;
using DOL.Database;
using DOL.Language;
using log4net;
namespace DOL.GS
{
/// <summary>
/// LootGeneratorAtlanteanGlass
/// At the moment this generator only adds AtlanteanGlass to the loot
/// </summary>
public class LootGeneratorAtlanteanGlass : LootGeneratorBase
{
private static ItemTemplate m_atlanteanglass = GameServer.Database.FindObjectByKey<ItemTemplate>("atlanteanglass");
/// <summary>
/// Generate loot for given mob
/// </summary>
/// <param name="mob"></param>
/// <param name="killer"></param>
/// <returns></returns>
public override LootList GenerateLoot(GameNPC mob, GameObject killer)
{
LootList loot = base.GenerateLoot(mob, killer);
try
{
GamePlayer player = killer as GamePlayer;
if (killer is GameNPC && ((GameNPC)killer).Brain is IControlledBrain)
player = ((ControlledNpcBrain)((GameNPC)killer).Brain).GetPlayerOwner();
if (player == null)
return loot;
ItemTemplate atlanteanGlass = GameServer.Database.FindObjectByKey<ItemTemplate>(m_atlanteanglass.Id_nb);
// ItemTemplate atlanteanGlass = new ItemTemplate(m_atlanteanglass); Creating a new ItemTemplate throws an exception later
int killedcon = (int)player.GetConLevel(mob)+3;
if(killedcon <= 0)
return loot;
int lvl = mob.Level + 1;
if (lvl < 1) lvl = 1;
int maxcount = 1;
//Switch pack size
if (lvl > 0 && lvl < 10)
{
//Single AtlanteanGlass
maxcount = (int)Math.Floor((double)(lvl/2))+1;
}
else if (lvl >= 10 && lvl < 20)
{
//Double
atlanteanGlass.PackSize = 2;
maxcount = (int)Math.Floor((double)((lvl-10)/2))+1;
}
else if (lvl >= 20 && lvl < 30)
{
//Triple
atlanteanGlass.PackSize = 3;
maxcount = (int)Math.Floor((double)((lvl-20)/2))+1;
}
else if (lvl >=30 && lvl < 40)
{
//Quad
atlanteanGlass.PackSize = 4;
maxcount = (int)Math.Floor((double)((lvl-30)/2))+1;
}
else if (lvl >= 40 && lvl < 50)
{
//Quint
atlanteanGlass.PackSize = 5;
maxcount = (int)Math.Floor((double)((lvl-40)/2))+1;
}
else
{
//Cache (x10)
atlanteanGlass.PackSize = 10;
maxcount = (int)Math.Round((double)(lvl/10));
}
if (!mob.Name.ToLower().Equals(mob.Name))
{
//Named mob, more cash !
maxcount = (int)Math.Round(maxcount*ServerProperties.Properties.LOOTGENERATOR_ATLANTEANGLASS_NAMED_COUNT);
}
if(maxcount > 0 && Util.Chance(ServerProperties.Properties.LOOTGENERATOR_ATLANTEANGLASS_BASE_CHANCE+Math.Max(10, killedcon)))
loot.AddFixed(atlanteanGlass, maxcount);
}
catch
{
return loot;
}
return loot;
}
}
}
| 412 | 0.904395 | 1 | 0.904395 | game-dev | MEDIA | 0.973406 | game-dev | 0.965799 | 1 | 0.965799 |
ImLegiitXD/Blossom | 2,229 | src/main/java/net/minecraft/tileentity/TileEntityMobSpawner.java | package net.minecraft.tileentity;
import net.minecraft.init.Blocks;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.Packet;
import net.minecraft.network.play.server.S35PacketUpdateTileEntity;
import net.minecraft.util.BlockPos;
import net.minecraft.util.ITickable;
import net.minecraft.world.World;
public class TileEntityMobSpawner extends TileEntity implements ITickable
{
private final MobSpawnerBaseLogic spawnerLogic = new MobSpawnerBaseLogic()
{
public void func_98267_a(int id)
{
TileEntityMobSpawner.this.worldObj.addBlockEvent(TileEntityMobSpawner.this.pos, Blocks.mob_spawner, id, 0);
}
public World getSpawnerWorld()
{
return TileEntityMobSpawner.this.worldObj;
}
public BlockPos getSpawnerPosition()
{
return TileEntityMobSpawner.this.pos;
}
public void setRandomEntity(MobSpawnerBaseLogic.WeightedRandomMinecart p_98277_1_)
{
super.setRandomEntity(p_98277_1_);
if (this.getSpawnerWorld() != null)
{
this.getSpawnerWorld().markBlockForUpdate(TileEntityMobSpawner.this.pos);
}
}
};
public void readFromNBT(NBTTagCompound compound)
{
super.readFromNBT(compound);
this.spawnerLogic.readFromNBT(compound);
}
public void writeToNBT(NBTTagCompound compound)
{
super.writeToNBT(compound);
this.spawnerLogic.writeToNBT(compound);
}
public void update()
{
this.spawnerLogic.updateSpawner();
}
public Packet getDescriptionPacket()
{
NBTTagCompound nbttagcompound = new NBTTagCompound();
this.writeToNBT(nbttagcompound);
nbttagcompound.removeTag("SpawnPotentials");
return new S35PacketUpdateTileEntity(this.pos, 1, nbttagcompound);
}
public boolean receiveClientEvent(int id, int type)
{
return this.spawnerLogic.setDelayToMin(id) ? true : super.receiveClientEvent(id, type);
}
public boolean func_183000_F()
{
return true;
}
public MobSpawnerBaseLogic getSpawnerBaseLogic()
{
return this.spawnerLogic;
}
}
| 412 | 0.912208 | 1 | 0.912208 | game-dev | MEDIA | 0.991321 | game-dev | 0.897622 | 1 | 0.897622 |
pablushaa/AllahClientRecode | 28,148 | net/minecraft/world/storage/WorldInfo.java | package net.minecraft.world.storage;
import com.google.common.collect.Maps;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.Nullable;
import net.minecraft.crash.CrashReportCategory;
import net.minecraft.crash.ICrashReportDetail;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.datafix.DataFixer;
import net.minecraft.util.datafix.FixTypes;
import net.minecraft.util.datafix.IDataFixer;
import net.minecraft.util.datafix.IDataWalker;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.DimensionType;
import net.minecraft.world.EnumDifficulty;
import net.minecraft.world.GameRules;
import net.minecraft.world.GameType;
import net.minecraft.world.WorldSettings;
import net.minecraft.world.WorldType;
public class WorldInfo
{
private String versionName;
private int versionId;
private boolean versionSnapshot;
public static final EnumDifficulty DEFAULT_DIFFICULTY = EnumDifficulty.NORMAL;
/** Holds the seed of the currently world. */
private long randomSeed;
private WorldType terrainType = WorldType.DEFAULT;
private String generatorOptions = "";
/** The spawn zone position X coordinate. */
private int spawnX;
/** The spawn zone position Y coordinate. */
private int spawnY;
/** The spawn zone position Z coordinate. */
private int spawnZ;
/** Total time for this world. */
private long totalTime;
/** The current world time in ticks, ranging from 0 to 23999. */
private long worldTime;
/** The last time the player was in this world. */
private long lastTimePlayed;
/** The size of entire save of current world on the disk, isn't exactly. */
private long sizeOnDisk;
private NBTTagCompound playerTag;
private int dimension;
/** The name of the save defined at world creation. */
private String levelName;
/** Introduced in beta 1.3, is the save version for future control. */
private int saveVersion;
private int cleanWeatherTime;
/** True if it's raining, false otherwise. */
private boolean raining;
/** Number of ticks until next rain. */
private int rainTime;
/** Is thunderbolts failing now? */
private boolean thundering;
/** Number of ticks untils next thunderbolt. */
private int thunderTime;
/** The Game Type. */
private GameType theGameType;
/**
* Whether the map features (e.g. strongholds) generation is enabled or disabled.
*/
private boolean mapFeaturesEnabled;
/** Hardcore mode flag */
private boolean hardcore;
private boolean allowCommands;
private boolean initialized;
private EnumDifficulty difficulty;
private boolean difficultyLocked;
private double borderCenterX;
private double borderCenterZ;
private double borderSize = 6.0E7D;
private long borderSizeLerpTime;
private double borderSizeLerpTarget;
private double borderSafeZone = 5.0D;
private double borderDamagePerBlock = 0.2D;
private int borderWarningDistance = 5;
private int borderWarningTime = 15;
private final Map<DimensionType, NBTTagCompound> dimensionData = Maps.newEnumMap(DimensionType.class);
private GameRules theGameRules = new GameRules();
protected WorldInfo()
{
}
public static void registerFixes(DataFixer fixer)
{
fixer.registerWalker(FixTypes.LEVEL, new IDataWalker()
{
public NBTTagCompound process(IDataFixer fixer, NBTTagCompound compound, int versionIn)
{
if (compound.hasKey("Player", 10))
{
compound.setTag("Player", fixer.process(FixTypes.PLAYER, compound.getCompoundTag("Player"), versionIn));
}
return compound;
}
});
}
public WorldInfo(NBTTagCompound nbt)
{
if (nbt.hasKey("Version", 10))
{
NBTTagCompound nbttagcompound = nbt.getCompoundTag("Version");
this.versionName = nbttagcompound.getString("Name");
this.versionId = nbttagcompound.getInteger("Id");
this.versionSnapshot = nbttagcompound.getBoolean("Snapshot");
}
this.randomSeed = nbt.getLong("RandomSeed");
if (nbt.hasKey("generatorName", 8))
{
String s1 = nbt.getString("generatorName");
this.terrainType = WorldType.parseWorldType(s1);
if (this.terrainType == null)
{
this.terrainType = WorldType.DEFAULT;
}
else if (this.terrainType.isVersioned())
{
int i = 0;
if (nbt.hasKey("generatorVersion", 99))
{
i = nbt.getInteger("generatorVersion");
}
this.terrainType = this.terrainType.getWorldTypeForGeneratorVersion(i);
}
if (nbt.hasKey("generatorOptions", 8))
{
this.generatorOptions = nbt.getString("generatorOptions");
}
}
this.theGameType = GameType.getByID(nbt.getInteger("GameType"));
if (nbt.hasKey("MapFeatures", 99))
{
this.mapFeaturesEnabled = nbt.getBoolean("MapFeatures");
}
else
{
this.mapFeaturesEnabled = true;
}
this.spawnX = nbt.getInteger("SpawnX");
this.spawnY = nbt.getInteger("SpawnY");
this.spawnZ = nbt.getInteger("SpawnZ");
this.totalTime = nbt.getLong("Time");
if (nbt.hasKey("DayTime", 99))
{
this.worldTime = nbt.getLong("DayTime");
}
else
{
this.worldTime = this.totalTime;
}
this.lastTimePlayed = nbt.getLong("LastPlayed");
this.sizeOnDisk = nbt.getLong("SizeOnDisk");
this.levelName = nbt.getString("LevelName");
this.saveVersion = nbt.getInteger("version");
this.cleanWeatherTime = nbt.getInteger("clearWeatherTime");
this.rainTime = nbt.getInteger("rainTime");
this.raining = nbt.getBoolean("raining");
this.thunderTime = nbt.getInteger("thunderTime");
this.thundering = nbt.getBoolean("thundering");
this.hardcore = nbt.getBoolean("hardcore");
if (nbt.hasKey("initialized", 99))
{
this.initialized = nbt.getBoolean("initialized");
}
else
{
this.initialized = true;
}
if (nbt.hasKey("allowCommands", 99))
{
this.allowCommands = nbt.getBoolean("allowCommands");
}
else
{
this.allowCommands = this.theGameType == GameType.CREATIVE;
}
if (nbt.hasKey("Player", 10))
{
this.playerTag = nbt.getCompoundTag("Player");
this.dimension = this.playerTag.getInteger("Dimension");
}
if (nbt.hasKey("GameRules", 10))
{
this.theGameRules.readFromNBT(nbt.getCompoundTag("GameRules"));
}
if (nbt.hasKey("Difficulty", 99))
{
this.difficulty = EnumDifficulty.getDifficultyEnum(nbt.getByte("Difficulty"));
}
if (nbt.hasKey("DifficultyLocked", 1))
{
this.difficultyLocked = nbt.getBoolean("DifficultyLocked");
}
if (nbt.hasKey("BorderCenterX", 99))
{
this.borderCenterX = nbt.getDouble("BorderCenterX");
}
if (nbt.hasKey("BorderCenterZ", 99))
{
this.borderCenterZ = nbt.getDouble("BorderCenterZ");
}
if (nbt.hasKey("BorderSize", 99))
{
this.borderSize = nbt.getDouble("BorderSize");
}
if (nbt.hasKey("BorderSizeLerpTime", 99))
{
this.borderSizeLerpTime = nbt.getLong("BorderSizeLerpTime");
}
if (nbt.hasKey("BorderSizeLerpTarget", 99))
{
this.borderSizeLerpTarget = nbt.getDouble("BorderSizeLerpTarget");
}
if (nbt.hasKey("BorderSafeZone", 99))
{
this.borderSafeZone = nbt.getDouble("BorderSafeZone");
}
if (nbt.hasKey("BorderDamagePerBlock", 99))
{
this.borderDamagePerBlock = nbt.getDouble("BorderDamagePerBlock");
}
if (nbt.hasKey("BorderWarningBlocks", 99))
{
this.borderWarningDistance = nbt.getInteger("BorderWarningBlocks");
}
if (nbt.hasKey("BorderWarningTime", 99))
{
this.borderWarningTime = nbt.getInteger("BorderWarningTime");
}
if (nbt.hasKey("DimensionData", 10))
{
NBTTagCompound nbttagcompound1 = nbt.getCompoundTag("DimensionData");
for (String s : nbttagcompound1.getKeySet())
{
this.dimensionData.put(DimensionType.getById(Integer.parseInt(s)), nbttagcompound1.getCompoundTag(s));
}
}
}
public WorldInfo(WorldSettings settings, String name)
{
this.populateFromWorldSettings(settings);
this.levelName = name;
this.difficulty = DEFAULT_DIFFICULTY;
this.initialized = false;
}
public void populateFromWorldSettings(WorldSettings settings)
{
this.randomSeed = settings.getSeed();
this.theGameType = settings.getGameType();
this.mapFeaturesEnabled = settings.isMapFeaturesEnabled();
this.hardcore = settings.getHardcoreEnabled();
this.terrainType = settings.getTerrainType();
this.generatorOptions = settings.getGeneratorOptions();
this.allowCommands = settings.areCommandsAllowed();
}
public WorldInfo(WorldInfo worldInformation)
{
this.randomSeed = worldInformation.randomSeed;
this.terrainType = worldInformation.terrainType;
this.generatorOptions = worldInformation.generatorOptions;
this.theGameType = worldInformation.theGameType;
this.mapFeaturesEnabled = worldInformation.mapFeaturesEnabled;
this.spawnX = worldInformation.spawnX;
this.spawnY = worldInformation.spawnY;
this.spawnZ = worldInformation.spawnZ;
this.totalTime = worldInformation.totalTime;
this.worldTime = worldInformation.worldTime;
this.lastTimePlayed = worldInformation.lastTimePlayed;
this.sizeOnDisk = worldInformation.sizeOnDisk;
this.playerTag = worldInformation.playerTag;
this.dimension = worldInformation.dimension;
this.levelName = worldInformation.levelName;
this.saveVersion = worldInformation.saveVersion;
this.rainTime = worldInformation.rainTime;
this.raining = worldInformation.raining;
this.thunderTime = worldInformation.thunderTime;
this.thundering = worldInformation.thundering;
this.hardcore = worldInformation.hardcore;
this.allowCommands = worldInformation.allowCommands;
this.initialized = worldInformation.initialized;
this.theGameRules = worldInformation.theGameRules;
this.difficulty = worldInformation.difficulty;
this.difficultyLocked = worldInformation.difficultyLocked;
this.borderCenterX = worldInformation.borderCenterX;
this.borderCenterZ = worldInformation.borderCenterZ;
this.borderSize = worldInformation.borderSize;
this.borderSizeLerpTime = worldInformation.borderSizeLerpTime;
this.borderSizeLerpTarget = worldInformation.borderSizeLerpTarget;
this.borderSafeZone = worldInformation.borderSafeZone;
this.borderDamagePerBlock = worldInformation.borderDamagePerBlock;
this.borderWarningTime = worldInformation.borderWarningTime;
this.borderWarningDistance = worldInformation.borderWarningDistance;
}
/**
* Creates a new NBTTagCompound for the world, with the given NBTTag as the "Player"
*/
public NBTTagCompound cloneNBTCompound(@Nullable NBTTagCompound nbt)
{
if (nbt == null)
{
nbt = this.playerTag;
}
NBTTagCompound nbttagcompound = new NBTTagCompound();
this.updateTagCompound(nbttagcompound, nbt);
return nbttagcompound;
}
private void updateTagCompound(NBTTagCompound nbt, NBTTagCompound playerNbt)
{
NBTTagCompound nbttagcompound = new NBTTagCompound();
nbttagcompound.setString("Name", "1.12.2");
nbttagcompound.setInteger("Id", 1343);
nbttagcompound.setBoolean("Snapshot", false);
nbt.setTag("Version", nbttagcompound);
nbt.setInteger("DataVersion", 1343);
nbt.setLong("RandomSeed", this.randomSeed);
nbt.setString("generatorName", this.terrainType.getWorldTypeName());
nbt.setInteger("generatorVersion", this.terrainType.getGeneratorVersion());
nbt.setString("generatorOptions", this.generatorOptions);
nbt.setInteger("GameType", this.theGameType.getID());
nbt.setBoolean("MapFeatures", this.mapFeaturesEnabled);
nbt.setInteger("SpawnX", this.spawnX);
nbt.setInteger("SpawnY", this.spawnY);
nbt.setInteger("SpawnZ", this.spawnZ);
nbt.setLong("Time", this.totalTime);
nbt.setLong("DayTime", this.worldTime);
nbt.setLong("SizeOnDisk", this.sizeOnDisk);
nbt.setLong("LastPlayed", MinecraftServer.getCurrentTimeMillis());
nbt.setString("LevelName", this.levelName);
nbt.setInteger("version", this.saveVersion);
nbt.setInteger("clearWeatherTime", this.cleanWeatherTime);
nbt.setInteger("rainTime", this.rainTime);
nbt.setBoolean("raining", this.raining);
nbt.setInteger("thunderTime", this.thunderTime);
nbt.setBoolean("thundering", this.thundering);
nbt.setBoolean("hardcore", this.hardcore);
nbt.setBoolean("allowCommands", this.allowCommands);
nbt.setBoolean("initialized", this.initialized);
nbt.setDouble("BorderCenterX", this.borderCenterX);
nbt.setDouble("BorderCenterZ", this.borderCenterZ);
nbt.setDouble("BorderSize", this.borderSize);
nbt.setLong("BorderSizeLerpTime", this.borderSizeLerpTime);
nbt.setDouble("BorderSafeZone", this.borderSafeZone);
nbt.setDouble("BorderDamagePerBlock", this.borderDamagePerBlock);
nbt.setDouble("BorderSizeLerpTarget", this.borderSizeLerpTarget);
nbt.setDouble("BorderWarningBlocks", (double)this.borderWarningDistance);
nbt.setDouble("BorderWarningTime", (double)this.borderWarningTime);
if (this.difficulty != null)
{
nbt.setByte("Difficulty", (byte)this.difficulty.getDifficultyId());
}
nbt.setBoolean("DifficultyLocked", this.difficultyLocked);
nbt.setTag("GameRules", this.theGameRules.writeToNBT());
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
for (Entry<DimensionType, NBTTagCompound> entry : this.dimensionData.entrySet())
{
nbttagcompound1.setTag(String.valueOf(((DimensionType)entry.getKey()).getId()), entry.getValue());
}
nbt.setTag("DimensionData", nbttagcompound1);
if (playerNbt != null)
{
nbt.setTag("Player", playerNbt);
}
}
/**
* Returns the seed of current world.
*/
public long getSeed()
{
return this.randomSeed;
}
/**
* Returns the x spawn position
*/
public int getSpawnX()
{
return this.spawnX;
}
/**
* Return the Y axis spawning point of the player.
*/
public int getSpawnY()
{
return this.spawnY;
}
/**
* Returns the z spawn position
*/
public int getSpawnZ()
{
return this.spawnZ;
}
public long getWorldTotalTime()
{
return this.totalTime;
}
/**
* Get current world time
*/
public long getWorldTime()
{
return this.worldTime;
}
public long getSizeOnDisk()
{
return this.sizeOnDisk;
}
/**
* Returns the player's NBTTagCompound to be loaded
*/
public NBTTagCompound getPlayerNBTTagCompound()
{
return this.playerTag;
}
/**
* Set the x spawn position to the passed in value
*/
public void setSpawnX(int x)
{
this.spawnX = x;
}
/**
* Sets the y spawn position
*/
public void setSpawnY(int y)
{
this.spawnY = y;
}
/**
* Set the z spawn position to the passed in value
*/
public void setSpawnZ(int z)
{
this.spawnZ = z;
}
public void setWorldTotalTime(long time)
{
this.totalTime = time;
}
/**
* Set current world time
*/
public void setWorldTime(long time)
{
this.worldTime = time;
}
public void setSpawn(BlockPos spawnPoint)
{
this.spawnX = spawnPoint.getX();
this.spawnY = spawnPoint.getY();
this.spawnZ = spawnPoint.getZ();
}
/**
* Get current world name
*/
public String getWorldName()
{
return this.levelName;
}
public void setWorldName(String worldName)
{
this.levelName = worldName;
}
/**
* Returns the save version of this world
*/
public int getSaveVersion()
{
return this.saveVersion;
}
/**
* Sets the save version of the world
*/
public void setSaveVersion(int version)
{
this.saveVersion = version;
}
/**
* Return the last time the player was in this world.
*/
public long getLastTimePlayed()
{
return this.lastTimePlayed;
}
public int getCleanWeatherTime()
{
return this.cleanWeatherTime;
}
public void setCleanWeatherTime(int cleanWeatherTimeIn)
{
this.cleanWeatherTime = cleanWeatherTimeIn;
}
/**
* Returns true if it is thundering, false otherwise.
*/
public boolean isThundering()
{
return this.thundering;
}
/**
* Sets whether it is thundering or not.
*/
public void setThundering(boolean thunderingIn)
{
this.thundering = thunderingIn;
}
/**
* Returns the number of ticks until next thunderbolt.
*/
public int getThunderTime()
{
return this.thunderTime;
}
/**
* Defines the number of ticks until next thunderbolt.
*/
public void setThunderTime(int time)
{
this.thunderTime = time;
}
/**
* Returns true if it is raining, false otherwise.
*/
public boolean isRaining()
{
return this.raining;
}
/**
* Sets whether it is raining or not.
*/
public void setRaining(boolean isRaining)
{
this.raining = isRaining;
}
/**
* Return the number of ticks until rain.
*/
public int getRainTime()
{
return this.rainTime;
}
/**
* Sets the number of ticks until rain.
*/
public void setRainTime(int time)
{
this.rainTime = time;
}
/**
* Gets the GameType.
*/
public GameType getGameType()
{
return this.theGameType;
}
/**
* Get whether the map features (e.g. strongholds) generation is enabled or disabled.
*/
public boolean isMapFeaturesEnabled()
{
return this.mapFeaturesEnabled;
}
public void setMapFeaturesEnabled(boolean enabled)
{
this.mapFeaturesEnabled = enabled;
}
/**
* Sets the GameType.
*/
public void setGameType(GameType type)
{
this.theGameType = type;
}
/**
* Returns true if hardcore mode is enabled, otherwise false
*/
public boolean isHardcoreModeEnabled()
{
return this.hardcore;
}
public void setHardcore(boolean hardcoreIn)
{
this.hardcore = hardcoreIn;
}
public WorldType getTerrainType()
{
return this.terrainType;
}
public void setTerrainType(WorldType type)
{
this.terrainType = type;
}
public String getGeneratorOptions()
{
return this.generatorOptions == null ? "" : this.generatorOptions;
}
/**
* Returns true if commands are allowed on this World.
*/
public boolean areCommandsAllowed()
{
return this.allowCommands;
}
public void setAllowCommands(boolean allow)
{
this.allowCommands = allow;
}
/**
* Returns true if the World is initialized.
*/
public boolean isInitialized()
{
return this.initialized;
}
/**
* Sets the initialization status of the World.
*/
public void setServerInitialized(boolean initializedIn)
{
this.initialized = initializedIn;
}
/**
* Gets the GameRules class Instance.
*/
public GameRules getGameRulesInstance()
{
return this.theGameRules;
}
/**
* Returns the border center X position
*/
public double getBorderCenterX()
{
return this.borderCenterX;
}
/**
* Returns the border center Z position
*/
public double getBorderCenterZ()
{
return this.borderCenterZ;
}
public double getBorderSize()
{
return this.borderSize;
}
/**
* Sets the border size
*/
public void setBorderSize(double size)
{
this.borderSize = size;
}
/**
* Returns the border lerp time
*/
public long getBorderLerpTime()
{
return this.borderSizeLerpTime;
}
/**
* Sets the border lerp time
*/
public void setBorderLerpTime(long time)
{
this.borderSizeLerpTime = time;
}
/**
* Returns the border lerp target
*/
public double getBorderLerpTarget()
{
return this.borderSizeLerpTarget;
}
/**
* Sets the border lerp target
*/
public void setBorderLerpTarget(double lerpSize)
{
this.borderSizeLerpTarget = lerpSize;
}
/**
* Sets the border center Z position
*/
public void getBorderCenterZ(double posZ)
{
this.borderCenterZ = posZ;
}
/**
* Sets the border center X position
*/
public void getBorderCenterX(double posX)
{
this.borderCenterX = posX;
}
/**
* Returns the border safe zone
*/
public double getBorderSafeZone()
{
return this.borderSafeZone;
}
/**
* Sets the border safe zone
*/
public void setBorderSafeZone(double amount)
{
this.borderSafeZone = amount;
}
/**
* Returns the border damage per block
*/
public double getBorderDamagePerBlock()
{
return this.borderDamagePerBlock;
}
/**
* Sets the border damage per block
*/
public void setBorderDamagePerBlock(double damage)
{
this.borderDamagePerBlock = damage;
}
/**
* Returns the border warning distance
*/
public int getBorderWarningDistance()
{
return this.borderWarningDistance;
}
/**
* Returns the border warning time
*/
public int getBorderWarningTime()
{
return this.borderWarningTime;
}
/**
* Sets the border warning distance
*/
public void setBorderWarningDistance(int amountOfBlocks)
{
this.borderWarningDistance = amountOfBlocks;
}
/**
* Sets the border warning time
*/
public void setBorderWarningTime(int ticks)
{
this.borderWarningTime = ticks;
}
public EnumDifficulty getDifficulty()
{
return this.difficulty;
}
public void setDifficulty(EnumDifficulty newDifficulty)
{
this.difficulty = newDifficulty;
}
public boolean isDifficultyLocked()
{
return this.difficultyLocked;
}
public void setDifficultyLocked(boolean locked)
{
this.difficultyLocked = locked;
}
/**
* Adds this WorldInfo instance to the crash report.
*/
public void addToCrashReport(CrashReportCategory category)
{
category.setDetail("Level seed", new ICrashReportDetail<String>()
{
public String call() throws Exception
{
return String.valueOf(WorldInfo.this.getSeed());
}
});
category.setDetail("Level generator", new ICrashReportDetail<String>()
{
public String call() throws Exception
{
return String.format("ID %02d - %s, ver %d. Features enabled: %b", WorldInfo.this.terrainType.getWorldTypeID(), WorldInfo.this.terrainType.getWorldTypeName(), WorldInfo.this.terrainType.getGeneratorVersion(), WorldInfo.this.mapFeaturesEnabled);
}
});
category.setDetail("Level generator options", new ICrashReportDetail<String>()
{
public String call() throws Exception
{
return WorldInfo.this.generatorOptions;
}
});
category.setDetail("Level spawn location", new ICrashReportDetail<String>()
{
public String call() throws Exception
{
return CrashReportCategory.getCoordinateInfo(WorldInfo.this.spawnX, WorldInfo.this.spawnY, WorldInfo.this.spawnZ);
}
});
category.setDetail("Level time", new ICrashReportDetail<String>()
{
public String call() throws Exception
{
return String.format("%d game time, %d day time", WorldInfo.this.totalTime, WorldInfo.this.worldTime);
}
});
category.setDetail("Level dimension", new ICrashReportDetail<String>()
{
public String call() throws Exception
{
return String.valueOf(WorldInfo.this.dimension);
}
});
category.setDetail("Level storage version", new ICrashReportDetail<String>()
{
public String call() throws Exception
{
String s = "Unknown?";
try
{
switch (WorldInfo.this.saveVersion)
{
case 19132:
s = "McRegion";
break;
case 19133:
s = "Anvil";
}
}
catch (Throwable var3)
{
;
}
return String.format("0x%05X - %s", WorldInfo.this.saveVersion, s);
}
});
category.setDetail("Level weather", new ICrashReportDetail<String>()
{
public String call() throws Exception
{
return String.format("Rain time: %d (now: %b), thunder time: %d (now: %b)", WorldInfo.this.rainTime, WorldInfo.this.raining, WorldInfo.this.thunderTime, WorldInfo.this.thundering);
}
});
category.setDetail("Level game mode", new ICrashReportDetail<String>()
{
public String call() throws Exception
{
return String.format("Game mode: %s (ID %d). Hardcore: %b. Cheats: %b", WorldInfo.this.theGameType.getName(), WorldInfo.this.theGameType.getID(), WorldInfo.this.hardcore, WorldInfo.this.allowCommands);
}
});
}
public NBTTagCompound getDimensionData(DimensionType dimensionIn)
{
NBTTagCompound nbttagcompound = this.dimensionData.get(dimensionIn);
return nbttagcompound == null ? new NBTTagCompound() : nbttagcompound;
}
public void setDimensionData(DimensionType dimensionIn, NBTTagCompound compound)
{
this.dimensionData.put(dimensionIn, compound);
}
public int getVersionId()
{
return this.versionId;
}
public boolean isVersionSnapshot()
{
return this.versionSnapshot;
}
public String getVersionName()
{
return this.versionName;
}
}
| 412 | 0.902963 | 1 | 0.902963 | game-dev | MEDIA | 0.958872 | game-dev | 0.971496 | 1 | 0.971496 |
Pursue525/Nattalie-1.12.2 | 14,728 | src/net/minecraft/block/BlockShulkerBox.java | package net.minecraft.block;
import java.util.List;
import javax.annotation.Nullable;
import net.minecraft.block.material.EnumPushReaction;
import net.minecraft.block.material.MapColor;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyDirection;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.state.BlockFaceShape;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.ItemStackHelper;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.stats.StatList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityShulkerBox;
import net.minecraft.util.EnumBlockRenderType;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.Mirror;
import net.minecraft.util.NonNullList;
import net.minecraft.util.Rotation;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.translation.I18n;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
public class BlockShulkerBox extends BlockContainer
{
public static final PropertyEnum<EnumFacing> field_190957_a = PropertyDirection.create("facing");
private final EnumDyeColor field_190958_b;
public BlockShulkerBox(EnumDyeColor p_i47248_1_)
{
super(Material.ROCK, MapColor.AIR);
this.field_190958_b = p_i47248_1_;
this.setCreativeTab(CreativeTabs.DECORATIONS);
this.setDefaultState(this.blockState.getBaseState().withProperty(field_190957_a, EnumFacing.UP));
}
/**
* Returns a new instance of a block's tile entity class. Called on placing the block.
*/
public TileEntity createNewTileEntity(World worldIn, int meta)
{
return new TileEntityShulkerBox(this.field_190958_b);
}
/**
* Used to determine ambient occlusion and culling when rebuilding chunks for render
*/
public boolean isOpaqueCube(IBlockState state)
{
return false;
}
public boolean causesSuffocation(IBlockState p_176214_1_)
{
return true;
}
public boolean isFullCube(IBlockState state)
{
return false;
}
public boolean func_190946_v(IBlockState p_190946_1_)
{
return true;
}
/**
* The type of render function called. MODEL for mixed tesr and static model, MODELBLOCK_ANIMATED for TESR-only,
* LIQUID for vanilla liquids, INVISIBLE to skip all rendering
*/
public EnumBlockRenderType getRenderType(IBlockState state)
{
return EnumBlockRenderType.ENTITYBLOCK_ANIMATED;
}
public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing heldItem, float side, float hitX, float hitY)
{
if (worldIn.isRemote)
{
return true;
}
else if (playerIn.isSpectator())
{
return true;
}
else
{
TileEntity tileentity = worldIn.getTileEntity(pos);
if (tileentity instanceof TileEntityShulkerBox)
{
EnumFacing enumfacing = (EnumFacing)state.getValue(field_190957_a);
boolean flag;
if (((TileEntityShulkerBox)tileentity).func_190591_p() == TileEntityShulkerBox.AnimationStatus.CLOSED)
{
AxisAlignedBB axisalignedbb = FULL_BLOCK_AABB.addCoord((double)(0.5F * (float)enumfacing.getFrontOffsetX()), (double)(0.5F * (float)enumfacing.getFrontOffsetY()), (double)(0.5F * (float)enumfacing.getFrontOffsetZ())).func_191195_a((double)enumfacing.getFrontOffsetX(), (double)enumfacing.getFrontOffsetY(), (double)enumfacing.getFrontOffsetZ());
flag = !worldIn.collidesWithAnyBlock(axisalignedbb.offset(pos.offset(enumfacing)));
}
else
{
flag = true;
}
if (flag)
{
playerIn.addStat(StatList.field_191272_ae);
playerIn.displayGUIChest((IInventory)tileentity);
}
return true;
}
else
{
return false;
}
}
}
/**
* Called by ItemBlocks just before a block is actually set in the world, to allow for adjustments to the
* IBlockstate
*/
public IBlockState onBlockPlaced(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer)
{
return this.getDefaultState().withProperty(field_190957_a, facing);
}
protected BlockStateContainer createBlockState()
{
return new BlockStateContainer(this, new IProperty[] {field_190957_a});
}
/**
* Convert the BlockState into the correct metadata value
*/
public int getMetaFromState(IBlockState state)
{
return ((EnumFacing)state.getValue(field_190957_a)).getIndex();
}
/**
* Convert the given metadata into a BlockState for this Block
*/
public IBlockState getStateFromMeta(int meta)
{
EnumFacing enumfacing = EnumFacing.getFront(meta);
return this.getDefaultState().withProperty(field_190957_a, enumfacing);
}
public void onBlockHarvested(World worldIn, BlockPos pos, IBlockState state, EntityPlayer player)
{
if (worldIn.getTileEntity(pos) instanceof TileEntityShulkerBox)
{
TileEntityShulkerBox tileentityshulkerbox = (TileEntityShulkerBox)worldIn.getTileEntity(pos);
tileentityshulkerbox.func_190579_a(player.capabilities.isCreativeMode);
tileentityshulkerbox.fillWithLoot(player);
}
}
/**
* Spawns this Block's drops into the World as EntityItems.
*/
public void dropBlockAsItemWithChance(World worldIn, BlockPos pos, IBlockState state, float chance, int fortune)
{
}
/**
* Called by ItemBlocks after a block is set in the world, to allow post-place logic
*/
public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack)
{
if (stack.hasDisplayName())
{
TileEntity tileentity = worldIn.getTileEntity(pos);
if (tileentity instanceof TileEntityShulkerBox)
{
((TileEntityShulkerBox)tileentity).func_190575_a(stack.getDisplayName());
}
}
}
/**
* Called serverside after this block is replaced with another in Chunk, but before the Tile Entity is updated
*/
public void breakBlock(World worldIn, BlockPos pos, IBlockState state)
{
TileEntity tileentity = worldIn.getTileEntity(pos);
if (tileentity instanceof TileEntityShulkerBox)
{
TileEntityShulkerBox tileentityshulkerbox = (TileEntityShulkerBox)tileentity;
if (!tileentityshulkerbox.func_190590_r() && tileentityshulkerbox.func_190582_F())
{
ItemStack itemstack = new ItemStack(Item.getItemFromBlock(this));
NBTTagCompound nbttagcompound = new NBTTagCompound();
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
nbttagcompound.setTag("BlockEntityTag", ((TileEntityShulkerBox)tileentity).func_190580_f(nbttagcompound1));
itemstack.setTagCompound(nbttagcompound);
if (tileentityshulkerbox.hasCustomName())
{
itemstack.setStackDisplayName(tileentityshulkerbox.getName());
tileentityshulkerbox.func_190575_a("");
}
spawnAsEntity(worldIn, pos, itemstack);
}
worldIn.updateComparatorOutputLevel(pos, state.getBlock());
}
super.breakBlock(worldIn, pos, state);
}
public void func_190948_a(ItemStack p_190948_1_, @Nullable World p_190948_2_, List<String> p_190948_3_, ITooltipFlag p_190948_4_)
{
super.func_190948_a(p_190948_1_, p_190948_2_, p_190948_3_, p_190948_4_);
NBTTagCompound nbttagcompound = p_190948_1_.getTagCompound();
if (nbttagcompound != null && nbttagcompound.hasKey("BlockEntityTag", 10))
{
NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("BlockEntityTag");
if (nbttagcompound1.hasKey("LootTable", 8))
{
p_190948_3_.add("???????");
}
if (nbttagcompound1.hasKey("Items", 9))
{
NonNullList<ItemStack> nonnulllist = NonNullList.<ItemStack>func_191197_a(27, ItemStack.field_190927_a);
ItemStackHelper.func_191283_b(nbttagcompound1, nonnulllist);
int i = 0;
int j = 0;
for (ItemStack itemstack : nonnulllist)
{
if (!itemstack.func_190926_b())
{
++j;
if (i <= 4)
{
++i;
p_190948_3_.add(String.format("%s x%d", itemstack.getDisplayName(), itemstack.func_190916_E()));
}
}
}
if (j - i > 0)
{
p_190948_3_.add(String.format(TextFormatting.ITALIC + I18n.translateToLocal("container.shulkerBox.more"), j - i));
}
}
}
}
public EnumPushReaction getMobilityFlag(IBlockState state)
{
return EnumPushReaction.DESTROY;
}
public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos)
{
TileEntity tileentity = source.getTileEntity(pos);
return tileentity instanceof TileEntityShulkerBox ? ((TileEntityShulkerBox)tileentity).func_190584_a(state) : FULL_BLOCK_AABB;
}
public boolean hasComparatorInputOverride(IBlockState state)
{
return true;
}
public int getComparatorInputOverride(IBlockState blockState, World worldIn, BlockPos pos)
{
return Container.calcRedstoneFromInventory((IInventory)worldIn.getTileEntity(pos));
}
public ItemStack getItem(World worldIn, BlockPos pos, IBlockState state)
{
ItemStack itemstack = super.getItem(worldIn, pos, state);
TileEntityShulkerBox tileentityshulkerbox = (TileEntityShulkerBox)worldIn.getTileEntity(pos);
NBTTagCompound nbttagcompound = tileentityshulkerbox.func_190580_f(new NBTTagCompound());
if (!nbttagcompound.hasNoTags())
{
itemstack.setTagInfo("BlockEntityTag", nbttagcompound);
}
return itemstack;
}
public static EnumDyeColor func_190955_b(Item p_190955_0_)
{
return func_190954_c(Block.getBlockFromItem(p_190955_0_));
}
public static EnumDyeColor func_190954_c(Block p_190954_0_)
{
return p_190954_0_ instanceof BlockShulkerBox ? ((BlockShulkerBox)p_190954_0_).func_190956_e() : EnumDyeColor.PURPLE;
}
public static Block func_190952_a(EnumDyeColor p_190952_0_)
{
switch (p_190952_0_)
{
case WHITE:
return Blocks.field_190977_dl;
case ORANGE:
return Blocks.field_190978_dm;
case MAGENTA:
return Blocks.field_190979_dn;
case LIGHT_BLUE:
return Blocks.field_190980_do;
case YELLOW:
return Blocks.field_190981_dp;
case LIME:
return Blocks.field_190982_dq;
case PINK:
return Blocks.field_190983_dr;
case GRAY:
return Blocks.field_190984_ds;
case SILVER:
return Blocks.field_190985_dt;
case CYAN:
return Blocks.field_190986_du;
case PURPLE:
default:
return Blocks.field_190987_dv;
case BLUE:
return Blocks.field_190988_dw;
case BROWN:
return Blocks.field_190989_dx;
case GREEN:
return Blocks.field_190990_dy;
case RED:
return Blocks.field_190991_dz;
case BLACK:
return Blocks.field_190975_dA;
}
}
public EnumDyeColor func_190956_e()
{
return this.field_190958_b;
}
public static ItemStack func_190953_b(EnumDyeColor p_190953_0_)
{
return new ItemStack(func_190952_a(p_190953_0_));
}
/**
* Returns the blockstate with the given rotation from the passed blockstate. If inapplicable, returns the passed
* blockstate.
*/
public IBlockState withRotation(IBlockState state, Rotation rot)
{
return state.withProperty(field_190957_a, rot.rotate((EnumFacing)state.getValue(field_190957_a)));
}
/**
* Returns the blockstate with the given mirror of the passed blockstate. If inapplicable, returns the passed
* blockstate.
*/
public IBlockState withMirror(IBlockState state, Mirror mirrorIn)
{
return state.withRotation(mirrorIn.toRotation((EnumFacing)state.getValue(field_190957_a)));
}
public BlockFaceShape func_193383_a(IBlockAccess p_193383_1_, IBlockState p_193383_2_, BlockPos p_193383_3_, EnumFacing p_193383_4_)
{
p_193383_2_ = this.getActualState(p_193383_2_, p_193383_1_, p_193383_3_);
EnumFacing enumfacing = (EnumFacing)p_193383_2_.getValue(field_190957_a);
TileEntityShulkerBox.AnimationStatus tileentityshulkerbox$animationstatus = ((TileEntityShulkerBox)p_193383_1_.getTileEntity(p_193383_3_)).func_190591_p();
return tileentityshulkerbox$animationstatus != TileEntityShulkerBox.AnimationStatus.CLOSED && (tileentityshulkerbox$animationstatus != TileEntityShulkerBox.AnimationStatus.OPENED || enumfacing != p_193383_4_.getOpposite() && enumfacing != p_193383_4_) ? BlockFaceShape.UNDEFINED : BlockFaceShape.SOLID;
}
}
| 412 | 0.858854 | 1 | 0.858854 | game-dev | MEDIA | 0.999234 | game-dev | 0.963614 | 1 | 0.963614 |
hyvanmielenpelit/GnollHack | 64,478 | src/wield.c | /* GnollHack File Change Notice: This file has been changed from the original. Date of last change: 2024-08-11 */
/* GnollHack 4.0 wield.c $NHDT-Date: 1543492132 2018/11/29 11:48:52 $ $NHDT-Branch: GnollHack-3.6.2-beta01 $:$NHDT-Revision: 1.58 $ */
/* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
/*-Copyright (c) Robert Patrick Rankin, 2009. */
/* GnollHack may be freely redistributed. See license for details. */
#include "hack.h"
/* KMH -- Differences between the three weapon slots.
*
* The main weapon (uwep):
* 1. Is filled by the (w)ield command.
* 2. Can be filled with any type of item.
* 3. May be carried in one or both hands.
* 4. Is used as the melee weapon and as the launcher for
* ammunition.
* 5. Only conveys intrinsics when it is a weapon, weapon-tool,
* or artifact.
* 6. Certain cursed items will weld to the hand and cannot be
* unwielded or dropped. See erodeable_wep() and will_weld()
* below for the list of which items apply.
*
* The secondary weapon (uswapwep):
* 1. Is filled by the e(x)change command, which swaps this slot
* with the main weapon. If the "pushweapon" option is set,
* the (w)ield command will also store the old weapon in the
* secondary slot.
* 2. Can be filled with anything that will fit in the main weapon
* slot; that is, any type of item.
* 3. Is usually NOT considered to be carried in the hands.
* That would force too many checks among the main weapon,
* second weapon, shield, gloves, and rings; and it would
* further be complicated by bimanual weapons. A special
* exception is made for two-weapon combat.
* 4. Is used as the second weapon for two-weapon combat, and as
* a convenience to swap with the main weapon.
* 5. Never conveys intrinsics.
* 6. Cursed items never weld (see #3 for reasons), but they also
* prevent two-weapon combat.
*
* The quiver (uquiver):
* 1. Is filled by the (Q)uiver command.
* 2. Can be filled with any type of item.
* 3. Is considered to be carried in a special part of the pack.
* 4. Is used as the item to throw with the (f)ire command.
* This is a convenience over the normal (t)hrow command.
* 5. Never conveys intrinsics.
* 6. Cursed items never weld; their effect is handled by the normal
* throwing code.
* 7. The autoquiver option will fill it with something deemed
* suitable if (f)ire is used when it's empty.
*
* No item may be in more than one of these slots.
*/
STATIC_DCL boolean FDECL(cant_wield_corpse, (struct obj *));
STATIC_DCL int FDECL(ready_weapon, (struct obj *, int64_t));
/* used by will_weld() */
/* probably should be renamed */
#define erodeable_wep(optr) \
((optr)->oclass == WEAPON_CLASS || is_weptool(optr) \
|| (optr)->otyp == HEAVY_IRON_BALL || (optr)->otyp == IRON_CHAIN)
/* used by welded(), and also while wielding */
#define will_weld(otmp, mtmp) \
((otmp)->cursed && (erodeable_wep(otmp) || (otmp)->otyp == TIN_OPENER) && !cursed_items_are_positive_mon(mtmp))
/*** Functions that place a given item in a slot ***/
/* Proper usage includes:
* 1. Initializing the slot during character generation or a
* restore.
* 2. Setting the slot due to a player's actions.
* 3. If one of the objects in the slot are split off, these
* functions can be used to put the remainder back in the slot.
* 4. Putting an item that was thrown and returned back into the slot.
* 5. Emptying the slot, by passing a null object. NEVER pass
* zeroobj!
*
* If the item is being moved from another slot, it is the caller's
* responsibility to handle that. It's also the caller's responsibility
* to print the appropriate messages.
*/
void
setuwep(obj, mask)
register struct obj* obj;
int64_t mask;
{
setuwepcore(obj, mask, TRUE);
}
void
setuwepquietly(obj, mask)
register struct obj* obj;
int64_t mask;
{
setuwepcore(obj, mask, FALSE);
}
void
setuwepcore(obj, mask, verbose)
register struct obj *obj;
int64_t mask;
boolean verbose;
{
struct obj* olduwep = (struct obj*)0;
if (mask == W_WEP)
{
olduwep = uwep;
}
else
{
olduwep = uarms;
}
if (obj == olduwep)
return; /* necessary to not set unweapon */
/* This message isn't printed in the caller because it happens
* *whenever* Sunsword is unwielded, from whatever cause.
*/
setworncore(obj, mask, verbose);
boolean invneedsupdate = FALSE;
if (obj && (objects[obj->otyp].oc_flags & O1_IS_ARMOR_WHEN_WIELDED))
{
invneedsupdate = verbose && obj->known != 1;
obj->known = 1;
}
if (uwep == obj && olduwep && (artifact_light(olduwep) || has_obj_mythic_magical_light(olduwep) || obj_shines_magical_light(olduwep)) && olduwep->lamplit) {
Strcpy(debug_buf_3, "setuwepcore");
end_burn(olduwep, FALSE);
if (!Blind && verbose)
pline_ex(ATR_NONE, CLR_MSG_ATTENTION, "%s shining.", Tobjnam(olduwep, "stop"));
}
context.botl = context.botlx = 1;
/* Note: Explicitly wielding a pick-axe will not give a "bashing"
* message. Wielding one via 'a'pplying it will.
* 3.2.2: Wielding arbitrary objects will give bashing message too.
*/
update_unweapon();
if (invneedsupdate)
update_inventory();
}
void
update_unweapon(VOID_ARGS)
{
update_hand_unweapon(1);
update_hand_unweapon(2);
}
void
update_hand_unweapon(hand)
int hand;
{
struct obj* wep = (hand <= 1 ? uwep : uarms);
boolean* unweapon_ptr = (hand <= 1 ? &unweapon1 : &unweapon2);
if (hand >= 2 && !u.twoweap)
{
*unweapon_ptr = FALSE;
return;
}
if (wep)
{
*unweapon_ptr = is_unweapon(wep);
}
else
{
*unweapon_ptr = ((uarmg && is_weapon(uarmg) && (P_SKILL_LEVEL(P_BARE_HANDED_COMBAT) >= P_SKILLED)) || (P_SKILL_LEVEL(P_MARTIAL_ARTS) >= P_BASIC) || (P_SKILL_LEVEL(P_BARE_HANDED_COMBAT) >= P_EXPERT)) ? FALSE : TRUE; /* for "bare hands" message */
}
}
STATIC_OVL boolean
cant_wield_corpse(obj)
struct obj *obj;
{
char kbuf[BUFSZ];
if (uarmg || obj->otyp != CORPSE || obj->corpsenm < LOW_PM || !touch_petrifies(&mons[obj->corpsenm])
|| Stone_resistance)
return FALSE;
/* Prevent wielding cockatrice when not wearing gloves --KAA */
You("wield %s in your bare %s.",
corpse_xname(obj, (const char *) 0, CXN_PFX_THE),
makeplural(body_part(HAND)));
Sprintf(kbuf, "wielding %s bare-handed", killer_xname(obj));
killer.hint_idx = HINT_KILLED_TOUCHED_COCKATRICE_CORPSE;
instapetrify(kbuf);
return TRUE;
}
STATIC_OVL int
ready_weapon(wep, mask)
struct obj *wep;
int64_t mask;
{
/* Separated function so swapping works easily */
int res = 0;
struct obj* wepinhand = (struct obj*)0;
struct obj* wepinotherhand = (struct obj*)0;
if (mask == W_WEP)
{
wepinhand = uwep;
wepinotherhand = uarms;
}
else if (mask == W_WEP2)
{
wepinhand = uarms;
wepinotherhand = uwep;
}
if (!wep)
{
/* No weapon */
if (wepinhand)
{
if(u.twoweap)
Your("%s %s is now empty.", mask == W_WEP2 ? "left" : "right", body_part(HAND));
else
You("are now empty %s.", body_part(HANDED));
setuwep((struct obj *) 0, mask);
res++;
}
else
{
if (u.twoweap)
Your("%s %s is already empty.", mask == W_WEP2 ? "left" : "right", body_part(HAND));
else
You("are already empty %s.", body_part(HANDED));
}
}
else if (wep->otyp == CORPSE && cant_wield_corpse(wep))
{
/* hero must have been life-saved to get here; use a turn */
res++; /* corpse won't be wielded */
}
else if (wepinotherhand && bimanual(wep))
{
play_sfx_sound(SFX_GENERAL_CANNOT);
You_ex(ATR_NONE, CLR_MSG_FAIL, "cannot wield a two-handed %s while %s.",
is_sword(wep) ? "sword" : wep->otyp == BATTLE_AXE ? "axe"
: "weapon", is_shield(wepinotherhand) ? "wearing a shield" : "wielding a weapon in the other hand");
}
else if (!retouch_object(&wep, FALSE))
{
res++; /* takes a turn even though it doesn't get wielded */
}
else
{
/* Weapon WILL be wielded after this point */
res++;
if (will_weld(wep, &youmonst))
{
const char *tmp = xname(wep), *thestr = "The ";
if (strncmp(tmp, thestr, 4) && !strncmp(The(tmp), thestr, 4))
tmp = thestr;
else
tmp = "";
play_sfx_sound(SFX_ITEM_WELDS);
pline_ex(ATR_NONE, CLR_MSG_NEGATIVE, "%s%s %s to your %s!", tmp, aobjnam(wep, "weld"),
(wep->quan == 1L) ? "itself" : "themselves", /* a3 */
bimanual(wep) ? (const char *) makeplural(body_part(HAND))
: body_part(HAND));
wep->bknown = TRUE;
}
else
{
/* The message must be printed before setuwep (since
* you might die and be revived from changing weapons),
* and the message must be before the death message and
* Lifesaved rewielding. Yet we want the message to
* say "weapon in hand", thus this kludge.
* [That comment is obsolete. It dates from the days (3.0)
* when unwielding Firebrand could cause hero to be burned
* to death in Hell due to loss of fire resistance.
* "Lifesaved re-wielding or re-wearing" is ancient history.]
*/
//Kludge removed by Janne Gustafsson; items may now be identified by setuwep
/*
int64_t dummy = wep->owornmask;
wep->owornmask |= W_WEP;
if (is_obj_tethered_weapon(wep, wep->owornmask))
You("secure the tether.");
wep->owornmask = dummy;
*/
}
setuwep(wep, mask);
prinv((char*)0, wep, 0L);
/* KMH -- Talking artifacts are finally implemented */
arti_speak(wep);
if (wep && (artifact_light(wep) || has_obj_mythic_magical_light(wep) || (obj_shines_magical_light(wep) && !inappropriate_monster_character_type(&youmonst, wep))) && !wep->lamplit)
{
begin_burn(wep, FALSE);
if (!Blind)
pline_ex(ATR_NONE, CLR_MSG_ATTENTION, "%s to shine %s!", Tobjnam(wep, "begin"),
arti_light_description(wep));
}
if (wep && wep->unpaid)
{
struct monst *this_shkp;
if ((this_shkp = shop_keeper(inside_shop(u.ux, u.uy)))
!= (struct monst *) 0) {
pline("%s says \"You be careful with my %s!\"",
shkname(this_shkp), xname(wep));
}
}
}
return res;
}
void
setuqwep(obj)
register struct obj *obj;
{
setworncore(obj, W_QUIVER, TRUE);
context.botl = context.botlx = TRUE;
status_reassess();
/* no extra handling needed; this used to include a call to
update_inventory() but that's already performed by setworn() */
return;
}
void
setuswapwep(obj, mask)
register struct obj *obj;
int64_t mask;
{
setworncore(obj, mask, TRUE);
return;
}
void
setuqwepquietly(obj)
register struct obj* obj;
{
setworncore(obj, W_QUIVER, FALSE);
/* no extra handling needed; this used to include a call to
update_inventory() but that's already performed by setworn() */
return;
}
void
setuswapwepquietly(obj, mask)
register struct obj* obj;
int64_t mask;
{
setworncore(obj, mask, FALSE);
return;
}
/*** Commands to change particular slot(s) ***/
STATIC_VAR NEARDATA const char wield_objs[] = {
ALL_CLASSES, ALLOW_NONE, WEAPON_CLASS, TOOL_CLASS, 0
};
STATIC_VAR NEARDATA const char ready_objs[] = {
ALLOW_COUNT, COIN_CLASS, ALL_CLASSES, ALLOW_NONE, WEAPON_CLASS, 0
};
STATIC_VAR NEARDATA const char bullets[] = { /* (note: different from dothrow.c) */
ALLOW_COUNT, COIN_CLASS, ALL_CLASSES, ALLOW_NONE,
GEM_CLASS, WEAPON_CLASS, 0
};
STATIC_VAR NEARDATA const char unwield_objs[] = { ALL_CLASSES, 0 };
int
dowield()
{
struct obj* wep;
/* May we attempt this? */
multi = 0;
if (cantwield(youmonst.data))
{
play_sfx_sound(SFX_GENERAL_CANNOT);
pline_ex(ATR_NONE, CLR_MSG_FAIL, "Don't be ridiculous!");
return 0;
}
/* Prompt for a new weapon */
if (!(wep = getobj(wield_objs, "wield", 0, "")))
/* Cancelled */
return 0;
return wield_weapon(wep);
}
int
dowieldprevwep()
{
multi = 0;
if (cantwield(youmonst.data))
{
play_sfx_sound(SFX_GENERAL_CANNOT);
pline_ex(ATR_NONE, CLR_MSG_FAIL, "Don't be ridiculous!");
return 0;
}
if (uwep && (uwep->speflags & SPEFLAGS_NO_PREVIOUS_WEAPON))
{
if (welded(uwep, &youmonst))
{
weldmsg(uwep);
/* previously interrupted armor removal mustn't be resumed */
reset_remarm();
return 0;
}
struct obj* otmp = uwep;
int result = ready_weapon((struct obj*)0, W_WEP);
boolean unwield_succeeded = uwep == (struct obj*)0;
if (unwield_succeeded)
{
otmp->speflags &= ~SPEFLAGS_NO_PREVIOUS_WEAPON;
play_simple_object_sound(otmp, OBJECT_SOUND_TYPE_UNWIELD);
update_all_character_properties((struct obj*)0, TRUE);
status_reassess();
}
return result;
}
else
{
struct obj* wep = 0;
struct obj* otmp;
for (otmp = invent; otmp; otmp = otmp->nobj)
{
if (otmp->speflags & SPEFLAGS_PREVIOUSLY_WIELDED)
{
wep = otmp;
break;
}
}
if (wep)
return wield_weapon(wep);
else
{
play_sfx_sound(SFX_GENERAL_CANNOT);
You_ex(ATR_NONE, CLR_MSG_FAIL, "couldn't locate your previous weapon!");
return 0;
}
}
}
int
wield_weapon(wep)
struct obj* wep;
{
struct obj* oldwep;
int result;
if (u.twoweap)
{
if (wep == uwep || wep == uarms)
{
play_sfx_sound(SFX_GENERAL_CANNOT);
You_ex(ATR_NONE, CLR_MSG_FAIL, "are already wielding that!");
return 0;
}
int64_t mask = 0;
char qbuf[BUFSZ] = "";
if (wep == &zeroobj)
{
if (uwep && uarms)
{
char answer = '\0';
do {
Sprintf(qbuf, "Which %s, Left or Right?",
body_part(HAND));
answer = yn_function(qbuf, "lr", '\0', "Left\nRight");
switch (answer) {
case '\0':
return 0;
case 'l':
case 'L':
mask = W_WEP2;
break;
case 'r':
case 'R':
mask = W_WEP;
break;
}
} while (!mask);
}
else if (uwep)
mask = W_WEP;
else if (uarms)
mask = W_WEP2;
}
else if (bimanual(wep))
{
mask = W_WEP;
}
else if (uwep && !uarms)
{
if (bimanual(uwep))
{
play_sfx_sound(SFX_GENERAL_CANNOT);
You_ex(ATR_NONE, CLR_MSG_FAIL, "cannot wield another weapon while wielding a two-handed weapon.");
return 0;
}
mask = W_WEP2;
}
else if (uarms && !uwep)
{
if (bimanual(uarms))
{
play_sfx_sound(SFX_GENERAL_CANNOT);
You_ex(ATR_NONE, CLR_MSG_FAIL, "cannot wield another weapon while wielding a two-handed weapon.");
return 0;
}
mask = W_WEP;
}
else
{
char answer = '\0';
do
{
Sprintf(qbuf, "Which %s, Left or Right?",
body_part(HAND));
answer = yn_function(qbuf, "lr", '\0', "Left\nRight");
switch (answer)
{
case '\0':
return 0;
case 'l':
case 'L':
mask = W_WEP2;
break;
case 'r':
case 'R':
mask = W_WEP;
break;
}
} while (!mask);
}
if ((mask == W_WEP || bimanual(wep)) && uwep && welded(uwep, &youmonst))
{
weldmsg(uwep);
/* previously interrupted armor removal mustn't be resumed */
reset_remarm();
return 0;
}
if ((mask == W_WEP2 || bimanual(wep)) && uarms && welded(uarms, &youmonst))
{
weldmsg(uarms);
/* previously interrupted armor removal mustn't be resumed */
reset_remarm();
return 0;
}
/* Handle no object, or object in other slot */
if (wep == &zeroobj)
wep = (struct obj*) 0;
else if (bimanual(wep) && (wep == uswapwep || wep == uswapwep2))
return doswapweapon();
else if (wep == uswapwep)
return dosingleswapweapon(W_SWAPWEP, mask);
else if (wep == uswapwep2)
return dosingleswapweapon(W_SWAPWEP2, mask);
else if (wep == uquiver)
setuqwep((struct obj*) 0);
else if (wep->owornmask & (W_ARMOR | W_ACCESSORY | W_SADDLE)) {
play_sfx_sound(SFX_GENERAL_CANNOT);
You_ex(ATR_NONE, CLR_MSG_FAIL, "cannot wield that!");
return 0;
}
/* Set your new primary weapon */
boolean ready_succeeded = FALSE;
if(mask == W_WEP)
{
oldwep = uwep;
result = ready_weapon(wep, W_WEP);
ready_succeeded = (uwep == wep);
if (flags.pushweapon && oldwep && uwep != oldwep)
setuswapwep(oldwep, W_SWAPWEP);
}
else
{
oldwep = uarms;
result = ready_weapon(wep, W_WEP2);
ready_succeeded = (uarms == wep);
if (flags.pushweapon && oldwep && uarms != oldwep)
setuswapwep(oldwep, W_SWAPWEP2);
}
if (ready_succeeded)
{
if (wep)
play_simple_object_sound(wep, OBJECT_SOUND_TYPE_WIELD);
else if (oldwep)
play_simple_object_sound(oldwep, OBJECT_SOUND_TYPE_UNWIELD);
}
}
else
{
if (wep == uwep)
{
play_sfx_sound(SFX_GENERAL_CANNOT);
You_ex(ATR_NONE, CLR_MSG_FAIL, "are already wielding that!");
return 0;
}
else if (welded(uwep, &youmonst))
{
weldmsg(uwep);
/* previously interrupted armor removal mustn't be resumed */
reset_remarm();
return 0;
}
/* Handle no object, or object in other slot */
if (wep == &zeroobj)
wep = (struct obj *) 0;
else if (bimanual(wep) && (wep == uswapwep || wep == uswapwep2))
return doswapweapon();
else if (wep == uswapwep)
return dosingleswapweapon(W_SWAPWEP, W_WEP);
else if (wep == uswapwep2)
return dosingleswapweapon(W_SWAPWEP2, W_WEP);
else if (wep == uquiver)
setuqwep((struct obj *) 0);
else if (wep->owornmask & (W_ARMOR | W_ACCESSORY | W_SADDLE))
{
play_sfx_sound(SFX_GENERAL_CANNOT);
You_ex(ATR_NONE, CLR_MSG_FAIL, "cannot wield that!");
return 0;
}
if (wep && bimanual(wep) && uarms && !is_shield(uarms) && !welded(uarms, &youmonst))
{
/* Automate the unwield to assist the player */
/* If weapon is bimanual and you have an unused secondardy weapon in hand, unwield it */
remove_worn_item(uarms, FALSE);
}
/* Set your new primary weapon */
oldwep = uwep;
result = ready_weapon(wep, W_WEP);
boolean ready_succeeded = (uwep == wep);
if (flags.pushweapon && oldwep && uwep != oldwep)
setuswapwep(oldwep, W_SWAPWEP);
if (ready_succeeded)
{
if (wep)
play_simple_object_sound(wep, OBJECT_SOUND_TYPE_WIELD);
else if (oldwep)
play_simple_object_sound(oldwep, OBJECT_SOUND_TYPE_UNWIELD);
}
}
update_all_character_properties((struct obj*)0, TRUE);
status_reassess();
return result;
}
/* the unwield command */
int
dounwield()
{
struct obj* otmp = (struct obj*)0;
if (!uwep && !uwep2) {
play_sfx_sound(SFX_GENERAL_CANNOT);
pline_ex(ATR_NONE, CLR_MSG_FAIL, "Not wielding anything.");
return 0;
}
otmp = getobj(unwield_objs, "unwield", 0, "");
if (!otmp || !(otmp->owornmask & W_WEAPON))
return 0;
int64_t mask = 0L;
if (otmp == uwep)
mask = W_WEP;
else if (otmp == uwep2)
mask = W_WEP2;
else if (otmp == uswapwep)
mask = W_SWAPWEP;
else if (otmp == uswapwep2)
mask = W_SWAPWEP2;
else if (otmp == uquiver)
mask = W_QUIVER;
else
return 0;
int result = 0;
if (mask == W_WEP2 && otmp == uarms && is_shield(otmp))
{
result = armor_or_accessory_off(otmp);
}
else if (mask == W_SWAPWEP)
{
uswapwepgone();
result = 1;
}
else if (mask == W_SWAPWEP2)
{
uswapwep2gone();
result = 1;
}
else if (mask == W_QUIVER)
{
uqwepgone();
result = 1;
}
else
{
if (welded(otmp, &youmonst))
{
weldmsg(otmp);
/* previously interrupted armor removal mustn't be resumed */
reset_remarm();
return 0;
}
result = ready_weapon((struct obj*)0, mask);
}
boolean unwield_succeeded =
mask == W_WEP ? (uwep == (struct obj*)0) :
mask == W_WEP2 ? (uwep2 == (struct obj*)0) :
mask == W_SWAPWEP ? (uswapwep == (struct obj*)0) :
mask == W_SWAPWEP2 ? (uswapwep2 == (struct obj*)0) :
mask == W_QUIVER ? (uquiver == (struct obj*)0) :
FALSE;
if (unwield_succeeded) //Note: shield unwearing may take longer
{
play_simple_object_sound(otmp, OBJECT_SOUND_TYPE_UNWIELD);
update_all_character_properties((struct obj*)0, TRUE);
status_reassess();
}
return result;
}
int
dosingleswapweapon(swap_wep_mask, swap_target_mask)
int64_t swap_wep_mask, swap_target_mask; // swap_wep_mask = mask of original weapon in swapwep, swap_target_mask is the mask it is going to swapped to
{
register struct obj *oldwep, * oldswap;
register struct obj *wep = (struct obj*)0, *altwep = (struct obj*)0, *swapwep = (struct obj*)0, *altswapwep = (struct obj*)0;
int result = 0;
if (swap_wep_mask == W_SWAPWEP)
{
swapwep = uswapwep;
altswapwep = uswapwep2;
if (swap_target_mask == W_WEP)
{
wep = uwep;
altwep = uarms;
}
else
{
wep = uarms;
altwep = uwep;
}
}
else
{
swapwep = uswapwep2;
altswapwep = uswapwep;
if (swap_target_mask == W_WEP2)
{
wep = uarms;
altwep = uwep;
}
else
{
wep = uwep;
altwep = uarms;
}
}
/* May we attempt this? */
multi = 0;
if (cantwield(youmonst.data))
{
play_sfx_sound(SFX_GENERAL_CANNOT);
pline_ex(ATR_NONE, CLR_MSG_FAIL, "Don't be ridiculous!");
return 0;
}
if (wep && wep->cursed && swapwep)
{
weldmsg(wep);
return 0;
}
if (wep && bimanual(wep) && altswapwep)
{
play_sfx_sound(SFX_GENERAL_CANNOT);
You_ex(ATR_NONE, CLR_MSG_FAIL, "cannot ready a two-handed weapon while having something already readied for the other %s.", body_part(HAND));
return 0;
}
if (wep && altwep && swapwep && bimanual(swapwep))
{
play_sfx_sound(SFX_GENERAL_CANNOT);
You_ex(ATR_NONE, CLR_MSG_FAIL, "cannot swap to a two-handed weapon while holding something in the other %s.", body_part(HAND));
return 0;
}
if (!wep && !swapwep)
{
play_sfx_sound(SFX_GENERAL_CANNOT);
Your_ex(ATR_NONE, CLR_MSG_FAIL, "%s %s is already empty.", swap_target_mask == W_WEP ? "right" : "left", body_part(HAND));
return 0;
}
//play_ui_sound(UI_SOUND_WEAPON_SWAPPED);
/* Unwield your current secondary weapon */
oldwep = wep;
oldswap = swapwep;
setuswapwep((struct obj*)0, swap_wep_mask);
/* Set your new secondary weapon */
result = ready_weapon(oldswap, swap_target_mask);
/* Handle swap */
struct obj* curwep = (swap_target_mask == W_WEP ? uwep : uarms);
if (curwep == oldwep)
{
/* Wield failed for some reason */
setuswapwep(oldswap, swap_wep_mask);
}
else
{
if (curwep == oldswap)
{
/* Wield succeeded */
play_simple_object_sound(oldswap, OBJECT_SOUND_TYPE_WIELD);
}
setuswapwep(oldwep, swap_wep_mask);
struct obj* curswapwep = (swap_wep_mask == W_SWAPWEP ? uswapwep : uswapwep2);
struct obj* curswapwep2 = (swap_wep_mask == W_SWAPWEP ? uswapwep2 : uswapwep);
if (curswapwep)
prinv((char*)0, curswapwep, 0L);
else if (!(curswapwep2 && bimanual(curswapwep2)))
You("have no %s %s alternate weapon readied.", swap_wep_mask == W_SWAPWEP ? "right" : "left", body_part(HAND));
}
if (result)
{
/* Do nothing */
}
status_reassess();
//Do not take a turn
return 0; // result;
}
int
doswaphandedness()
{
flags.swap_rhand_only = !flags.swap_rhand_only;
if (flags.swap_rhand_only)
{
play_ui_sound(UI_SOUND_WEAPON_SWAPPING_IN_RIGHT_HAND_ONLY);
You("are now swapping weapons only in your right %s.", body_part(HAND));
}
else
{
play_ui_sound(UI_SOUND_WEAPON_SWAPPING_IN_BOTH_HANDS);
You("are now swapping weapons in your both %s.", makeplural(body_part(HAND)));
}
return 0;
}
int
doswapweapon_right_or_both()
{
if (flags.swap_rhand_only)
return dosingleswapweapon(W_SWAPWEP, W_WEP);
else
return doswapweapon();
}
int
doswapweapon()
{
register struct obj *oldwep, *oldswap;
register struct obj* oldwep2, * oldswap2;
int result = 0;
int result2 = 0;
/* May we attempt this? */
multi = 0;
if (cantwield(youmonst.data))
{
play_sfx_sound(SFX_GENERAL_CANNOT);
pline_ex(ATR_NONE, CLR_MSG_FAIL, "Don't be ridiculous!");
return 0;
}
if (u.twoweap)
{
if (uwep && welded(uwep, &youmonst))
{
weldmsg(uwep);
return 0;
}
if (uarms && welded(uarms, &youmonst))
{
weldmsg(uarms);
return 0;
}
if (!uwep && !uswapwep && !uarms && !uswapwep2)
{
play_sfx_sound(SFX_GENERAL_CANNOT);
Your_ex(ATR_NONE, CLR_MSG_FAIL, "both %s are already empty.", makeplural(body_part(HAND)));
return 0;
}
//play_ui_sound(UI_SOUND_WEAPON_SWAPPED);
/* Unwield your current secondary weapon */
oldwep = uwep;
oldswap = uswapwep;
oldwep2 = uarms;
oldswap2 = uswapwep2;
setuswapwep((struct obj*) 0, W_SWAPWEP);
setuswapwep((struct obj*) 0, W_SWAPWEP2);
/* Unwield your current weapons */
if(oldwep)
setuwep((struct obj*) 0, W_WEP);
if(oldwep2)
setuwep((struct obj*) 0, W_WEP2);
/* Set your new primary weapon */
if (oldswap)
{
result = ready_weapon(oldswap, W_WEP);
if (uwep == oldswap)
{
play_simple_object_sound(oldswap, OBJECT_SOUND_TYPE_WIELD);
}
}
else if (oldwep)
{
play_simple_object_sound(oldwep, OBJECT_SOUND_TYPE_UNWIELD);
}
if (oldswap2)
{
result2 = ready_weapon(oldswap2, W_WEP2);
if (uarms == oldswap2)
{
play_simple_object_sound(oldswap2, OBJECT_SOUND_TYPE_WIELD);
}
}
else if (oldwep2)
{
play_simple_object_sound(oldwep2, OBJECT_SOUND_TYPE_UNWIELD);
}
/* Set your new secondary weapon */
if (uwep == oldwep)
{
/* Wield failed for some reason */
if(oldswap)
setuswapwep(oldswap, W_SWAPWEP);
}
else
{
if(oldwep)
{
setuswapwep(oldwep, W_SWAPWEP);
if (uswapwep)
prinv((char*)0, uswapwep, 0L);
else if (!(uswapwep2 && bimanual(uswapwep2)))
You("have no right hand alternate weapon readied.");
}
}
if (uarms == oldwep2)
{
/* Wield failed for some reason */
setuswapwep(oldswap2, W_SWAPWEP2);
}
else
{
if (oldwep2)
{
setuswapwep(oldwep2, W_SWAPWEP2);
if (uswapwep2)
prinv((char*)0, uswapwep2, 0L);
else if (!(uswapwep && bimanual(uswapwep)))
You("have no left hand alternate weapon readied.");
}
}
}
else
{
if (welded(uwep, &youmonst))
{
weldmsg(uwep);
return 0;
}
if (uarms && uarms->cursed && !cursed_items_are_positive(youmonst.data) /*&& (uswapwep2 || (uswapwep && bimanual(uswapwep))) */ )
{
weldmsg(uarms);
if (!flags.swap_rhand_only && yn_query("Do you want to swap weapons only in your right hand?") == 'y')
{
(void)doswaphandedness();
return doswapweapon_right_or_both();
}
return 0;
}
if (!uwep && !uswapwep && !uarms && !uswapwep2)
{
play_sfx_sound(SFX_GENERAL_CANNOT);
You_ex(ATR_NONE, CLR_MSG_FAIL, "are already empty %s.", body_part(HANDED));
return 0;
}
//play_ui_sound(UI_SOUND_WEAPON_SWAPPED);
/* Unwield your current secondary weapon */
oldwep = uwep;
oldwep2 = uarms;
oldswap = uswapwep;
oldswap2 = uswapwep2;
setuswapwep((struct obj*)0, W_SWAPWEP);
setuswapwep((struct obj*)0, W_SWAPWEP2);
/* Unwield your current weapons / shields */
if(oldwep)
setuwep((struct obj*) 0, W_WEP);
if (oldwep2)
{
if (is_shield(oldwep2))
remove_worn_item(oldwep2, FALSE);
else
setuwep((struct obj*) 0, W_WEP2);
}
/* Set your new primary weapon */
result = ready_weapon(oldswap, W_WEP);
/* Set your new secondary weapon */
if (uwep == oldwep)
{
/* Wield failed for some reason */
setuswapwep(oldswap, W_SWAPWEP);
}
else
{
if (uwep == oldswap)
{
/* Wield succeeded */
if (oldswap)
{
play_simple_object_sound(oldswap, OBJECT_SOUND_TYPE_WIELD);
}
else if (oldwep)
{
play_simple_object_sound(oldwep, OBJECT_SOUND_TYPE_UNWIELD);
}
}
setuswapwep(oldwep, W_SWAPWEP);
if (uswapwep)
prinv((char *) 0, uswapwep, 0L);
else if (!(uswapwep2 && bimanual(uswapwep2)))
You("have no alternate weapon readied.");
if(oldwep2 && !oldswap2)
{
setuswapwep(oldwep2, W_SWAPWEP2);
if (uswapwep2)
prinv((char*)0, uswapwep2, 0L);
else if (!(uswapwep && bimanual(uswapwep)))
You("have no alternate shield readied.");
}
}
if (oldswap2 && !(uwep && (bimanual(uwep) || bimanual(oldswap2))))
{
if (is_shield(oldswap2))
{
setworn(oldswap2, W_ARMS);
if (uarms)
prinv((char*)0, uarms, 0L);
}
else if (erodeable_wep(oldswap2))
ready_weapon(oldswap2, W_WEP2);
if (uarms == oldwep2)
{
/* Wield failed for some reason */
setuswapwep(oldswap2, W_SWAPWEP2);
}
else
{
if (uarms == oldswap2)
{
/* Wield succeeded */
if (oldswap2)
{
play_simple_object_sound(oldswap2, OBJECT_SOUND_TYPE_WIELD);
}
else if (oldwep2)
{
play_simple_object_sound(oldwep2, OBJECT_SOUND_TYPE_UNWIELD);
}
}
setuswapwep(oldwep2, W_SWAPWEP2);
if (uswapwep2)
prinv((char*)0, uswapwep2, 0L);
else if(!(uswapwep && bimanual(uswapwep)))
You("have no alternate shield readied.");
}
}
}
if (result || result2)
{
/* Do nothing */
}
status_reassess();
//Do not take a turn
return 0; // result;
}
int
dowieldquiver()
{
char qbuf[QBUFSZ];
struct obj *newquiver;
const char *quivee_types;
int res;
boolean finish_splitting = FALSE,
was_uwep = FALSE, was_uarms = FALSE, was_twoweap = u.twoweap;
/* Since the quiver isn't in your hands, don't check cantwield(), */
/* will_weld(), touch_petrifies(), etc. */
multi = 0;
/* forget last splitobj() before calling getobj() with ALLOW_COUNT */
context.objsplit.child_oid = context.objsplit.parent_oid = 0;
/* Prompt for a new quiver: "What do you want to ready?"
(Include gems/stones as likely candidates if either primary
or secondary weapon is a sling.) */
quivee_types = (uslinging()
|| (uswapwep
&& objects[uswapwep->otyp].oc_skill == P_SLING))
? bullets
: ready_objs;
newquiver = getobj(quivee_types, "ready", 0, "");
if (!newquiver)
{
/* Cancelled */
return 0;
}
else if (newquiver == &zeroobj)
{ /* no object */
/* Explicitly nothing */
if (uquiver)
{
play_simple_object_sound(uquiver, OBJECT_SOUND_TYPE_UNQUIVER);
You("now have no ammunition readied.");
/* skip 'quivering: prinv()' */
setuqwep((struct obj *) 0);
}
else
{
play_sfx_sound(SFX_GENERAL_CANNOT);
You_ex(ATR_NONE, CLR_MSG_FAIL, "already have no ammunition readied!");
}
return 0;
}
else if (newquiver->o_id == context.objsplit.child_oid)
{
/* if newquiver is the result of supplying a count to getobj()
we don't want to split something already in the quiver;
for any other item, we need to give it its own inventory slot */
if (uquiver && uquiver->o_id == context.objsplit.parent_oid)
{
unsplitobj(newquiver);
goto already_quivered;
}
finish_splitting = TRUE;
}
else if (newquiver == uquiver)
{
already_quivered:
play_sfx_sound(SFX_GENERAL_CANNOT);
pline_ex(ATR_NONE, CLR_MSG_FAIL, "That ammunition is already readied!");
return 0;
}
else if (newquiver->owornmask & (W_ARMOR | W_ACCESSORY | W_SADDLE))
{
play_sfx_sound(SFX_GENERAL_CANNOT);
You_ex(ATR_NONE, CLR_MSG_FAIL, "cannot ready that!");
return 0;
}
else if (newquiver == uwep && uwep)
{
int weld_res = !uwep->bknown;
if (welded(uwep, &youmonst))
{
weldmsg(uwep);
reset_remarm(); /* same as dowield() */
return weld_res;
}
/* offer to split stack if wielding more than 1 */
if (uwep->quan > 1L && inv_cnt(FALSE) < 52 && splittable(uwep))
{
Sprintf(qbuf, "You are wielding %lld %s. Ready %lld of them?",
(long long)uwep->quan, simpleonames(uwep), (long long)uwep->quan - 1);
switch (ynq(qbuf))
{
case 'q':
return 0;
case 'y':
/* leave 1 wielded, split rest off and put into quiver */
newquiver = splitobj(uwep, uwep->quan - 1L);
finish_splitting = TRUE;
goto quivering;
default:
break;
}
Strcpy(qbuf, "Ready all of them instead?");
}
else
{
boolean use_plural = (is_plural(uwep) || pair_of(uwep));
Sprintf(qbuf, "You are wielding %s. Ready %s instead?",
!use_plural ? "that" : "those",
!use_plural ? "it" : "them");
}
/* require confirmation to ready the main weapon */
if (yn_query(qbuf) != 'y')
{
(void) Shk_Your(qbuf, uwep); /* replace qbuf[] contents */
pline("%s%s %s wielded.", qbuf,
simpleonames(uwep), otense(uwep, "remain"));
return 0;
}
/* quivering main weapon, so no longer wielding it */
setuwep((struct obj *) 0, W_WEP);
//untwoweapon();
was_uwep = TRUE;
}
else if (newquiver == uarms && uarms)
{
int weld_res = !uarms->bknown;
if (welded(uarms, &youmonst))
{
weldmsg(uarms);
reset_remarm(); /* same as dowield() */
return weld_res;
}
/* offer to split stack if wielding more than 1 */
if (uarms->quan > 1L && inv_cnt(FALSE) < 52 && splittable(uarms))
{
Sprintf(qbuf, "You are wielding %lld %s. Ready %lld of them?",
(long long)uarms->quan, simpleonames(uarms), (long long)uarms->quan - 1);
switch (ynq(qbuf))
{
case 'q':
return 0;
case 'y':
/* leave 1 wielded, split rest off and put into quiver */
newquiver = splitobj(uarms, uarms->quan - 1L);
finish_splitting = TRUE;
goto quivering;
default:
break;
}
Strcpy(qbuf, "Ready all of them instead?");
}
else
{
boolean use_plural = (is_plural(uarms) || pair_of(uarms));
Sprintf(qbuf, "You are wielding %s. Ready %s instead?",
!use_plural ? "that" : "those",
!use_plural ? "it" : "them");
}
/* require confirmation to ready the main weapon */
if (yn_query(qbuf) != 'y')
{
(void)Shk_Your(qbuf, uarms); /* replace qbuf[] contents */
pline("%s%s %s wielded.", qbuf,
simpleonames(uarms), otense(uarms, "remain"));
return 0;
}
/* quivering main weapon, so no longer wielding it */
setuwep((struct obj*) 0, W_WEP2);
//untwoweapon();
was_uarms = TRUE;
}
else if (newquiver == uswapwep && uswapwep)
{
if (uswapwep->quan > 1L && inv_cnt(FALSE) < 52
&& splittable(uswapwep))
{
Sprintf(qbuf, "%s %lld %s. Ready %lld of them?",
"Your alternate weapon is",
(long long)uswapwep->quan, simpleonames(uswapwep),
(long long)uswapwep->quan - 1);
switch (ynq(qbuf))
{
case 'q':
return 0;
case 'y':
/* leave 1 alt-wielded, split rest off and put into quiver */
newquiver = splitobj(uswapwep, uswapwep->quan - 1L);
finish_splitting = TRUE;
goto quivering;
default:
break;
}
Strcpy(qbuf, "Ready all of them instead?");
}
else
{
boolean use_plural = (is_plural(uswapwep) || pair_of(uswapwep));
Sprintf(qbuf, "%s your %s weapon. Ready %s instead?",
!use_plural ? "That is" : "Those are",
"alternate",
!use_plural ? "it" : "them");
}
/* require confirmation to ready the alternate weapon */
if (yn_query(qbuf) != 'y')
{
(void) Shk_Your(qbuf, uswapwep); /* replace qbuf[] contents */
pline("%s%s %s %s.", qbuf,
simpleonames(uswapwep), otense(uswapwep, "remain"),
"as alternate weapon");
return 0;
}
/* quivering alternate weapon, so no more uswapwep */
setuswapwep((struct obj *) 0, W_SWAPWEP);
//untwoweapon();
}
else if (newquiver == uswapwep2 && uswapwep2)
{
if (uswapwep2->quan > 1L && inv_cnt(FALSE) < 52
&& splittable(uswapwep2))
{
Sprintf(qbuf, "%s %lld %s. Ready %lld of them?",
"Your alternate weapon is",
(long long)uswapwep2->quan, simpleonames(uswapwep2),
(long long)uswapwep2->quan - 1);
switch (ynq(qbuf))
{
case 'q':
return 0;
case 'y':
/* leave 1 alt-wielded, split rest off and put into quiver */
newquiver = splitobj(uswapwep2, uswapwep2->quan - 1L);
finish_splitting = TRUE;
goto quivering;
default:
break;
}
Strcpy(qbuf, "Ready all of them instead?");
}
else
{
boolean use_plural = (is_plural(uswapwep2) || pair_of(uswapwep2));
Sprintf(qbuf, "%s your %s weapon. Ready %s instead?",
!use_plural ? "That is" : "Those are",
"alternate",
!use_plural ? "it" : "them");
}
/* require confirmation to ready the alternate weapon */
if (yn_query(qbuf) != 'y')
{
(void)Shk_Your(qbuf, uswapwep2); /* replace qbuf[] contents */
pline("%s%s %s %s.", qbuf,
simpleonames(uswapwep2), otense(uswapwep2, "remain"),
"as alternate weapon");
return 0;
}
/* quivering alternate weapon, so no more uswapwep */
setuswapwep((struct obj*) 0, W_SWAPWEP2);
//untwoweapon();
}
quivering:
if (finish_splitting)
{
freeinv(newquiver);
newquiver->nomerge = 1;
addinv(newquiver);
newquiver->nomerge = 0;
}
/* place item in quiver before printing so that inventory feedback
includes "(at the ready)" */
play_simple_object_sound(newquiver, OBJECT_SOUND_TYPE_QUIVER);
setuqwep(newquiver);
prinv((char *) 0, newquiver, 0L);
/* quiver is a convenience slot and manipulating it ordinarily
consumes no time, but unwielding primary or secondary weapon
should take time (perhaps we're adjacent to a rust monster
or disenchanter and want to hit it immediately, but not with
something we're wielding that's vulnerable to its damage) */
res = 0;
if (was_uwep)
{
Your("right %s is now empty.", body_part(HAND));
res = 1;
}
else if (was_uarms)
{
Your("left %s is now empty.", body_part(HAND));
res = 1;
}
else if (was_twoweap && !u.twoweap) {
You("are no longer wielding two weapons at once.");
res = 1;
}
return res;
}
/* used for #rub and for applying pick-axe, whip, grappling hook or polearm */
boolean
wield_tool(obj, verb)
struct obj *obj;
const char *verb; /* "rub",&c */
{
if (!obj)
return FALSE;
const char *what;
boolean more_than_1;
if (obj == uwep || (u.twoweap && obj == uarms))
return TRUE; /* nothing to do if already wielding it */
if (!verb)
verb = "wield";
what = xname(obj);
more_than_1 = (obj->quan > 1L || strstri(what, "pair of ") != 0
|| strstri(what, "s of ") != 0);
if (obj->owornmask & W_WORN_NOT_WIELDED)
{
You_cant_ex(ATR_NONE, CLR_MSG_FAIL, "%s %s while wearing %s.", verb, yname(obj),
more_than_1 ? "them" : "it");
return FALSE;
}
boolean selected_hand_is_right = TRUE;
if (u.twoweap && (obj == uarms || obj == uswapwep2))
selected_hand_is_right = FALSE;
else if (!uwep)
selected_hand_is_right = TRUE;
else if (bimanual(uwep))
selected_hand_is_right = TRUE;
else if (u.twoweap)
{
if (uarms && welded(uarms, &youmonst))
selected_hand_is_right = TRUE;
else if (!uarms)
selected_hand_is_right = FALSE;
else if (uwep && welded(uwep, &youmonst))
selected_hand_is_right = FALSE;
}
struct obj* wep = selected_hand_is_right ? uwep : uarms;
if (wep && welded(wep, &youmonst))
{
if (flags.verbose)
{
const char *hand = body_part(HAND);
if (bimanual(uwep))
hand = makeplural(hand);
if (strstri(what, "pair of ") != 0)
more_than_1 = FALSE;
play_sfx_sound(SFX_GENERAL_CANNOT);
pline_ex(ATR_NONE, CLR_MSG_FAIL,
"Since your weapon is welded to your %s, you cannot %s %s %s.",
hand, verb, more_than_1 ? "those" : "that", xname(obj));
}
else
{
play_sfx_sound(SFX_GENERAL_CANNOT);
You_cant_ex(ATR_NONE, CLR_MSG_FAIL, "do that.");
}
return FALSE;
}
if (cantwield(youmonst.data))
{
You_cant_ex(ATR_NONE, CLR_MSG_FAIL, "hold %s strongly enough.", more_than_1 ? "them" : "it");
return FALSE;
}
/* check shield */
if (uarms && bimanual(obj))
{
play_sfx_sound(SFX_GENERAL_CANNOT);
You_ex(ATR_NONE, CLR_MSG_FAIL, "cannot %s a two-handed %s while %s.", verb,
(obj->oclass == WEAPON_CLASS) ? "weapon" : "tool",
is_shield(obj) ? "wearing a shield" : is_weapon(obj) ? "wielding a weapon in the other hand" : "wielding an item in the other hand");
return FALSE;
}
obj->speflags &= ~SPEFLAGS_NO_PREVIOUS_WEAPON;
if (uquiver == obj)
setuqwep((struct obj *) 0);
else if (bimanual(obj) && uswapwep == obj)
{
(void)doswapweapon();
/* doswapweapon might fail */
if (uswapwep == obj)
return FALSE;
}
else if (uswapwep == obj && uwep && bimanual(uwep))
{
(void)doswapweapon();
/* doswapweapon might fail */
if (uswapwep == obj)
return FALSE;
}
else if (u.twoweap && uswapwep2 == obj && uwep && bimanual(uwep)) /* two-weaponing is needed for swapping, as otherwise the tool wouldn't be ready for use after the function call */
{
(void)doswapweapon();
/* doswapweapon might fail */
if (uswapwep2 == obj)
return FALSE;
}
else if (uswapwep == obj)
{
(void) dosingleswapweapon(W_SWAPWEP, selected_hand_is_right ? W_WEP : W_WEP2);
/* doswapweapon might fail */
if (uswapwep == obj)
return FALSE;
}
else if (u.twoweap && uswapwep2 == obj) /* two-weaponing is needed for swapping, as otherwise the tool wouldn't be ready for use after the function call */
{
(void)dosingleswapweapon(W_SWAPWEP2, selected_hand_is_right ? W_WEP : W_WEP2);
/* doswapweapon might fail */
if (uswapwep2 == obj)
return FALSE;
}
else
{
int64_t wepslot = selected_hand_is_right ? W_WEP : W_WEP2;
int64_t swapwepslot = selected_hand_is_right ? W_SWAPWEP : W_SWAPWEP2;
/* if not two-weaponing, unwield first if the obj is uarms or swapweapon2, so that it can be wielded normally */
if (!u.twoweap && uarms == obj)
setuwep((struct obj*)0, W_WEP2);
else if (uswapwep2 == obj)
setuswapwep((struct obj*)0, W_SWAPWEP2);
struct obj *oldwep = selected_hand_is_right ? uwep: uarms;
if(!oldwep)
obj->speflags |= SPEFLAGS_NO_PREVIOUS_WEAPON;
if (will_weld(obj, &youmonst))
{
/* hope none of ready_weapon()'s early returns apply here... */
(void) ready_weapon(obj, wepslot);
}
else
{
char handbuf[BUFSZ];
Strcpy(handbuf, "");
if(u.twoweap)
Sprintf(handbuf, " in your %s %s", selected_hand_is_right ? "right" : "left", body_part(HAND));
You_ex(ATR_NONE, CLR_MSG_ATTENTION, "now wield %s%s.", doname(obj), handbuf);
setuwep(obj, wepslot);
}
/* refresh wep */
wep = selected_hand_is_right ? uwep : uarms;
boolean setprevwepflag = FALSE;
if (oldwep && wep != oldwep)
{
if (flags.pushweapon)
setuswapwep(oldwep, swapwepslot);
else
{
setprevwepflag = TRUE;
}
}
struct obj* otmp;
for (otmp = invent; otmp; otmp = otmp->nobj)
otmp->speflags &= ~SPEFLAGS_PREVIOUSLY_WIELDED;
if(setprevwepflag && oldwep)
oldwep->speflags |= SPEFLAGS_PREVIOUSLY_WIELDED;
context.botl = context.botlx = TRUE;
status_reassess();
}
/* refresh wep */
wep = selected_hand_is_right ? uwep : uarms;
if (wep != obj)
return FALSE; /* rewielded old object after dying */
return TRUE;
}
void
drop_uswapwep()
{
char str[BUFSZ];
struct obj *obj = uswapwep;
/* Avoid trashing makeplural's static buffer */
Strcpy(str, makeplural(body_part(HAND)));
pline("%s from your %s!", Yobjnam2(obj, "slip"), str);
dropxf(obj);
}
int
dotwoweapon()
{
/* You can always toggle it off */
if (u.twoweap)
{
play_ui_sound(UI_SOUND_STOP_TWO_WEAPON_COMBAT);
You("stop two weapon fighting.");
u.twoweap = 0;
}
else
{
if (P_SKILL_LEVEL(P_DUAL_WEAPON_COMBAT) == P_ISRESTRICTED)
{
play_sfx_sound(SFX_GENERAL_CANNOT);
You_ex(ATR_NONE, CLR_MSG_FAIL, "do not have the dual wielding skill.");
return 0;
}
play_ui_sound(UI_SOUND_START_TWO_WEAPON_COMBAT);
You("begin two weapon fighting.");
u.twoweap = 1;
}
update_hand_unweapon(2);
context.botl = context.botlx = TRUE;
newsym(u.ux, u.uy);
flush_screen(1);
update_inventory();
status_reassess();
return 0;
}
/*** Functions to empty a given slot ***/
/* These should be used only when the item can't be put back in
* the slot by life saving. Proper usage includes:
* 1. The item has been eaten, stolen, burned away, or rotted away.
* 2. Making an item disappear for a bones pile.
*/
void
uwepgone()
{
if (uwep) {
if ((artifact_light(uwep) || has_obj_mythic_magical_light(uwep) || obj_shines_magical_light(uwep)) && uwep->lamplit) {
Strcpy(debug_buf_3, "uwepgone");
end_burn(uwep, FALSE);
if (!Blind)
pline_ex(ATR_NONE, CLR_MSG_ATTENTION, "%s shining.", Tobjnam(uwep, "stop"));
}
setworn((struct obj *) 0, W_WEP);
update_unweapon();
update_inventory();
//status_reassess();
}
}
void
uwep2gone()
{
if (uarms) {
if ((artifact_light(uarms) || has_obj_mythic_magical_light(uarms) || obj_shines_magical_light(uarms)) && uarms->lamplit) {
Strcpy(debug_buf_3, "uwep2gone");
end_burn(uarms, FALSE);
if (!Blind)
pline_ex(ATR_NONE, CLR_MSG_ATTENTION, "%s shining.", Tobjnam(uarms, "stop"));
}
setworn((struct obj*) 0, W_ARMS);
update_unweapon();
update_inventory();
status_reassess();
}
}
void
uswapwepgone()
{
if (uswapwep) {
setworn((struct obj *) 0, W_SWAPWEP);
update_inventory();
}
}
void
uswapwep2gone()
{
if (uswapwep2) {
setworn((struct obj*) 0, W_SWAPWEP2);
update_inventory();
}
}
void
uqwepgone()
{
if (uquiver) {
setworn((struct obj *) 0, W_QUIVER);
update_inventory();
status_reassess();
}
}
void
untwoweapon()
{
if (u.twoweap) {
play_ui_sound(UI_SOUND_STOP_TWO_WEAPON_COMBAT);
You("can no longer use two weapons at once.");
u.twoweap = FALSE;
update_inventory();
}
return;
}
int
enchant_weapon(otmp, weapon, amount, dopopup)
register struct obj *otmp;
register struct obj* weapon;
register int amount;
boolean dopopup;
{
const char *color = (amount < 0) ? NH_BLACK : NH_BLUE;
const char *xtime, *wepname = "";
boolean multiple;
int otyp = STRANGE_OBJECT;
char buf[BUFSZ] = "";
boolean enchwepknown = FALSE;
if (otmp && (otmp->oclass == SPBOOK_CLASS || objects[otmp->otyp].oc_name_known))
enchwepknown = TRUE;
if (!weapon || !((is_weapon(weapon) || is_ammo(weapon)) && objects[weapon->otyp].oc_enchantable))
{
if (amount >= 0 && weapon && will_weld(weapon, &youmonst))
{ /* cursed tin opener */
play_sfx_sound(SFX_ENCHANT_ITEM_UNCURSE_AND_OTHER);
if (!Blind)
{
Strcpy(buf, "");
const char* hclr = hcolor_multi_buf2(NH_AMBER);
pline_multi_ex_popup(ATR_NONE, Hallucination ? CLR_MSG_HALLUCINATED : CLR_MSG_POSITIVE, no_multiattrs, multicolor_buffer, "Strange Feeling", dopopup,
"%s with %s%s aura.",
Yobjnam2(weapon, "glow"), an_prefix(hclr), hclr);
weapon->bknown = !Hallucination;
}
else
{
/* cursed tin opener is wielded in right hand */
Sprintf(buf, "Your right %s tingles.", body_part(HAND));
}
uncurse(weapon);
update_inventory();
}
else
{
play_sfx_sound(SFX_HANDS_ITCH);
Sprintf(buf, "Your %s %s.", makeplural(body_part(HAND)),
(amount >= 0) ? "twitch" : "itch");
}
strange_feeling(otmp, buf, dopopup); /* pline()+docall()+useup() */
exercise(A_DEX, (boolean) (amount >= 0));
return 0;
}
if (otmp && otmp->oclass == SCROLL_CLASS)
otyp = otmp->otyp;
if (weapon->otyp == WORM_TOOTH && amount >= 0)
{
if (otyp != STRANGE_OBJECT)
{
makeknown(otyp);
enchwepknown = TRUE;
}
play_sfx_sound(SFX_ENCHANT_ITEM_SPECIAL_SUCCESS);
multiple = (weapon->quan > 1L);
/* order: message, transformation, shop handling */
Sprintf(buf, "%s %s much sharper now.", simpleonames(weapon),
multiple ? "fuse, and become" : "is");
pline_ex1_popup(ATR_NONE, CLR_MSG_POSITIVE, buf, enchwepknown ? "Enchant Weapon" : "Sharpening Magic", dopopup);
weapon->otyp = CRYSKNIFE;
weapon->material = objects[weapon->otyp].oc_material;
weapon->oerodeproof = 0;
if (multiple)
{
weapon->quan = 1L;
weapon->owt = weight(weapon);
}
if (weapon->cursed)
uncurse(weapon);
/* update shop bill to reflect new higher value */
if (weapon->unpaid)
alter_cost(weapon, 0L);
if (multiple)
encumber_msg();
update_inventory();
return 1;
}
else if (weapon->otyp == CRYSKNIFE && amount < 0)
{
if (otyp != STRANGE_OBJECT && otmp && otmp->bknown)
{
makeknown(otyp);
enchwepknown = TRUE;
}
multiple = (weapon->quan > 1L);
play_sfx_sound(SFX_ENCHANT_ITEM_SPECIAL_NEGATIVE);
/* order matters: message, shop handling, transformation */
Sprintf(buf, "Your %s %s much duller now.", simpleonames(weapon), multiple ? "fuse, and become" : "is");
pline_ex1_popup(ATR_NONE, CLR_MSG_NEGATIVE, buf, enchwepknown ? "Enchant Weapon" : "Dulling Magic", dopopup);
costly_alteration(weapon, COST_DEGRD); /* DECHNT? other? */
weapon->otyp = WORM_TOOTH;
weapon->material = objects[weapon->otyp].oc_material;
weapon->oerodeproof = 0;
if (multiple)
{
weapon->quan = 1L;
weapon->owt = weight(weapon);
}
if (multiple)
encumber_msg();
update_inventory();
return 1;
}
if (has_oname(weapon))
wepname = ONAME(weapon);
if (amount < 0 && weapon->oartifact && restrict_name(weapon, wepname))
{
play_sfx_sound(SFX_ENCHANT_ITEM_GENERAL_FAIL);
if (!Blind)
{
pline_multi_ex_popup(ATR_NONE, CLR_MSG_ATTENTION, no_multiattrs, multicolor_buffer, enchwepknown ? "Enchant Weapon" : "Faint Glow", dopopup,
"%s %s.", Yobjnam2(weapon, "faintly glow"), hcolor_multi_buf1(color));
}
return 1;
}
int max_ench = get_obj_max_enchantment(weapon);
/* there is a (soft) upper and lower limit to weapon->enchantment */
if (((weapon->enchantment > max_ench && amount >= 0) || (weapon->enchantment < -max_ench && amount < 0)) && rn2(3))
{
if (((weapon->speflags & SPEFLAGS_GIVEN_OUT_BLUE_SMOKE) == 0 || rn2(3)) && (weapon->material == MAT_ORICHALCUM || obj_resists(weapon, 0, 75)))
{
play_special_effect_at(SPECIAL_EFFECT_PUFF_OF_SMOKE, u.ux, u.uy, 0, FALSE);
play_sfx_sound(SFX_VANISHES_IN_PUFF_OF_SMOKE);
special_effect_wait_until_action(0);
if (!Blind)
{
const char* icolor = hcolor_multi_buf1(color);
const char* bluecolor = hcolor_multi(NH_BLUE, multicolor_buffer, 3);
pline_multi_ex_popup(ATR_NONE, CLR_MSG_NEGATIVE, no_multiattrs, multicolor_buffer, Blind ? "Puff of Smoke" : "Puff of Blue Smoke", dopopup,
"%s %s for a while, and then suddenly %s out a puff of %s smoke.",
Yobjnam2(weapon, "violently glow"), icolor, otense(weapon, "give"), bluecolor);
}
else
{
Sprintf(buf, "%s for a while, and then suddenly %s out a puff of smoke.", Yobjnam2(weapon, "violently vibrate"), otense(weapon, "give"));
pline_ex1_popup(ATR_NONE, CLR_MSG_NEGATIVE, buf, Blind ? "Puff of Smoke" : "Puff of Blue Smoke", dopopup);
}
weapon->enchantment = 0;
weapon->speflags |= SPEFLAGS_GIVEN_OUT_BLUE_SMOKE;
update_inventory();
special_effect_wait_until_end(0);
}
else
{
play_sfx_sound(SFX_ENCHANT_ITEM_VIBRATE_AND_DESTROY);
if (!Blind)
{
pline_multi_ex_popup(ATR_NONE, CLR_MSG_NEGATIVE, no_multiattrs, multicolor_buffer, "Evaporation", dopopup,
"%s %s for a while and then %s.", Yobjnam2(weapon, "violently glow"), hcolor_multi_buf1(color), otense(weapon, "evaporate"));
}
else
{
Sprintf(buf, "%s.", Yobjnam2(weapon, "evaporate"));
pline_ex1_popup(ATR_NONE, CLR_MSG_NEGATIVE, buf, "Evaporation", dopopup);
}
Sprintf(priority_debug_buf_3, "enchant_weapon: %d", weapon->otyp);
useupall(weapon); /* let all of them disappear */
}
return 1;
}
if (amount == 0)
play_sfx_sound(SFX_ENCHANT_ITEM_VIOLENT_GLOW);
else
play_sfx_sound(amount > 1 ? SFX_ENCHANT_ITEM_BLESSED_SUCCESS : amount < 0 ? SFX_ENCHANT_ITEM_NEGATIVE : SFX_ENCHANT_ITEM_SUCCESS);
if (!Blind)
{
if (otyp != STRANGE_OBJECT && weapon->known && (amount > 0 || (amount < 0 && otmp && otmp->bknown)))
{
makeknown(otyp);
enchwepknown = TRUE;
}
xtime = (amount * amount == 1) ? "moment" : "while";
pline_multi_ex_popup(ATR_NONE, Hallucination ? CLR_MSG_HALLUCINATED : amount == 0 ? CLR_MSG_WARNING : amount > 0 ? CLR_MSG_POSITIVE : CLR_MSG_NEGATIVE, no_multiattrs, multicolor_buffer,
enchwepknown ? "Enchant Weapon" : amount == 0 ? "Violent Glow" : "Magical Glow", dopopup,
"%s %s for a %s.", Yobjnam2(weapon, amount == 0 ? "violently glow" : "glow"), hcolor_multi_buf1(color), xtime);
}
if (amount < 0)
costly_alteration(weapon, COST_DECHNT);
weapon->enchantment += amount;
if (amount > 0)
{
if (weapon->cursed)
uncurse(weapon);
/* update shop bill to reflect new higher price */
if (weapon->unpaid)
alter_cost(weapon, 0L);
}
/*
* Enchantment, which normally improves a weapon, has an
* addition adverse reaction on Magicbane whose effects are
* enchantment dependent. Give an obscure clue here.
*/
if (weapon->oartifact && artifact_has_flag(weapon, AF_MAGIC_ABSORBING) && weapon->enchantment >= 0)
{
play_sfx_sound(SFX_HANDS_ITCH);
Sprintf(buf, "Your right %s %sches!", body_part(HAND),
(((amount > 1) && (weapon->enchantment > 1)) ? "flin" : "it"));
pline_ex1_popup(ATR_NONE, CLR_MSG_ATTENTION, buf, ((amount > 1) && (weapon->enchantment > 1)) ? "Flinching Sensation" : "Itching Sensation", dopopup);
}
/* an elven magic clue, cookie@keebler */
/* elven weapons vibrate warningly when enchanted beyond a limit */
if ((weapon->enchantment > max_ench)
/*&& (is_elven_weapon(weapon) || weapon->oartifact || !rn2(7)) */ ) /* Vibrates for sure */
{
play_sfx_sound(SFX_ENCHANT_ITEM_VIBRATE_WARNING);
Sprintf(buf, "%s unexpectedly.", Yobjnam2(weapon, "suddenly vibrate"));
pline_ex1_popup(ATR_NONE, CLR_MSG_WARNING, buf, "Unexpected Vibration", dopopup);
}
update_inventory();
return 1;
}
int
welded(obj, mon)
register struct obj *obj;
register struct monst* mon;
{
if (obj && mon && (obj == uwep || obj == uarms) && will_weld(obj, mon))
{
if (!obj->bknown)
{
obj->bknown = TRUE;
if (obj->where == OBJ_INVENT)
update_inventory();
}
return 1;
}
return 0;
}
void
weldmsg(obj)
register struct obj *obj;
{
int64_t savewornmask;
savewornmask = obj->owornmask;
play_sfx_sound(SFX_GENERAL_WELDED);
pline_ex(ATR_NONE, CLR_MSG_NEGATIVE, "%s welded to your %s%s!", Yobjnam2(obj, "are"), bimanual(obj) ? "" : savewornmask & W_WEP ? "right " : "left ",
bimanual(obj) ? (const char *) makeplural(body_part(HAND))
: body_part(HAND));
obj->owornmask = savewornmask;
}
/* test whether monster's wielded weapon is stuck to hand/paw/whatever */
boolean
mwelded(obj, mon)
struct obj *obj;
struct monst* mon;
{
/* caller is responsible for making sure this is a monster's item */
if (obj && mon && (obj->owornmask & W_WEP) && will_weld(obj, mon)) /* cursed objects won't weld for demons and undead */
return TRUE;
return FALSE;
}
/*wield.c*/
| 412 | 0.979727 | 1 | 0.979727 | game-dev | MEDIA | 0.981716 | game-dev | 0.980979 | 1 | 0.980979 |
WayofTime/BloodMagic | 4,163 | src/main/java/wayoftime/bloodmagic/entity/projectile/EntityMeteor.java | package wayoftime.bloodmagic.entity.projectile;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.game.ClientGamePacketListener;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.projectile.ThrowableProjectile;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.network.NetworkHooks;
import wayoftime.bloodmagic.common.registries.BloodMagicEntityTypes;
import wayoftime.bloodmagic.impl.BloodMagicAPI;
import wayoftime.bloodmagic.recipe.RecipeMeteor;
import wayoftime.bloodmagic.util.Constants;
public class EntityMeteor extends ThrowableProjectile
{
private ItemStack containedStack = ItemStack.EMPTY;
public EntityMeteor(EntityType<EntityMeteor> p_i50159_1_, Level p_i50159_2_)
{
super(p_i50159_1_, p_i50159_2_);
}
public EntityMeteor(Level worldIn, LivingEntity throwerIn)
{
super(BloodMagicEntityTypes.METEOR.getEntityType(), throwerIn, worldIn);
}
public EntityMeteor(Level worldIn, double x, double y, double z)
{
super(BloodMagicEntityTypes.METEOR.getEntityType(), x, y, z, worldIn);
}
public void setContainedStack(ItemStack stack)
{
this.containedStack = stack;
}
@Override
public Packet<ClientGamePacketListener> getAddEntityPacket()
{
return NetworkHooks.getEntitySpawningPacket(this);
}
@Override
protected void addAdditionalSaveData(CompoundTag compound)
{
compound.put(Constants.NBT.ITEM, containedStack.save(new CompoundTag()));
// compound.putInt("Time", this.fallTime);
// compound.putBoolean("DropItem", this.shouldDropItem);
// compound.putBoolean("HurtEntities", this.hurtEntities);
// compound.putFloat("FallHurtAmount", this.fallHurtAmount);
// compound.putInt("FallHurtMax", this.fallHurtMax);
// if (this.tileEntityData != null) {
// compound.put("TileEntityData", this.tileEntityData);
// }
}
/**
* (abstract) Protected helper method to read subclass entity data from NBT.
*/
@Override
protected void readAdditionalSaveData(CompoundTag tagCompound)
{
CompoundTag tag = tagCompound.getCompound(Constants.NBT.ITEM);
containedStack = ItemStack.of(tag);
}
@Override
public void tick()
{
super.tick();
// TODO: Check doBlockCollision
// RayTraceResult raytraceresult = ProjectileHelper.getHitResult(this, this::canHitEntity);
//// boolean flag = false;
// if (raytraceresult.getType() == RayTraceResult.Type.BLOCK)
// {
// BlockPos blockpos = ((BlockRayTraceResult) raytraceresult).getPos().offset(((BlockRayTraceResult) raytraceresult).getFace());
// BlockState blockstate = this.world.getBlockState(blockpos);
// Material material = blockstate.getMaterial();
// if (blockstate.isAir() || blockstate.isIn(BlockTags.FIRE) || material.isLiquid() || material.isReplaceable())
// {
// this.getEntityWorld().setBlockState(blockpos, BloodMagicBlocks.BLOOD_LIGHT.get().getDefaultState());
// this.setDead();
// }
// }
}
protected void onInsideBlock(BlockState state)
{
if (level().isClientSide)
{
return;
}
// System.out.println("Now inside a block: " + state.getBlock());
int i = Mth.floor(position().x);
int j = Mth.floor(position().y);
int k = Mth.floor(position().z);
BlockPos blockpos = new BlockPos(i, j, k);
if (!state.canOcclude())
{
return;
}
// System.out.println("Contained item: " + containedStack.toString());
RecipeMeteor recipe = BloodMagicAPI.INSTANCE.getRecipeRegistrar().getMeteor(level(), containedStack);
if (recipe != null)
{
recipe.spawnMeteorInWorld(level(), blockpos);
}
// this.getEntityWorld().setBlockState(blockpos, BloodMagicBlocks.AIR_RITUAL_STONE.get().getDefaultState());
// spawnMeteorInWorld
this.removeAfterChangingDimensions();
}
// protected float getGravityVelocity()
// {
// return 0;
// }
@Override
protected void defineSynchedData()
{
// TODO Auto-generated method stub
}
} | 412 | 0.916561 | 1 | 0.916561 | game-dev | MEDIA | 0.997061 | game-dev | 0.978041 | 1 | 0.978041 |
Legacy-Fabric/fabric | 2,122 | legacy-fabric-resource-loader-v1/1.8.9/src/main/java/net/legacyfabric/fabric/mixin/resource/loader/client/ItemRendererMixin.java | /*
* Copyright (c) 2020 - 2025 Legacy Fabric
* Copyright (c) 2016 - 2022 FabricMC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.legacyfabric.fabric.mixin.resource.loader.client;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import net.minecraft.block.Block;
import net.minecraft.client.render.item.ItemRenderer;
import net.minecraft.item.Item;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.legacyfabric.fabric.impl.resource.loader.ItemModelRegistryImpl;
@Environment(EnvType.CLIENT)
@Mixin(ItemRenderer.class)
public abstract class ItemRendererMixin implements ItemModelRegistryImpl.Registrar {
@Shadow
protected abstract void addModel(Item item, int metadata, String id);
@Shadow
protected abstract void addModel(Item item, String id);
@Shadow
protected abstract void addModel(Block block, String id);
@Shadow
protected abstract void addModel(Block block, int metadata, String id);
@Override
public void fabric_register() {
ItemModelRegistryImpl.ITEMS_WITHOUT_META.forEach(pair -> {
this.addModel(pair.getObject(), pair.getModel().toString());
});
ItemModelRegistryImpl.BLOCKS_WITHOUT_META.forEach(pair -> {
this.addModel(pair.getObject(), pair.getModel().toString());
});
ItemModelRegistryImpl.ITEMS_WITH_META.forEach(triad -> {
this.addModel(triad.getObject(), triad.getMetadata(), triad.getModel().toString());
});
ItemModelRegistryImpl.BLOCKS_WITH_META.forEach(triad -> {
this.addModel(triad.getObject(), triad.getMetadata(), triad.getModel().toString());
});
}
}
| 412 | 0.856097 | 1 | 0.856097 | game-dev | MEDIA | 0.975446 | game-dev | 0.909455 | 1 | 0.909455 |
OpenDungeons/OpenDungeons | 1,670 | source/creatureaction/CreatureActionGrabEntity.h | /*
* Copyright (C) 2011-2016 OpenDungeons Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 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/>.
*/
#ifndef CREATUREACTIONGRABENTITY_H
#define CREATUREACTIONGRABENTITY_H
#include "creatureaction/CreatureAction.h"
#include "entities/GameEntity.h"
class GameEntity;
class CreatureActionGrabEntity : public CreatureAction, public GameEntityListener
{
public:
CreatureActionGrabEntity(Creature& creature, GameEntity& entityToCarry);
virtual ~CreatureActionGrabEntity();
CreatureActionType getType() const override
{ return CreatureActionType::grabEntity; }
std::function<bool()> action() override;
std::string getListenerName() const override;
bool notifyDead(GameEntity* entity) override;
bool notifyRemovedFromGameMap(GameEntity* entity) override;
bool notifyPickedUp(GameEntity* entity) override;
bool notifyDropped(GameEntity* entity) override;
static bool handleGrabEntity(Creature& creature, GameEntity* entityToCarry);
private:
GameEntity* mEntityToCarry;
};
#endif // CREATUREACTIONGRABENTITY_H
| 412 | 0.749163 | 1 | 0.749163 | game-dev | MEDIA | 0.974402 | game-dev | 0.608034 | 1 | 0.608034 |
neverlosecc/source2sdk | 2,747 | sdk/include/source2sdk/particles/C_INIT_PositionWarp.hpp | #pragma once
#include "source2sdk/source2gen/source2gen.hpp"
#include <cstddef>
#include <cstdint>
#include "source2sdk/particles/CParticleFunctionInitializer.hpp"
#include "source2sdk/particleslib/CParticleCollectionVecInput.hpp"
// /////////////////////////////////////////////////////////////
// Module: particles
// Created using source2gen - github.com/neverlosecc/source2gen
// /////////////////////////////////////////////////////////////
namespace source2sdk
{
namespace particles
{
// Registered alignment: 0x8
// Alignment: 0x8
// Standard-layout class: false
// Size: 0xed8
// Has VTable
//
// static metadata: MGetKV3ClassDefaults
#pragma pack(push, 1)
class C_INIT_PositionWarp : public source2sdk::particles::CParticleFunctionInitializer
{
public:
// metadata: MPropertyFriendlyName "warp min"
// metadata: MVectorIsCoordinate
source2sdk::particleslib::CParticleCollectionVecInput m_vecWarpMin; // 0x1c8
// metadata: MPropertyFriendlyName "warp max"
// metadata: MVectorIsCoordinate
source2sdk::particleslib::CParticleCollectionVecInput m_vecWarpMax; // 0x840
// metadata: MPropertyFriendlyName "warp scale control point number"
std::int32_t m_nScaleControlPointNumber; // 0xeb8
// metadata: MPropertyFriendlyName "control point number"
std::int32_t m_nControlPointNumber; // 0xebc
// metadata: MPropertyFriendlyName "radius scale component"
// metadata: MPropertyAttributeChoiceName "vector_component"
std::int32_t m_nRadiusComponent; // 0xec0
// metadata: MPropertyFriendlyName "warp transition time (treats min/max as start/end sizes)"
float m_flWarpTime; // 0xec4
// metadata: MPropertyFriendlyName "warp transition start time"
float m_flWarpStartTime; // 0xec8
// metadata: MPropertyFriendlyName "previous position sacale"
float m_flPrevPosScale; // 0xecc
// metadata: MPropertyFriendlyName "reverse warp (0/1)"
bool m_bInvertWarp; // 0xed0
// metadata: MPropertyFriendlyName "use particle count instead of time"
bool m_bUseCount; // 0xed1
uint8_t _pad0ed2[0x6];
};
#pragma pack(pop)
// Cannot assert offsets of fields in C_INIT_PositionWarp because it is not a standard-layout class
static_assert(sizeof(source2sdk::particles::C_INIT_PositionWarp) == 0xed8);
};
};
| 412 | 0.975523 | 1 | 0.975523 | game-dev | MEDIA | 0.358563 | game-dev | 0.510125 | 1 | 0.510125 |
ProjectIgnis/CardScripts | 3,032 | unofficial/c511000518.lua | --プリズム・ウォール
--Prism Wall
--fixed by Larry126
local s,id=GetID()
function s.initial_effect(c)
--change target
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_ATTACK_ANNOUNCE)
e1:SetCondition(s.condition1)
e1:SetTarget(s.target1)
e1:SetOperation(s.activate1)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,1))
e2:SetType(EFFECT_TYPE_ACTIVATE)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetCode(EVENT_CHAINING)
e2:SetCondition(s.condition2)
e2:SetTarget(s.target2)
e2:SetOperation(s.activate2)
c:RegisterEffect(e2)
end
function s.condition1(e,tp,eg,ep,ev,re,r,rp)
local at=Duel.GetAttacker()
local d=Duel.GetAttackTarget()
return d and d:IsControler(tp) and at:IsControler(1-tp)
end
function s.target1(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
local ag=eg:GetFirst():GetAttackableTarget()
if chkc then return ag:IsContains(chkc) and chkc:IsCanBeEffectTarget(e) end
local at=Duel.GetAttackTarget()
if chk==0 then return ag:IsExists(Card.IsCanBeEffectTarget,1,at,e) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET)
local g=ag:FilterSelect(tp,Card.IsCanBeEffectTarget,1,1,at,e)
Duel.SetTargetCard(g)
end
function s.activate1(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc and tc:IsRelateToEffect(e) and Duel.ChangeAttackTarget(tc) then
Duel.BreakEffect()
local dam=tc:GetAttack()
Duel.Damage(1-tp,dam,REASON_EFFECT,true)
Duel.Damage(tp,dam,REASON_EFFECT,true)
Duel.RDComplete()
end
end
function s.condition2(e,tp,eg,ep,ev,re,r,rp)
local rc=re:GetHandler()
if not re:IsActiveType(TYPE_MONSTER) or not re:IsHasProperty(EFFECT_FLAG_CARD_TARGET) or not rc:IsControler(1-tp) then return false end
local g=Duel.GetChainInfo(ev,CHAININFO_TARGET_CARDS)
if not g or #g~=1 then return false end
local tc=g:GetFirst()
e:SetLabelObject(tc)
return tc:IsControler(tp) and tc:IsLocation(LOCATION_MZONE)
end
function s.filter2(c,re,rp,tf,ceg,cep,cev,cre,cr,crp)
return tf(re,rp,ceg,cep,cev,cre,cr,crp,0,c)
end
function s.target2(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
local tf=re:GetTarget()
local res,ceg,cep,cev,cre,cr,crp=Duel.CheckEvent(re:GetCode(),true)
if chkc then return chkc~=e:GetLabelObject() and chkc:IsLocation(LOCATION_MZONE)
and chkc:IsControler(tp) and tf(re,rp,ceg,cep,cev,cre,cr,crp,0,chkc) end
if chk==0 then return Duel.IsExistingTarget(s.filter2,tp,LOCATION_MZONE,0,1,e:GetLabelObject(),re,rp,tf,ceg,cep,cev,cre,cr,crp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET)
Duel.SelectTarget(tp,s.filter2,tp,LOCATION_MZONE,0,1,1,e:GetLabelObject(),re,rp,tf,ceg,cep,cev,cre,cr,crp)
end
function s.activate2(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS)
if #g>0 and g:GetFirst():IsRelateToEffect(e) then
Duel.ChangeTargetCard(ev,g)
Duel.BreakEffect()
local dam=g:GetFirst():GetAttack()
Duel.Damage(1-tp,dam,REASON_EFFECT,true)
Duel.Damage(tp,dam,REASON_EFFECT,true)
Duel.RDComplete()
end
end | 412 | 0.964298 | 1 | 0.964298 | game-dev | MEDIA | 0.986045 | game-dev | 0.940998 | 1 | 0.940998 |
liweiwei1419/LeetCode-Solutions-in-Good-Style | 2,288 | 20-graph/Dijkstra 算法/0818-race-car/src/Solution4.java | import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
public class Solution4 {
// 方法三:暴力BFS
public int racecar(int target) {
State initState = new State(0, 1);
Queue<State> queue = new LinkedList<>();
queue.add(initState);
Set<State> visited = new HashSet<>(Math.max(target, 64));
visited.add(initState);
int count = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
State state = queue.poll();
State[] nextStates = state.move();
if (nextStates[0].getPosition() == target) {
return count + 1;
}
// 剪枝
if (nextStates[0].getPosition() < 0) {
continue;
}
// 去重
if (!visited.contains(nextStates[0])) {
queue.add(nextStates[0]);
visited.add(nextStates[0]);
}
if (!visited.contains(nextStates[1])) {
queue.add(nextStates[1]);
visited.add(nextStates[1]);
}
}
count += 1;
}
return -1;
}
private class State {
private int position;
private int speed;
public State(int position, int speed) {
this.position = position;
this.speed = speed;
}
public int getPosition() {
return position;
}
public State[] move() {
return new State[]{
new State(position + speed, speed * 2),
new State(position, speed > 0 ? -1 : 1),
};
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
State that = (State) o;
return position == that.position && speed == that.speed;
}
@Override
public int hashCode() {
return position + speed * speed * 500000;
}
}
} | 412 | 0.825635 | 1 | 0.825635 | game-dev | MEDIA | 0.165945 | game-dev | 0.887504 | 1 | 0.887504 |
libsdl-org/SDL | 5,215 | src/main/gdk/SDL_sysmain_runapp.cpp | /*
Simple DirectMedia Layer
Copyright (C) 1997-2025 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "SDL_internal.h"
extern "C" {
#include "../../core/gdk/SDL_gdk.h"
#include "../../core/windows/SDL_windows.h"
#include "../../events/SDL_events_c.h"
}
#include <XGameRuntime.h>
#include <xsapi-c/services_c.h>
#include <shellapi.h> // CommandLineToArgvW()
#include <appnotify.h>
// Pop up an out of memory message, returns to Windows
static BOOL OutOfMemory(void)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Fatal Error", "Out of memory - aborting", NULL);
return FALSE;
}
/* Gets the arguments with GetCommandLine, converts them to argc and argv
and calls SDL_main */
extern "C"
int SDL_RunApp(int, char **, SDL_main_func mainFunction, void *reserved)
{
LPWSTR *argvw;
char **argv;
int i, argc, result;
HRESULT hr;
XTaskQueueHandle taskQueue;
argvw = CommandLineToArgvW(GetCommandLineW(), &argc);
if (argvw == NULL) {
return OutOfMemory();
}
/* Note that we need to be careful about how we allocate/free memory here.
* If the application calls SDL_SetMemoryFunctions(), we can't rely on
* SDL_free() to use the same allocator after SDL_main() returns.
*/
// Parse it into argv and argc
argv = (char **)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (argc + 1) * sizeof(*argv));
if (argv == NULL) {
return OutOfMemory();
}
for (i = 0; i < argc; ++i) {
const int utf8size = WideCharToMultiByte(CP_UTF8, 0, argvw[i], -1, NULL, 0, NULL, NULL);
if (!utf8size) { // uhoh?
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Fatal Error", "Error processing command line arguments", NULL);
return -1;
}
argv[i] = (char *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, utf8size); // this size includes the null-terminator character.
if (!argv[i]) {
return OutOfMemory();
}
if (WideCharToMultiByte(CP_UTF8, 0, argvw[i], -1, argv[i], utf8size, NULL, NULL) == 0) { // failed? uhoh!
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Fatal Error", "Error processing command line arguments", NULL);
return -1;
}
}
argv[i] = NULL;
LocalFree(argvw);
hr = XGameRuntimeInitialize();
if (SUCCEEDED(hr) && SDL_GetGDKTaskQueue(&taskQueue)) {
Uint32 titleid = 0;
char scidBuffer[64];
XblInitArgs xblArgs;
XTaskQueueSetCurrentProcessTaskQueue(taskQueue);
// Try to get the title ID and initialize Xbox Live
hr = XGameGetXboxTitleId(&titleid);
if (SUCCEEDED(hr)) {
SDL_zero(xblArgs);
xblArgs.queue = taskQueue;
SDL_snprintf(scidBuffer, 64, "00000000-0000-0000-0000-0000%08X", titleid);
xblArgs.scid = scidBuffer;
hr = XblInitialize(&xblArgs);
} else {
SDL_SetError("[GDK] Unable to get titleid. Will not call XblInitialize. Check MicrosoftGame.config!");
}
SDL_SetMainReady();
if (!GDK_RegisterChangeNotifications()) {
return -1;
}
// Run the application main() code
result = mainFunction(argc, argv);
GDK_UnregisterChangeNotifications();
// !!! FIXME: This follows the docs exactly, but for some reason still leaks handles on exit?
// Terminate the task queue and dispatch any pending tasks
XTaskQueueTerminate(taskQueue, false, nullptr, nullptr);
while (XTaskQueueDispatch(taskQueue, XTaskQueuePort::Completion, 0))
;
XTaskQueueCloseHandle(taskQueue);
XGameRuntimeUninitialize();
} else {
#ifdef SDL_PLATFORM_WINGDK
if (hr == E_GAMERUNTIME_DLL_NOT_FOUND) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Fatal Error", "[GDK] Gaming Runtime library not found (xgameruntime.dll)", NULL);
} else {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Fatal Error", "[GDK] Could not initialize - aborting", NULL);
}
#else
SDL_assert_always(0 && "[GDK] Could not initialize - aborting");
#endif
result = -1;
}
// Free argv, to avoid memory leak
for (i = 0; i < argc; ++i) {
HeapFree(GetProcessHeap(), 0, argv[i]);
}
HeapFree(GetProcessHeap(), 0, argv);
return result;
}
| 412 | 0.859398 | 1 | 0.859398 | game-dev | MEDIA | 0.317664 | game-dev | 0.871157 | 1 | 0.871157 |
Pico-Developer/XR-Profiling-Toolkit | 2,786 | Packages/XRProfilingToolKit/Runtime/Scripts/Scene/SceneLoader.cs | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2024 PICO Developer
// SPDX-License-Identifier: MIT
// 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.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.SceneManagement;
namespace DeveloperTech.XRProfilingToolkit
{
/// <summary>
/// Singleton class that loads XR profiling scenes
/// </summary>
public class SceneLoader : MonoBehaviour
{
[SerializeField]
private List<string> sceneNames;
[SerializeField]
private string mainMenuSceneName;
private static SceneLoader _instance = null;
// Start is called before the first frame update
private void Start()
{
if (_instance == null)
{
_instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
/// <summary>
/// Loads XRProfilingToolkit scenes
/// <param name="index">Index of teh scene to load, 0 corresponds to the first scene</param>
/// </summary>
public static AsyncOperation OnSceneSelected(int index)
{
Assert.IsTrue(index >= 0 && index < _instance.sceneNames.Count);
return SceneManager.LoadSceneAsync(_instance.sceneNames[index], LoadSceneMode.Single);
}
public static AsyncOperation LoadMainMenu()
{
return SceneManager.LoadSceneAsync(_instance.mainMenuSceneName, LoadSceneMode.Single);
}
}
}
| 412 | 0.723246 | 1 | 0.723246 | game-dev | MEDIA | 0.908753 | game-dev | 0.777941 | 1 | 0.777941 |
gamekit-developers/gamekit | 7,359 | wxWidgets-2.9.1/src/generic/selstore.cpp | ///////////////////////////////////////////////////////////////////////////////
// Name: generic/selstore.cpp
// Purpose: wxSelectionStore implementation
// Author: Vadim Zeitlin
// Modified by:
// Created: 08.06.03 (extracted from src/generic/listctrl.cpp)
// RCS-ID: $Id$
// Copyright: (c) 2000-2003 Vadim Zeitlin <vadim@wxwindows.org>
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#include "wx/selstore.h"
// ============================================================================
// wxSelectionStore
// ============================================================================
// ----------------------------------------------------------------------------
// tests
// ----------------------------------------------------------------------------
bool wxSelectionStore::IsSelected(unsigned item) const
{
bool isSel = m_itemsSel.Index(item) != wxNOT_FOUND;
// if the default state is to be selected, being in m_itemsSel means that
// the item is not selected, so we have to inverse the logic
return m_defaultState ? !isSel : isSel;
}
// ----------------------------------------------------------------------------
// Select*()
// ----------------------------------------------------------------------------
bool wxSelectionStore::SelectItem(unsigned item, bool select)
{
// search for the item ourselves as like this we get the index where to
// insert it later if needed, so we do only one search in the array instead
// of two (adding item to a sorted array requires a search)
size_t index = m_itemsSel.IndexForInsert(item);
bool isSel = index < m_itemsSel.GetCount() && m_itemsSel[index] == item;
if ( select != m_defaultState )
{
if ( !isSel )
{
m_itemsSel.AddAt(item, index);
return true;
}
}
else // reset to default state
{
if ( isSel )
{
m_itemsSel.RemoveAt(index);
return true;
}
}
return false;
}
bool wxSelectionStore::SelectRange(unsigned itemFrom, unsigned itemTo,
bool select,
wxArrayInt *itemsChanged)
{
// 100 is hardcoded but it shouldn't matter much: the important thing is
// that we don't refresh everything when really few (e.g. 1 or 2) items
// change state
static const unsigned MANY_ITEMS = 100;
wxASSERT_MSG( itemFrom <= itemTo, wxT("should be in order") );
// are we going to have more [un]selected items than the other ones?
if ( itemTo - itemFrom > m_count/2 )
{
if ( select != m_defaultState )
{
// the default state now becomes the same as 'select'
m_defaultState = select;
// so all the old selections (which had state select) shouldn't be
// selected any more, but all the other ones should
wxSelectedIndices selOld = m_itemsSel;
m_itemsSel.Empty();
// TODO: it should be possible to optimize the searches a bit
// knowing the possible range
unsigned item;
for ( item = 0; item < itemFrom; item++ )
{
if ( selOld.Index(item) == wxNOT_FOUND )
m_itemsSel.Add(item);
}
for ( item = itemTo + 1; item < m_count; item++ )
{
if ( selOld.Index(item) == wxNOT_FOUND )
m_itemsSel.Add(item);
}
// many items (> half) changed state
itemsChanged = NULL;
}
else // select == m_defaultState
{
// get the inclusive range of items between itemFrom and itemTo
size_t count = m_itemsSel.GetCount(),
start = m_itemsSel.IndexForInsert(itemFrom),
end = m_itemsSel.IndexForInsert(itemTo);
if ( start == count || m_itemsSel[start] < itemFrom )
{
start++;
}
if ( end == count || m_itemsSel[end] > itemTo )
{
end--;
}
if ( start <= end )
{
// delete all of them (from end to avoid changing indices)
for ( int i = end; i >= (int)start; i-- )
{
if ( itemsChanged )
{
if ( itemsChanged->GetCount() > MANY_ITEMS )
{
// stop counting (see comment below)
itemsChanged = NULL;
}
else
{
itemsChanged->Add(m_itemsSel[i]);
}
}
m_itemsSel.RemoveAt(i);
}
}
}
}
else // "few" items change state
{
if ( itemsChanged )
{
itemsChanged->Empty();
}
// just add the items to the selection
for ( unsigned item = itemFrom; item <= itemTo; item++ )
{
if ( SelectItem(item, select) && itemsChanged )
{
itemsChanged->Add(item);
if ( itemsChanged->GetCount() > MANY_ITEMS )
{
// stop counting them, we'll just eat gobs of memory
// for nothing at all - faster to refresh everything in
// this case
itemsChanged = NULL;
}
}
}
}
// we set it to NULL if there are many items changing state
return itemsChanged != NULL;
}
// ----------------------------------------------------------------------------
// callbacks
// ----------------------------------------------------------------------------
void wxSelectionStore::OnItemDelete(unsigned item)
{
size_t count = m_itemsSel.GetCount(),
i = m_itemsSel.IndexForInsert(item);
if ( i < count && m_itemsSel[i] == item )
{
// this item itself was in m_itemsSel, remove it from there
m_itemsSel.RemoveAt(i);
count--;
}
// and adjust the index of all which follow it
while ( i < count )
{
// all following elements must be greater than the one we deleted
wxASSERT_MSG( m_itemsSel[i] > item, wxT("logic error") );
m_itemsSel[i++]--;
}
}
void wxSelectionStore::SetItemCount(unsigned count)
{
// forget about all items whose indices are now invalid if the size
// decreased
if ( count < m_count )
{
for ( size_t i = m_itemsSel.GetCount(); i > 0; i-- )
{
if ( m_itemsSel[i - 1] >= count )
m_itemsSel.RemoveAt(i - 1);
}
}
// remember the new number of items
m_count = count;
}
| 412 | 0.929561 | 1 | 0.929561 | game-dev | MEDIA | 0.559007 | game-dev,desktop-app | 0.998302 | 1 | 0.998302 |
FirstPersonKSP/AvionicsSystems | 1,064 | GameData/MOARdV/MAS_ASET/SwitchPUSH/MAS_swPush_AG2.cfg | PROP
{
name = MAS_swPush_AG2
MODEL
{
model = ASET/ASET_Props/Control/SwitchPUSH/SwitchPushButton
}
MODULE
{
name = MASComponent
COLLIDER_EVENT
{
name = Collider
collider = SwitchPUSHcollider
sound = ASET/ASET_Props/Sounds/buttonbeep
volume = 0.5
onClick = fc.ToggleActionGroup(2)
}
COLOR_SHIFT
{
name = Label Illumination
transform = SwitchNamePlate
variable = fc.Conditioned(fc.GetPersistentAsNumber("Backlight"))
passiveColor = 0,0,0,255
activeColor = COLOR_ASET_PUSHBUTTON_BACKLIGHT_ACTIVECOLOR
blend = true
}
COLOR_SHIFT
{
name = Border Illumination
transform = buttonBorder
passiveColor = 0,0,0,255
activeColor = COLOR_ASET_AG_PUSHBUTTON_ACTIVECOLOR
variable = fc.Conditioned(fc.GetActionGroup(2))
}
ANIMATION_PLAYER
{
name = Switch animation
animation = SwitchPUSHanim
animationSpeed = 1.0
variable = fc.GetActionGroup(2)
}
TEXTURE_SHIFT
{
name = Label
transform = SwitchNamePlate
layers = _MainTex _Emissive
startUV = 0.25, 0.25
}
}
}
| 412 | 0.820883 | 1 | 0.820883 | game-dev | MEDIA | 0.733516 | game-dev | 0.548079 | 1 | 0.548079 |
TauCetiStation/TauCetiClassic | 5,990 | code/game/objects/structures/rd_armor_stand.dm | /obj/structure/rd_armor_stand
name = "Experimental Armor Storage"
desc = "Storage of experimental teleportation armor."
icon = 'icons/obj/stationobjs.dmi'
icon_state = "telearmorstand"
anchored = TRUE
integrity_failure = 0.5
var/obj/item/clothing/suit/armor/vest/reactive/reactive
var/opened = FALSE
var/smashed = FALSE
var/lock = TRUE
/obj/structure/rd_armor_stand/atom_init(mapload)
. = ..()
reactive = new /obj/item/clothing/suit/armor/vest/reactive(src)
update_icon()
/obj/structure/rd_armor_stand/Destroy()
QDEL_NULL(reactive)
return ..()
/obj/structure/rd_armor_stand/attackby(obj/item/O, mob/living/user)
if (user.is_busy(src))
return
if (isrobot(usr) || lock)
if(ispulsing(O))
to_chat(user, "<span class='warning'>Resetting circuitry...</span>")
playsound(src, 'sound/machines/lockreset.ogg', VOL_EFFECTS_MASTER)
if (do_after(user, 100, target = src))
lock = FALSE
to_chat(user, "<span class='notice'>You disable the locking modules.</span>")
playsound(src, 'sound/machines/airlock/bolts_up_2.ogg', VOL_EFFECTS_MASTER)
return
if(istype(O, /obj/item/weapon/card/id))
var/obj/item/weapon/card/id/I = O
if(!(access_rd in I.access))
to_chat(user, "<span class='warning'>Access denied.</span>")
return
else
lock = FALSE
to_chat(user, "<span class='notice'>You disable the locking modules.</span>")
playsound(src, 'sound/machines/airlock/bolts_up_2.ogg', VOL_EFFECTS_MASTER)
return
else if (istype(O, /obj/item/clothing/suit/armor/vest/reactive) && opened)
if(!reactive)
user.drop_from_inventory(O, src)
reactive = O
to_chat(user, "<span class='notice'>You place the armor back in the [src.name].</span>")
update_icon()
else
if(smashed)
return
if(ispulsing(O))
if(opened)
opened = FALSE
to_chat(user, "<span class='notice'>You closed the [name].</span>")
update_icon()
else
to_chat(user, "<span class='warning'>Resetting circuitry...</span>")
if(O.use_tool(src, user, 100, volume = 50, quality = QUALITY_PULSING))
lock = TRUE
to_chat(user, "<span class='notice'>You re-enable the locking modules.</span>")
playsound(src, 'sound/machines/airlock/bolts_down_2.ogg', VOL_EFFECTS_MASTER)
return
if(istype(O, /obj/item/weapon/card/id))
var/obj/item/weapon/card/id/ID = O
if(!(access_rd in ID.access))
to_chat(user, "<span class='warning'>Access denied.</span>")
return
if(opened)
opened = FALSE
to_chat(user, "<span class='notice'>You closed the [name].</span>")
update_icon()
return
if((!opened) && (!lock))
lock = TRUE
to_chat(user, "<span class='notice'>You re-enable the locking modules.</span>")
playsound(src, 'sound/machines/airlock/bolts_down_2.ogg', VOL_EFFECTS_MASTER)
else
if(opened)
to_chat(user, "<span class='notice'>You closed the [name].</span>")
opened = FALSE
update_icon()
/obj/structure/rd_armor_stand/play_attack_sound(damage_amount, damage_type = BRUTE, damage_flag = 0)
switch(damage_type)
if(BRUTE)
if(smashed)
playsound(loc, 'sound/effects/hit_on_shattered_glass.ogg', VOL_EFFECTS_MASTER, 90, TRUE)
else
playsound(loc, 'sound/effects/Glasshit.ogg', VOL_EFFECTS_MASTER, 90, TRUE)
if(BURN)
playsound(loc, 'sound/items/Welder.ogg', VOL_EFFECTS_MASTER, 100, TRUE)
/obj/structure/rd_armor_stand/atom_break(damage_flag)
if(smashed || flags & NODECONSTRUCT)
return ..()
smashed = TRUE
opened = TRUE
lock = FALSE
update_icon()
playsound(loc, 'sound/effects/Glassbr3.ogg', VOL_EFFECTS_MASTER, 100, TRUE)
new /obj/item/weapon/shard(loc)
new /obj/item/weapon/shard(loc)
. = ..()
/obj/structure/rd_armor_stand/deconstruct(disassembled = TRUE)
if(flags & NODECONSTRUCT)
return ..()
if(reactive)
reactive.forceMove(loc)
reactive = null
new /obj/item/stack/sheet/metal(loc, 2)
if(!smashed)
new /obj/item/weapon/shard(loc)
new /obj/item/weapon/shard(loc)
return ..()
/obj/structure/rd_armor_stand/attack_hand(mob/living/user)
if(user.is_busy(src))
return
user.SetNextMove(CLICK_CD_MELEE)
if(lock)
to_chat(user, "<span class='warning'>The storage won't budge!</span>")
return
if((!opened) && (!smashed))
opened = TRUE
update_icon()
to_chat(user, "<span class='notice'>You opened the [name].</span>")
return
if((opened) || (smashed))
if(reactive)
user.try_take(reactive, loc)
reactive = null
to_chat(user, "<span class='notice'>You take the armor from the [name].</span>")
add_fingerprint(user)
update_icon()
return
if((opened) && (!smashed))
to_chat(user, "<span class='notice'>You closed the [name].</span>")
opened = FALSE
update_icon()
return
/obj/structure/rd_armor_stand/attack_paw(mob/user)
attack_hand(user)
/obj/structure/rd_armor_stand/attack_ai(mob/user)
if(smashed)
to_chat(user, "<span class='warning'>The security of the storage is compromised.</span>")
else
if(lock)
lock = TRUE
to_chat(user, "<span class='warning'>Storage locked.</span>")
playsound(src, 'sound/machines/airlock/bolts_down_2.ogg', VOL_EFFECTS_MASTER)
else
lock = FALSE
to_chat(user, "<span class='notice'>Storage unlocked.</span>")
playsound(src, 'sound/machines/airlock/bolts_up_2.ogg', VOL_EFFECTS_MASTER)
/obj/structure/rd_armor_stand/emag_act()
lock = FALSE
visible_message("<span class='warning'>[name] lock sparkles!</span>")
playsound(src, 'sound/machines/airlock/bolts_up_2.ogg', VOL_EFFECTS_MASTER)
return
/obj/structure/rd_armor_stand/update_icon()
cut_overlays()
if(reactive)
var/mutable_appearance/showpiece_overlay = mutable_appearance(reactive.icon, reactive.icon_state)
showpiece_overlay.copy_overlays(reactive)
showpiece_overlay.transform *= 0.75
add_overlay(showpiece_overlay)
if((!opened) && (!smashed))
add_overlay(image(icon = 'icons/obj/stationobjs.dmi', icon_state = "standglass_overlay"))
if(smashed)
add_overlay(image(icon = 'icons/obj/stationobjs.dmi', icon_state = "standglass_broken_overlay"))
| 412 | 0.963532 | 1 | 0.963532 | game-dev | MEDIA | 0.988257 | game-dev | 0.925616 | 1 | 0.925616 |
MATTYOneInc/AionEncomBase_Java8 | 3,350 | AL-Game/data/scripts/system/handlers/quest/silentera_canyon/_30155StonetoFlesh.java | package quest.silentera_canyon;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.network.aion.serverpackets.SM_DIALOG_WINDOW;
import com.aionemu.gameserver.questEngine.handlers.QuestHandler;
import com.aionemu.gameserver.questEngine.model.QuestDialog;
import com.aionemu.gameserver.questEngine.model.QuestEnv;
import com.aionemu.gameserver.questEngine.model.QuestState;
import com.aionemu.gameserver.questEngine.model.QuestStatus;
import com.aionemu.gameserver.services.QuestService;
import com.aionemu.gameserver.utils.PacketSendUtility;
/**
* @author Ritsu
*
*/
public class _30155StonetoFlesh extends QuestHandler {
private final static int questId = 30155;
public _30155StonetoFlesh() {
super(questId);
}
@Override
public void register() {
qe.registerQuestNpc(799234).addOnQuestStart(questId);
qe.registerQuestNpc(799234).addOnTalkEvent(questId);
qe.registerQuestNpc(204433).addOnTalkEvent(questId);
qe.registerQuestNpc(204304).addOnTalkEvent(questId);
}
@Override
public boolean onDialogEvent(QuestEnv env) {
Player player = env.getPlayer();
QuestState qs = player.getQuestStateList().getQuestState(questId);
QuestDialog dialog = env.getDialog();
int targetId = env.getTargetId();
if (qs == null || qs.getStatus() == QuestStatus.NONE) {
if (targetId == 799234) {
if (dialog == QuestDialog.START_DIALOG) {
return sendQuestDialog(env, 1011);
}
else
return sendQuestStartDialog(env);
}
}
else if (qs == null || qs.getStatus() == QuestStatus.REWARD) {
int var = qs.getQuestVarById(0);
if (targetId == 204304) {
if (var == 3)
return sendQuestEndDialog(env);
}
else if (targetId == 799234) {
switch (dialog) {
case SELECT_NO_REWARD:
if (var == 2) {
QuestService.finishQuest(env, qs.getQuestVars().getQuestVars()-2);
PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(env.getVisibleObject().getObjectId(), 10));
return true;
}
}
}
}
else if (qs.getStatus() == QuestStatus.START) {
int var = qs.getQuestVarById(0);
if (targetId == 799234) {
switch (dialog) {
case START_DIALOG:
if (var == 1)
return sendQuestDialog(env, 1693);
case STEP_TO_2:
if (var == 1) {
changeQuestStep(env, 1, 2, false);
return sendQuestDialog(env, 2375);
}
case SELECT_REWARD:
if (var == 2) {
removeQuestItem(env, 182209252, 1);
qs.setStatus(QuestStatus.REWARD);
updateQuestStatus(env);
return sendQuestDialog(env, 6);
}
}
}
else if (targetId == 204433) {
switch (dialog) {
case START_DIALOG:
if (var == 0)
return sendQuestDialog(env, 1352);
case STEP_TO_1:
if (var == 0)
return defaultCloseDialog(env, 0, 1, false, false, 182209252, 1, 0, 0);
}
}
else if (targetId == 204304) {
switch (dialog) {
case START_DIALOG:
if (var == 1)
return sendQuestDialog(env, 2034);
case STEP_TO_3:
if (var == 1)
changeQuestStep(env, 1, 3, false);
return sendQuestDialog(env, 2375);
case SELECT_REWARD:
if (var == 3) {
removeQuestItem(env, 182209252, 1);
qs.setStatus(QuestStatus.REWARD);
updateQuestStatus(env);
}
}
}
}
return false;
}
} | 412 | 0.8666 | 1 | 0.8666 | game-dev | MEDIA | 0.938856 | game-dev | 0.9513 | 1 | 0.9513 |
ForestDango/Hollow-Knight-Demo | 1,326 | Assets/PlayMaker/Actions/Editor/GetDistanceEditor.cs | using System.ComponentModel;
using UnityEditor;
using UnityEngine;
namespace HutongGames.PlayMakerEditor
{
[CustomActionEditor(typeof(HutongGames.PlayMaker.Actions.GetDistance))]
public class GetDistanceEditor : CustomActionEditor
{
public override bool OnGUI()
{
return DrawDefaultInspector();
}
[Localizable(false)]
public override void OnSceneGUI()
{
var action = target as HutongGames.PlayMaker.Actions.GetDistance;
if (action == null) // shouldn't happen!
{
return;
}
var fromObject = action.Fsm.GetOwnerDefaultTarget(action.gameObject);
var toObject = action.target;
if (fromObject == null || toObject.IsNone || toObject.Value == null)
{
return;
}
var fromPos = fromObject.transform.position;
var toPos = toObject.Value.transform.position;
var distance = Vector3.Distance(fromPos, toPos);
var label = string.Format("Get Distance:\n{0}", string.Format("{0:0.000}", distance));
Handles.color = new Color(1, 1, 1, 0.5f);
Handles.DrawLine(fromPos, toPos);
Handles.Label((fromPos + toPos)*0.5f, label);
}
}
}
| 412 | 0.892751 | 1 | 0.892751 | game-dev | MEDIA | 0.973482 | game-dev | 0.968189 | 1 | 0.968189 |
GameGrind/Simple-RPG-in-Unity | 2,411 | Assets/PostProcessing/Editor/PostProcessingModelEditor.cs | using UnityEngine;
using UnityEngine.PostProcessing;
using System;
using System.Linq.Expressions;
namespace UnityEditor.PostProcessing
{
public class PostProcessingModelEditor
{
public PostProcessingModel target { get; internal set; }
public SerializedProperty serializedProperty { get; internal set; }
protected SerializedProperty m_SettingsProperty;
protected SerializedProperty m_EnabledProperty;
internal bool alwaysEnabled = false;
internal PostProcessingProfile profile;
internal PostProcessingInspector inspector;
internal void OnPreEnable()
{
m_SettingsProperty = serializedProperty.FindPropertyRelative("m_Settings");
m_EnabledProperty = serializedProperty.FindPropertyRelative("m_Enabled");
OnEnable();
}
public virtual void OnEnable()
{}
public virtual void OnDisable()
{}
internal void OnGUI()
{
GUILayout.Space(5);
var display = alwaysEnabled
? EditorGUIHelper.Header(serializedProperty.displayName, m_SettingsProperty, Reset)
: EditorGUIHelper.Header(serializedProperty.displayName, m_SettingsProperty, m_EnabledProperty, Reset);
if (display)
{
EditorGUI.indentLevel++;
using (new EditorGUI.DisabledGroupScope(!m_EnabledProperty.boolValue))
{
OnInspectorGUI();
}
EditorGUI.indentLevel--;
}
}
void Reset()
{
var obj = serializedProperty.serializedObject;
Undo.RecordObject(obj.targetObject, "Reset");
target.Reset();
EditorUtility.SetDirty(obj.targetObject);
}
public virtual void OnInspectorGUI()
{}
public void Repaint()
{
inspector.Repaint();
}
protected SerializedProperty FindSetting<T, TValue>(Expression<Func<T, TValue>> expr)
{
return m_SettingsProperty.FindPropertyRelative(ReflectionUtils.GetFieldPath(expr));
}
protected SerializedProperty FindSetting<T, TValue>(SerializedProperty prop, Expression<Func<T, TValue>> expr)
{
return prop.FindPropertyRelative(ReflectionUtils.GetFieldPath(expr));
}
}
}
| 412 | 0.774187 | 1 | 0.774187 | game-dev | MEDIA | 0.939015 | game-dev | 0.764329 | 1 | 0.764329 |
nguillaumin/slick2d-maven | 2,304 | slick2d-core/src/main/java/org/newdawn/slick/state/transition/FadeInTransition.java | package org.newdawn.slick.state.transition;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.state.GameState;
import org.newdawn.slick.state.StateBasedGame;
/**
* A transition to fade in from a given colour
*
* @author kevin
*/
public class FadeInTransition implements Transition {
/** The color to fade to */
private Color color;
/** The time it takes to fade in */
private int fadeTime = 500;
/**
* Create a new fade in transition
*/
public FadeInTransition() {
this(Color.black, 500);
}
/**
* Create a new fade in transition
*
* @param color The color we're going to fade in from
*/
public FadeInTransition(Color color) {
this(color, 500);
}
/**
* Create a new fade in transition
*
* @param color The color we're going to fade in from
* @param fadeTime The time it takes for the fade to occur
*/
public FadeInTransition(Color color, int fadeTime) {
this.color = new Color(color);
this.color.a = 1;
this.fadeTime = fadeTime;
}
/**
* @see org.newdawn.slick.state.transition.Transition#isComplete()
*/
public boolean isComplete() {
return (color.a <= 0);
}
/**
* @see org.newdawn.slick.state.transition.Transition#postRender(org.newdawn.slick.state.StateBasedGame, org.newdawn.slick.GameContainer, org.newdawn.slick.Graphics)
*/
public void postRender(StateBasedGame game, GameContainer container, Graphics g) {
Color old = g.getColor();
g.setColor(color);
g.fillRect(0, 0, container.getWidth()*2, container.getHeight()*2);
g.setColor(old);
}
/**
* @see org.newdawn.slick.state.transition.Transition#update(org.newdawn.slick.state.StateBasedGame, org.newdawn.slick.GameContainer, int)
*/
public void update(StateBasedGame game, GameContainer container, int delta) {
color.a -= delta * (1.0f / fadeTime);
if (color.a < 0) {
color.a = 0;
}
}
/**
* @see org.newdawn.slick.state.transition.Transition#preRender(org.newdawn.slick.state.StateBasedGame, org.newdawn.slick.GameContainer, org.newdawn.slick.Graphics)
*/
public void preRender(StateBasedGame game, GameContainer container, Graphics g) {
}
public void init(GameState firstState, GameState secondState) {
// TODO Auto-generated method stub
}
}
| 412 | 0.775897 | 1 | 0.775897 | game-dev | MEDIA | 0.903831 | game-dev | 0.939714 | 1 | 0.939714 |
magefree/mage | 3,502 | Mage.Sets/src/mage/cards/e/EnduringRenewal.java | package mage.cards.e;
import mage.abilities.Ability;
import mage.abilities.common.PutIntoGraveFromBattlefieldAllTriggeredAbility;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.effects.ReplacementEffectImpl;
import mage.abilities.effects.common.ReturnFromGraveyardToHandTargetEffect;
import mage.abilities.effects.common.continuous.PlayWithHandRevealedEffect;
import mage.cards.*;
import mage.constants.*;
import mage.filter.StaticFilters;
import mage.game.Game;
import mage.game.events.GameEvent;
import mage.players.Player;
import java.util.UUID;
/**
* @author anonymous
*/
public final class EnduringRenewal extends CardImpl {
public EnduringRenewal(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{2}{W}{W}");
// Play with your hand revealed.
this.addAbility(new SimpleStaticAbility(new PlayWithHandRevealedEffect(TargetController.YOU)));
// If you would draw a card, reveal the top card of your library instead. If it's a creature card, put it into your graveyard. Otherwise, draw a card.
this.addAbility(new SimpleStaticAbility(new EnduringRenewalReplacementEffect()));
// Whenever a creature is put into your graveyard from the battlefield, return it to your hand.
this.addAbility(new PutIntoGraveFromBattlefieldAllTriggeredAbility(
new ReturnFromGraveyardToHandTargetEffect().setText("return it to your hand"),
false, StaticFilters.FILTER_PERMANENT_A_CREATURE, true, true
));
}
private EnduringRenewal(final EnduringRenewal card) {
super(card);
}
@Override
public EnduringRenewal copy() {
return new EnduringRenewal(this);
}
}
class EnduringRenewalReplacementEffect extends ReplacementEffectImpl {
EnduringRenewalReplacementEffect() {
super(Duration.WhileOnBattlefield, Outcome.Benefit);
staticText = "If you would draw a card, reveal the top card of your library instead. " +
"If it's a creature card, put it into your graveyard. Otherwise, draw a card";
}
private EnduringRenewalReplacementEffect(final EnduringRenewalReplacementEffect effect) {
super(effect);
}
@Override
public EnduringRenewalReplacementEffect copy() {
return new EnduringRenewalReplacementEffect(this);
}
@Override
public boolean replaceEvent(GameEvent event, Ability source, Game game) {
Player controller = game.getPlayer(source.getControllerId());
if (controller == null) {
return false;
}
Card card = controller.getLibrary().getFromTop(game);
if (card == null) {
return false;
}
Cards cards = new CardsImpl(card);
controller.revealCards("Top card of " + controller.getName() + "'s library", cards, game);
if (card.isCreature(game)) {
controller.moveCards(card, Zone.GRAVEYARD, source, game);
} else {
// This is still replacing the draw, so we still return true
controller.drawCards(1, source, game, event);
}
return true;
}
@Override
public boolean checksEventType(GameEvent event, Game game) {
return event.getType() == GameEvent.EventType.DRAW_CARD;
}
@Override
public boolean applies(GameEvent event, Ability source, Game game) {
return event.getPlayerId().equals(source.getControllerId());
}
}
| 412 | 0.991773 | 1 | 0.991773 | game-dev | MEDIA | 0.978486 | game-dev | 0.98695 | 1 | 0.98695 |
spajus/ruby-gamedev-book-examples | 1,423 | 07-damage/entities/components/bullet_physics.rb | class BulletPhysics < Component
START_DIST = 20
MAX_DIST = 300
def initialize(game_object, object_pool)
super(game_object)
@object_pool = object_pool
object.x, object.y = point_at_distance(START_DIST)
if trajectory_length > MAX_DIST
object.target_x, object.target_y = point_at_distance(MAX_DIST)
end
end
def update
fly_speed = Utils.adjust_speed(object.speed)
fly_distance = (Gosu.milliseconds - object.fired_at) * 0.001 * fly_speed
object.x, object.y = point_at_distance(fly_distance)
check_hit
object.explode if arrived?
end
def trajectory_length
Utils.distance_between(object.target_x, object.target_y, x, y)
end
def point_at_distance(distance)
if distance > trajectory_length
return [object.target_x, object.target_y]
end
distance_factor = distance.to_f / trajectory_length
p_x = x + (object.target_x - x) * distance_factor
p_y = y + (object.target_y - y) * distance_factor
[p_x, p_y]
end
private
def check_hit
@object_pool.nearby(object, 50).each do |obj|
next if obj == object.source # Don't hit source tank
if Utils.point_in_poly(x, y, *obj.box)
# Direct hit - extra damage
obj.health.inflict_damage(20)
object.target_x = x
object.target_y = y
return
end
end
end
def arrived?
x == object.target_x && y == object.target_y
end
end
| 412 | 0.722527 | 1 | 0.722527 | game-dev | MEDIA | 0.653715 | game-dev | 0.896679 | 1 | 0.896679 |
HuvaaKoodia/2DMetaballs | 28,518 | Assets/PostProcessing/Editor/Models/ColorGradingModelEditor.cs | using UnityEngine;
using UnityEngine.PostProcessing;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace UnityEditor.PostProcessing
{
using Settings = ColorGradingModel.Settings;
using Tonemapper = ColorGradingModel.Tonemapper;
using ColorWheelMode = ColorGradingModel.ColorWheelMode;
[PostProcessingModelEditor(typeof(ColorGradingModel))]
public class ColorGradingModelEditor : PostProcessingModelEditor
{
static GUIContent[] s_Tonemappers =
{
new GUIContent("None"),
new GUIContent("Filmic (ACES)"),
new GUIContent("Neutral")
};
struct TonemappingSettings
{
public SerializedProperty tonemapper;
public SerializedProperty neutralBlackIn;
public SerializedProperty neutralWhiteIn;
public SerializedProperty neutralBlackOut;
public SerializedProperty neutralWhiteOut;
public SerializedProperty neutralWhiteLevel;
public SerializedProperty neutralWhiteClip;
}
struct BasicSettings
{
public SerializedProperty exposure;
public SerializedProperty temperature;
public SerializedProperty tint;
public SerializedProperty hueShift;
public SerializedProperty saturation;
public SerializedProperty contrast;
}
struct ChannelMixerSettings
{
public SerializedProperty[] channels;
public SerializedProperty currentEditingChannel;
}
struct ColorWheelsSettings
{
public SerializedProperty mode;
public SerializedProperty log;
public SerializedProperty linear;
}
static GUIContent[] s_Curves =
{
new GUIContent("YRGB"),
new GUIContent("Hue VS Hue"),
new GUIContent("Hue VS Sat"),
new GUIContent("Sat VS Sat"),
new GUIContent("Lum VS Sat")
};
struct CurvesSettings
{
public SerializedProperty master;
public SerializedProperty red;
public SerializedProperty green;
public SerializedProperty blue;
public SerializedProperty hueVShue;
public SerializedProperty hueVSsat;
public SerializedProperty satVSsat;
public SerializedProperty lumVSsat;
public SerializedProperty currentEditingCurve;
public SerializedProperty curveY;
public SerializedProperty curveR;
public SerializedProperty curveG;
public SerializedProperty curveB;
}
TonemappingSettings m_Tonemapping;
BasicSettings m_Basic;
ChannelMixerSettings m_ChannelMixer;
ColorWheelsSettings m_ColorWheels;
CurvesSettings m_Curves;
CurveEditor m_CurveEditor;
Dictionary<SerializedProperty, Color> m_CurveDict;
// Neutral tonemapping curve helper
const int k_CurveResolution = 24;
const float k_NeutralRangeX = 2f;
const float k_NeutralRangeY = 1f;
Vector3[] m_RectVertices = new Vector3[4];
Vector3[] m_LineVertices = new Vector3[2];
Vector3[] m_CurveVertices = new Vector3[k_CurveResolution];
Rect m_NeutralCurveRect;
public override void OnEnable()
{
// Tonemapping settings
m_Tonemapping = new TonemappingSettings
{
tonemapper = FindSetting((Settings x) => x.tonemapping.tonemapper),
neutralBlackIn = FindSetting((Settings x) => x.tonemapping.neutralBlackIn),
neutralWhiteIn = FindSetting((Settings x) => x.tonemapping.neutralWhiteIn),
neutralBlackOut = FindSetting((Settings x) => x.tonemapping.neutralBlackOut),
neutralWhiteOut = FindSetting((Settings x) => x.tonemapping.neutralWhiteOut),
neutralWhiteLevel = FindSetting((Settings x) => x.tonemapping.neutralWhiteLevel),
neutralWhiteClip = FindSetting((Settings x) => x.tonemapping.neutralWhiteClip)
};
// Basic settings
m_Basic = new BasicSettings
{
exposure = FindSetting((Settings x) => x.basic.postExposure),
temperature = FindSetting((Settings x) => x.basic.temperature),
tint = FindSetting((Settings x) => x.basic.tint),
hueShift = FindSetting((Settings x) => x.basic.hueShift),
saturation = FindSetting((Settings x) => x.basic.saturation),
contrast = FindSetting((Settings x) => x.basic.contrast)
};
// Channel mixer
m_ChannelMixer = new ChannelMixerSettings
{
channels = new[]
{
FindSetting((Settings x) => x.channelMixer.red),
FindSetting((Settings x) => x.channelMixer.green),
FindSetting((Settings x) => x.channelMixer.blue)
},
currentEditingChannel = FindSetting((Settings x) => x.channelMixer.currentEditingChannel)
};
// Color wheels
m_ColorWheels = new ColorWheelsSettings
{
mode = FindSetting((Settings x) => x.colorWheels.mode),
log = FindSetting((Settings x) => x.colorWheels.log),
linear = FindSetting((Settings x) => x.colorWheels.linear)
};
// Curves
m_Curves = new CurvesSettings
{
master = FindSetting((Settings x) => x.curves.master.curve),
red = FindSetting((Settings x) => x.curves.red.curve),
green = FindSetting((Settings x) => x.curves.green.curve),
blue = FindSetting((Settings x) => x.curves.blue.curve),
hueVShue = FindSetting((Settings x) => x.curves.hueVShue.curve),
hueVSsat = FindSetting((Settings x) => x.curves.hueVSsat.curve),
satVSsat = FindSetting((Settings x) => x.curves.satVSsat.curve),
lumVSsat = FindSetting((Settings x) => x.curves.lumVSsat.curve),
currentEditingCurve = FindSetting((Settings x) => x.curves.e_CurrentEditingCurve),
curveY = FindSetting((Settings x) => x.curves.e_CurveY),
curveR = FindSetting((Settings x) => x.curves.e_CurveR),
curveG = FindSetting((Settings x) => x.curves.e_CurveG),
curveB = FindSetting((Settings x) => x.curves.e_CurveB)
};
// Prepare the curve editor and extract curve display settings
m_CurveDict = new Dictionary<SerializedProperty, Color>();
var settings = CurveEditor.Settings.defaultSettings;
m_CurveEditor = new CurveEditor(settings);
AddCurve(m_Curves.master, new Color(1f, 1f, 1f), 2, false);
AddCurve(m_Curves.red, new Color(1f, 0f, 0f), 2, false);
AddCurve(m_Curves.green, new Color(0f, 1f, 0f), 2, false);
AddCurve(m_Curves.blue, new Color(0f, 0.5f, 1f), 2, false);
AddCurve(m_Curves.hueVShue, new Color(1f, 1f, 1f), 0, true);
AddCurve(m_Curves.hueVSsat, new Color(1f, 1f, 1f), 0, true);
AddCurve(m_Curves.satVSsat, new Color(1f, 1f, 1f), 0, false);
AddCurve(m_Curves.lumVSsat, new Color(1f, 1f, 1f), 0, false);
}
void AddCurve(SerializedProperty prop, Color color, uint minPointCount, bool loop)
{
var state = CurveEditor.CurveState.defaultState;
state.color = color;
state.visible = false;
state.minPointCount = minPointCount;
state.onlyShowHandlesOnSelection = true;
state.zeroKeyConstantValue = 0.5f;
state.loopInBounds = loop;
m_CurveEditor.Add(prop, state);
m_CurveDict.Add(prop, color);
}
public override void OnDisable()
{
m_CurveEditor.RemoveAll();
}
public override void OnInspectorGUI()
{
DoGUIFor("Tonemapping", DoTonemappingGUI);
EditorGUILayout.Space();
DoGUIFor("Basic", DoBasicGUI);
EditorGUILayout.Space();
DoGUIFor("Channel Mixer", DoChannelMixerGUI);
EditorGUILayout.Space();
DoGUIFor("Trackballs", DoColorWheelsGUI);
EditorGUILayout.Space();
DoGUIFor("Grading Curves", DoCurvesGUI);
}
void DoGUIFor(string title, Action func)
{
EditorGUILayout.LabelField(title, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
func();
EditorGUI.indentLevel--;
}
void DoTonemappingGUI()
{
int tid = EditorGUILayout.Popup(EditorGUIHelper.GetContent("Tonemapper"), m_Tonemapping.tonemapper.intValue, s_Tonemappers);
if (tid == (int)Tonemapper.Neutral)
{
DrawNeutralTonemappingCurve();
EditorGUILayout.PropertyField(m_Tonemapping.neutralBlackIn, EditorGUIHelper.GetContent("Black In"));
EditorGUILayout.PropertyField(m_Tonemapping.neutralWhiteIn, EditorGUIHelper.GetContent("White In"));
EditorGUILayout.PropertyField(m_Tonemapping.neutralBlackOut, EditorGUIHelper.GetContent("Black Out"));
EditorGUILayout.PropertyField(m_Tonemapping.neutralWhiteOut, EditorGUIHelper.GetContent("White Out"));
EditorGUILayout.PropertyField(m_Tonemapping.neutralWhiteLevel, EditorGUIHelper.GetContent("White Level"));
EditorGUILayout.PropertyField(m_Tonemapping.neutralWhiteClip, EditorGUIHelper.GetContent("White Clip"));
}
m_Tonemapping.tonemapper.intValue = tid;
}
void DrawNeutralTonemappingCurve()
{
using (new GUILayout.HorizontalScope())
{
GUILayout.Space(EditorGUI.indentLevel * 15f);
m_NeutralCurveRect = GUILayoutUtility.GetRect(128, 80);
}
// Background
m_RectVertices[0] = PointInRect( 0f, 0f);
m_RectVertices[1] = PointInRect(k_NeutralRangeX, 0f);
m_RectVertices[2] = PointInRect(k_NeutralRangeX, k_NeutralRangeY);
m_RectVertices[3] = PointInRect( 0f, k_NeutralRangeY);
Handles.DrawSolidRectangleWithOutline(
m_RectVertices,
Color.white * 0.1f,
Color.white * 0.4f
);
// Horizontal lines
for (var i = 1; i < k_NeutralRangeY; i++)
DrawLine(0, i, k_NeutralRangeX, i, 0.4f);
// Vertical lines
for (var i = 1; i < k_NeutralRangeX; i++)
DrawLine(i, 0, i, k_NeutralRangeY, 0.4f);
// Label
Handles.Label(
PointInRect(0, k_NeutralRangeY) + Vector3.right,
"Neutral Tonemapper", EditorStyles.miniLabel
);
// Precompute some values
var tonemap = ((ColorGradingModel)target).settings.tonemapping;
const float scaleFactor = 20f;
const float scaleFactorHalf = scaleFactor * 0.5f;
float inBlack = tonemap.neutralBlackIn * scaleFactor + 1f;
float outBlack = tonemap.neutralBlackOut * scaleFactorHalf + 1f;
float inWhite = tonemap.neutralWhiteIn / scaleFactor;
float outWhite = 1f - tonemap.neutralWhiteOut / scaleFactor;
float blackRatio = inBlack / outBlack;
float whiteRatio = inWhite / outWhite;
const float a = 0.2f;
float b = Mathf.Max(0f, Mathf.LerpUnclamped(0.57f, 0.37f, blackRatio));
float c = Mathf.LerpUnclamped(0.01f, 0.24f, whiteRatio);
float d = Mathf.Max(0f, Mathf.LerpUnclamped(0.02f, 0.20f, blackRatio));
const float e = 0.02f;
const float f = 0.30f;
float whiteLevel = tonemap.neutralWhiteLevel;
float whiteClip = tonemap.neutralWhiteClip / scaleFactorHalf;
// Tonemapping curve
var vcount = 0;
while (vcount < k_CurveResolution)
{
float x = k_NeutralRangeX * vcount / (k_CurveResolution - 1);
float y = NeutralTonemap(x, a, b, c, d, e, f, whiteLevel, whiteClip);
if (y < k_NeutralRangeY)
{
m_CurveVertices[vcount++] = PointInRect(x, y);
}
else
{
if (vcount > 1)
{
// Extend the last segment to the top edge of the rect.
var v1 = m_CurveVertices[vcount - 2];
var v2 = m_CurveVertices[vcount - 1];
var clip = (m_NeutralCurveRect.y - v1.y) / (v2.y - v1.y);
m_CurveVertices[vcount - 1] = v1 + (v2 - v1) * clip;
}
break;
}
}
if (vcount > 1)
{
Handles.color = Color.white * 0.9f;
Handles.DrawAAPolyLine(2.0f, vcount, m_CurveVertices);
}
}
void DrawLine(float x1, float y1, float x2, float y2, float grayscale)
{
m_LineVertices[0] = PointInRect(x1, y1);
m_LineVertices[1] = PointInRect(x2, y2);
Handles.color = Color.white * grayscale;
Handles.DrawAAPolyLine(2f, m_LineVertices);
}
Vector3 PointInRect(float x, float y)
{
x = Mathf.Lerp(m_NeutralCurveRect.x, m_NeutralCurveRect.xMax, x / k_NeutralRangeX);
y = Mathf.Lerp(m_NeutralCurveRect.yMax, m_NeutralCurveRect.y, y / k_NeutralRangeY);
return new Vector3(x, y, 0);
}
float NeutralCurve(float x, float a, float b, float c, float d, float e, float f)
{
return ((x * (a * x + c * b) + d * e) / (x * (a * x + b) + d * f)) - e / f;
}
float NeutralTonemap(float x, float a, float b, float c, float d, float e, float f, float whiteLevel, float whiteClip)
{
x = Mathf.Max(0f, x);
// Tonemap
float whiteScale = 1f / NeutralCurve(whiteLevel, a, b, c, d, e, f);
x = NeutralCurve(x * whiteScale, a, b, c, d, e, f);
x *= whiteScale;
// Post-curve white point adjustment
x /= whiteClip;
return x;
}
void DoBasicGUI()
{
EditorGUILayout.PropertyField(m_Basic.exposure, EditorGUIHelper.GetContent("Post Exposure (EV)"));
EditorGUILayout.PropertyField(m_Basic.temperature);
EditorGUILayout.PropertyField(m_Basic.tint);
EditorGUILayout.PropertyField(m_Basic.hueShift);
EditorGUILayout.PropertyField(m_Basic.saturation);
EditorGUILayout.PropertyField(m_Basic.contrast);
}
void DoChannelMixerGUI()
{
int currentChannel = m_ChannelMixer.currentEditingChannel.intValue;
EditorGUI.BeginChangeCheck();
{
using (new EditorGUILayout.HorizontalScope())
{
EditorGUILayout.PrefixLabel("Channel");
if (GUILayout.Toggle(currentChannel == 0, EditorGUIHelper.GetContent("Red|Red output channel."), EditorStyles.miniButtonLeft)) currentChannel = 0;
if (GUILayout.Toggle(currentChannel == 1, EditorGUIHelper.GetContent("Green|Green output channel."), EditorStyles.miniButtonMid)) currentChannel = 1;
if (GUILayout.Toggle(currentChannel == 2, EditorGUIHelper.GetContent("Blue|Blue output channel."), EditorStyles.miniButtonRight)) currentChannel = 2;
}
}
if (EditorGUI.EndChangeCheck())
{
GUI.FocusControl(null);
}
var serializedChannel = m_ChannelMixer.channels[currentChannel];
m_ChannelMixer.currentEditingChannel.intValue = currentChannel;
var v = serializedChannel.vector3Value;
v.x = EditorGUILayout.Slider(EditorGUIHelper.GetContent("Red|Modify influence of the red channel within the overall mix."), v.x, -2f, 2f);
v.y = EditorGUILayout.Slider(EditorGUIHelper.GetContent("Green|Modify influence of the green channel within the overall mix."), v.y, -2f, 2f);
v.z = EditorGUILayout.Slider(EditorGUIHelper.GetContent("Blue|Modify influence of the blue channel within the overall mix."), v.z, -2f, 2f);
serializedChannel.vector3Value = v;
}
void DoColorWheelsGUI()
{
int wheelMode = m_ColorWheels.mode.intValue;
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Space(15);
if (GUILayout.Toggle(wheelMode == (int)ColorWheelMode.Linear, "Linear", EditorStyles.miniButtonLeft)) wheelMode = (int)ColorWheelMode.Linear;
if (GUILayout.Toggle(wheelMode == (int)ColorWheelMode.Log, "Log", EditorStyles.miniButtonRight)) wheelMode = (int)ColorWheelMode.Log;
}
m_ColorWheels.mode.intValue = wheelMode;
EditorGUILayout.Space();
if (wheelMode == (int)ColorWheelMode.Linear)
{
EditorGUILayout.PropertyField(m_ColorWheels.linear);
WheelSetTitle(GUILayoutUtility.GetLastRect(), "Linear Controls");
}
else if (wheelMode == (int)ColorWheelMode.Log)
{
EditorGUILayout.PropertyField(m_ColorWheels.log);
WheelSetTitle(GUILayoutUtility.GetLastRect(), "Log Controls");
}
}
static void WheelSetTitle(Rect position, string label)
{
var matrix = GUI.matrix;
var rect = new Rect(position.x - 10f, position.y, TrackballGroupDrawer.m_Size, TrackballGroupDrawer.m_Size);
GUIUtility.RotateAroundPivot(-90f, rect.center);
GUI.Label(rect, label, FxStyles.centeredMiniLabel);
GUI.matrix = matrix;
}
void ResetVisibleCurves()
{
foreach (var curve in m_CurveDict)
{
var state = m_CurveEditor.GetCurveState(curve.Key);
state.visible = false;
m_CurveEditor.SetCurveState(curve.Key, state);
}
}
void SetCurveVisible(SerializedProperty prop)
{
var state = m_CurveEditor.GetCurveState(prop);
state.visible = true;
m_CurveEditor.SetCurveState(prop, state);
}
bool SpecialToggle(bool value, string name, out bool rightClicked)
{
var rect = GUILayoutUtility.GetRect(EditorGUIHelper.GetContent(name), EditorStyles.toolbarButton);
var e = Event.current;
rightClicked = (e.type == EventType.MouseUp && rect.Contains(e.mousePosition) && e.button == 1);
return GUI.Toggle(rect, value, name, EditorStyles.toolbarButton);
}
static Material s_MaterialSpline;
void DoCurvesGUI()
{
EditorGUILayout.Space();
EditorGUI.indentLevel -= 2;
ResetVisibleCurves();
using (new EditorGUI.DisabledGroupScope(serializedProperty.serializedObject.isEditingMultipleObjects))
{
int curveEditingId = 0;
// Top toolbar
using (new GUILayout.HorizontalScope(EditorStyles.toolbar))
{
curveEditingId = EditorGUILayout.Popup(m_Curves.currentEditingCurve.intValue, s_Curves, EditorStyles.toolbarPopup, GUILayout.MaxWidth(150f));
bool y = false, r = false, g = false, b = false;
if (curveEditingId == 0)
{
EditorGUILayout.Space();
bool rightClickedY, rightClickedR, rightClickedG, rightClickedB;
y = SpecialToggle(m_Curves.curveY.boolValue, "Y", out rightClickedY);
r = SpecialToggle(m_Curves.curveR.boolValue, "R", out rightClickedR);
g = SpecialToggle(m_Curves.curveG.boolValue, "G", out rightClickedG);
b = SpecialToggle(m_Curves.curveB.boolValue, "B", out rightClickedB);
if (!y && !r && !g && !b)
{
r = g = b = false;
y = true;
}
if (rightClickedY || rightClickedR || rightClickedG || rightClickedB)
{
y = rightClickedY;
r = rightClickedR;
g = rightClickedG;
b = rightClickedB;
}
if (y) SetCurveVisible(m_Curves.master);
if (r) SetCurveVisible(m_Curves.red);
if (g) SetCurveVisible(m_Curves.green);
if (b) SetCurveVisible(m_Curves.blue);
m_Curves.curveY.boolValue = y;
m_Curves.curveR.boolValue = r;
m_Curves.curveG.boolValue = g;
m_Curves.curveB.boolValue = b;
}
else
{
switch (curveEditingId)
{
case 1: SetCurveVisible(m_Curves.hueVShue);
break;
case 2: SetCurveVisible(m_Curves.hueVSsat);
break;
case 3: SetCurveVisible(m_Curves.satVSsat);
break;
case 4: SetCurveVisible(m_Curves.lumVSsat);
break;
}
}
GUILayout.FlexibleSpace();
if (GUILayout.Button("Reset", EditorStyles.toolbarButton))
{
switch (curveEditingId)
{
case 0:
if (y) m_Curves.master.animationCurveValue = AnimationCurve.Linear(0f, 0f, 1f, 1f);
if (r) m_Curves.red.animationCurveValue = AnimationCurve.Linear(0f, 0f, 1f, 1f);
if (g) m_Curves.green.animationCurveValue = AnimationCurve.Linear(0f, 0f, 1f, 1f);
if (b) m_Curves.blue.animationCurveValue = AnimationCurve.Linear(0f, 0f, 1f, 1f);
break;
case 1: m_Curves.hueVShue.animationCurveValue = new AnimationCurve();
break;
case 2: m_Curves.hueVSsat.animationCurveValue = new AnimationCurve();
break;
case 3: m_Curves.satVSsat.animationCurveValue = new AnimationCurve();
break;
case 4: m_Curves.lumVSsat.animationCurveValue = new AnimationCurve();
break;
}
}
m_Curves.currentEditingCurve.intValue = curveEditingId;
}
// Curve area
var settings = m_CurveEditor.settings;
var rect = GUILayoutUtility.GetAspectRect(2f);
var innerRect = settings.padding.Remove(rect);
if (Event.current.type == EventType.Repaint)
{
// Background
EditorGUI.DrawRect(rect, new Color(0.15f, 0.15f, 0.15f, 1f));
if (s_MaterialSpline == null)
s_MaterialSpline = new Material(Shader.Find("Hidden/Post FX/UI/Curve Background")) { hideFlags = HideFlags.HideAndDontSave };
if (curveEditingId == 1 || curveEditingId == 2)
DrawBackgroundTexture(innerRect, 0);
else if (curveEditingId == 3 || curveEditingId == 4)
DrawBackgroundTexture(innerRect, 1);
// Bounds
Handles.color = Color.white;
Handles.DrawSolidRectangleWithOutline(innerRect, Color.clear, new Color(0.8f, 0.8f, 0.8f, 0.5f));
// Grid setup
Handles.color = new Color(1f, 1f, 1f, 0.05f);
int hLines = (int)Mathf.Sqrt(innerRect.width);
int vLines = (int)(hLines / (innerRect.width / innerRect.height));
// Vertical grid
int gridOffset = Mathf.FloorToInt(innerRect.width / hLines);
int gridPadding = ((int)(innerRect.width) % hLines) / 2;
for (int i = 1; i < hLines; i++)
{
var offset = i * Vector2.right * gridOffset;
offset.x += gridPadding;
Handles.DrawLine(innerRect.position + offset, new Vector2(innerRect.x, innerRect.yMax - 1) + offset);
}
// Horizontal grid
gridOffset = Mathf.FloorToInt(innerRect.height / vLines);
gridPadding = ((int)(innerRect.height) % vLines) / 2;
for (int i = 1; i < vLines; i++)
{
var offset = i * Vector2.up * gridOffset;
offset.y += gridPadding;
Handles.DrawLine(innerRect.position + offset, new Vector2(innerRect.xMax - 1, innerRect.y) + offset);
}
}
// Curve editor
if (m_CurveEditor.OnGUI(rect))
{
Repaint();
GUI.changed = true;
}
if (Event.current.type == EventType.Repaint)
{
// Borders
Handles.color = Color.black;
Handles.DrawLine(new Vector2(rect.x, rect.y - 18f), new Vector2(rect.xMax, rect.y - 18f));
Handles.DrawLine(new Vector2(rect.x, rect.y - 19f), new Vector2(rect.x, rect.yMax));
Handles.DrawLine(new Vector2(rect.x, rect.yMax), new Vector2(rect.xMax, rect.yMax));
Handles.DrawLine(new Vector2(rect.xMax, rect.yMax), new Vector2(rect.xMax, rect.y - 18f));
// Selection info
var selection = m_CurveEditor.GetSelection();
if (selection.curve != null && selection.keyframeIndex > -1)
{
var key = selection.keyframe.Value;
var infoRect = innerRect;
infoRect.x += 5f;
infoRect.width = 100f;
infoRect.height = 30f;
GUI.Label(infoRect, string.Format("{0}\n{1}", key.time.ToString("F3"), key.value.ToString("F3")), FxStyles.preLabel);
}
}
}
/*
EditorGUILayout.HelpBox(
@"Curve editor cheat sheet:
- [Del] or [Backspace] to remove a key
- [Ctrl] to break a tangent handle
- [Shift] to align tangent handles
- [Double click] to create a key on the curve(s) at mouse position
- [Alt] + [Double click] to create a key on the curve(s) at a given time",
MessageType.Info);
*/
EditorGUILayout.Space();
EditorGUI.indentLevel += 2;
}
void DrawBackgroundTexture(Rect rect, int pass)
{
float scale = EditorGUIUtility.pixelsPerPoint;
var oldRt = RenderTexture.active;
var rt = RenderTexture.GetTemporary(Mathf.CeilToInt(rect.width * scale), Mathf.CeilToInt(rect.height * scale), 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear);
s_MaterialSpline.SetFloat("_DisabledState", GUI.enabled ? 1f : 0.5f);
s_MaterialSpline.SetFloat("_PixelScaling", EditorGUIUtility.pixelsPerPoint);
Graphics.Blit(null, rt, s_MaterialSpline, pass);
RenderTexture.active = oldRt;
GUI.DrawTexture(rect, rt);
RenderTexture.ReleaseTemporary(rt);
}
}
}
| 412 | 0.976228 | 1 | 0.976228 | game-dev | MEDIA | 0.443378 | game-dev,graphics-rendering | 0.95672 | 1 | 0.95672 |
lanl-ansi/Juniper.jl | 4,472 | src/bb_gains.jl | function Base.:+(a::GainObj, b::GainObj)
new_minus = a.minus + b.minus
new_plus = a.plus + b.plus
new_minus_counter = a.minus_counter + b.minus_counter
new_plus_counter = a.plus_counter + b.plus_counter
new_inf_counter = a.inf_counter + b.inf_counter
return GainObj(
new_minus,
new_plus,
new_minus_counter,
new_plus_counter,
new_inf_counter,
)
end
function Base.copy(a::GainObj)
return GainObj(
a.minus,
a.plus,
a.minus_counter,
a.plus_counter,
a.inf_counter,
)
end
function init_gains(num_disc_var)
gains_m = zeros(num_disc_var)
gains_p = zeros(num_disc_var)
gains_mc = zeros(Int64, num_disc_var)
gains_pc = zeros(Int64, num_disc_var)
gains_inf = zeros(Int64, num_disc_var)
return GainObj(gains_m, gains_p, gains_mc, gains_pc, gains_inf)
end
"""
update_gains!(tree::BnBTreeObj, parent::BnBNode, l_nd, r_nd)
Update the objective gains for the branch variable used for node
"""
function update_gains!(tree::BnBTreeObj, parent::BnBNode, l_nd, r_nd)
gain_l =
sigma_minus(tree.options, parent, l_nd, parent.solution[parent.var_idx])
gain_r =
sigma_plus(tree.options, parent, r_nd, parent.solution[parent.var_idx])
idx = tree.var2disc_idx[parent.var_idx]
gain = 0.0
gain_c = 0
if !isinf(gain_l)
tree.obj_gain.minus[idx] = gain_l
tree.obj_gain.minus_counter[idx] += 1
gain += gain_l
gain_c += 1
else
tree.obj_gain.inf_counter[idx] += 1
end
if !isinf(gain_r)
tree.obj_gain.plus[idx] = gain_r
tree.obj_gain.plus_counter[idx] += 1
gain += gain_r
gain_c += 1
else
tree.obj_gain.inf_counter[idx] += 1
end
if !isinf(gain_l) && !isinf(gain_r) && tree.obj_gain.inf_counter[idx] > 0
tree.obj_gain.inf_counter[idx] -= 1
end
if gain_c == 0
return 0
else
return gain / gain_c
end
end
"""
upd_gains_step!(tree, step_obj)
Update the gains using the step_obj if using StrongPseudoCost or PseudoCost
"""
function upd_gains_step!(tree, step_obj)
branch_strat = tree.options.branch_strategy
opts = tree.options
if step_obj.upd_gains == :GainsToTree || (
branch_strat == :StrongPseudoCost &&
step_obj.counter <= opts.strong_branching_nsteps
)
tree.obj_gain += step_obj.obj_gain
tree.obj_gain.inf_counter[tree.obj_gain.inf_counter.<0] .= 0
if step_obj.counter == 1
cum_counter =
tree.obj_gain.minus_counter .+ tree.obj_gain.plus_counter
strong_disc_vars = findall(cum_counter .> 0)
step_obj.strong_disc_vars = strong_disc_vars
# all other variables that haven't been checked get the median value of the others
med_gain_m = median(tree.obj_gain.minus[strong_disc_vars])
med_gain_p = median(tree.obj_gain.plus[strong_disc_vars])
rest = filter(i -> !(i in strong_disc_vars), 1:tree.m.num_disc_var)
tree.obj_gain.minus[rest] .= med_gain_m
tree.obj_gain.plus[rest] .= med_gain_p
tree.obj_gain.minus_counter[rest] .= 1
tree.obj_gain.plus_counter[rest] .= 1
end
elseif step_obj.upd_gains == :GuessAndUpdate ||
branch_strat == :PseudoCost ||
(
branch_strat == :StrongPseudoCost &&
step_obj.counter > opts.strong_branching_nsteps
)
upd_start = time()
guess_gain_val = guess_gain(tree, step_obj)
gain = update_gains!(tree, step_obj.node, step_obj.l_nd, step_obj.r_nd)
step_obj.gain_gap = abs(guess_gain_val - gain) / abs(gain)
if isnan(step_obj.gain_gap) # 0/0
step_obj.gain_gap = 0.0
end
step_obj.upd_gains_time = time() - upd_start
end
end
function guess_gain(tree, step_obj)
i = step_obj.var_idx
disc_i = tree.var2disc_idx[i]
x = step_obj.node.solution
g_minus, g_minus_c = tree.obj_gain.minus, tree.obj_gain.minus_counter
g_plus, g_plus_c = tree.obj_gain.plus, tree.obj_gain.plus_counter
g_minus_c += map(i -> (i == 0) && (i = 1), g_minus_c)
g_plus_c += map(i -> (i == 0) && (i = 1), g_plus_c)
mu = tree.options.gain_mu
return score(
f_minus(x[i]) * g_minus[disc_i] / g_minus_c[disc_i],
f_plus(x[i]) * g_plus[disc_i] / g_plus_c[disc_i],
mu,
)
end
| 412 | 0.746556 | 1 | 0.746556 | game-dev | MEDIA | 0.679274 | game-dev | 0.947648 | 1 | 0.947648 |
emmansun/gmsm | 2,496 | internal/bigmod/nat_loong64.s | // Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// derived from crypto/internal/fips140/bigmod/nat_riscv64.s
//go:build !purego
#include "textflag.h"
// func addMulVVW256(z, x *uint, y uint) (c uint)
TEXT ·addMulVVW256(SB),$0-32
MOVV $4, R8
JMP addMulVVWy(SB)
// func addMulVVW1024(z, x *uint, y uint) (c uint)
TEXT ·addMulVVW1024(SB),$0-32
MOVV $16, R8
JMP addMulVVWy(SB)
// func addMulVVW1536(z, x *uint, y uint) (c uint)
TEXT ·addMulVVW1536(SB),$0-32
MOVV $24, R8
JMP addMulVVWy(SB)
// func addMulVVW2048(z, x *uint, y uint) (c uint)
TEXT ·addMulVVW2048(SB),$0-32
MOVV $32, R8
JMP addMulVVWy(SB)
TEXT addMulVVWy(SB),NOFRAME|NOSPLIT,$0
MOVV z+0(FP), R4
MOVV x+8(FP), R6
MOVV y+16(FP), R5
MOVV $0, R7
BEQ R8, R0, done
loop:
MOVV 0*8(R4), R9 // z[0]
MOVV 1*8(R4), R10 // z[1]
MOVV 2*8(R4), R11 // z[2]
MOVV 3*8(R4), R12 // z[3]
MOVV 0*8(R6), R13 // x[0]
MOVV 1*8(R6), R14 // x[1]
MOVV 2*8(R6), R15 // x[2]
MOVV 3*8(R6), R16 // x[3]
MULHVU R13, R5, R17 // z_hi[0] = x[0] * y
MULV R13, R5, R13 // z_lo[0] = x[0] * y
ADDV R13, R9, R18 // z_lo[0] = x[0] * y + z[0]
SGTU R13, R18, R19
ADDV R17, R19, R17 // z_hi[0] = x[0] * y + z[0]
ADDV R18, R7, R9 // z_lo[0] = x[0] * y + z[0] + c
SGTU R18, R9, R19
ADDV R17, R19, R7 // next c
MULHVU R14, R5, R24 // z_hi[1] = x[1] * y
MULV R14, R5, R14 // z_lo[1] = x[1] * y
ADDV R14, R10, R18 // z_lo[1] = x[1] * y + z[1]
SGTU R14, R18, R19
ADDV R24, R19, R24 // z_hi[1] = x[1] * y + z[1]
ADDV R18, R7, R10 // z_lo[1] = x[1] * y + z[1] + c
SGTU R18, R10, R19
ADDV R24, R19, R7 // next c
MULHVU R15, R5, R25 // z_hi[2] = x[2] * y
MULV R15, R5, R15 // z_lo[2] = x[2] * y
ADDV R15, R11, R18 // z_lo[2] = x[2] * y + z[2]
SGTU R15, R18, R19
ADDV R25, R19, R25 // z_hi[2] = x[2] * y + z[2]
ADDV R18, R7, R11 // z_lo[2] = x[2] * y + z[2] + c
SGTU R18, R11, R19
ADDV R25, R19, R7 // next c
MULHVU R16, R5, R26 // z_hi[3] = x[3] * y
MULV R16, R5, R16 // z_lo[3] = x[3] * y
ADDV R16, R12, R18 // z_lo[3] = x[3] * y + z[3]
SGTU R16, R18, R19
ADDV R26, R19, R26 // z_hi[3] = x[3] * y + z[3]
ADDV R18, R7, R12 // z_lo[3] = x[3] * y + z[3] + c
SGTU R18, R12, R19
ADDV R26, R19, R7 // next c
MOVV R9, 0*8(R4) // z[0]
MOVV R10, 1*8(R4) // z[1]
MOVV R11, 2*8(R4) // z[2]
MOVV R12, 3*8(R4) // z[3]
ADDV $32, R4
ADDV $32, R6
SUBV $4, R8
BNE R8, R0, loop
done:
MOVV R7, c+24(FP)
RET
| 412 | 0.598775 | 1 | 0.598775 | game-dev | MEDIA | 0.487185 | game-dev | 0.95299 | 1 | 0.95299 |
google-deepmind/lab | 2,710 | public/dmlab.h | // Copyright (C) 2016-2018 Google Inc.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
////////////////////////////////////////////////////////////////////////////////
//
// The RL Environment API entry point.
#ifndef DML_PUBLIC_DMLAB_H_
#define DML_PUBLIC_DMLAB_H_
#include <stddef.h>
#include "public/file_reader_types.h"
#include "public/level_cache_types.h"
#include "third_party/rl_api/env_c_api.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct DeepMindLabLaunchParams_s DeepMindLabLaunchParams;
// Enum depicting which renderer to use for DMLab.
enum DeepMindLabRenderer_Enum {
DeepMindLabRenderer_Software,
DeepMindLabRenderer_Hardware,
};
typedef enum DeepMindLabRenderer_Enum DeepMindLabRenderer;
struct DeepMindLabLaunchParams_s {
// Path to where DeepMind Lab assets are stored.
const char* runfiles_path;
DeepMindLabRenderer renderer;
DeepMindLabLevelCacheParams level_cache_params;
// Optional function for reading from the file system. If set, a call returns
// whether the file 'file_name' was read successfully and if so 'buff' points
// to the content and 'size' contains the size of the file and after use
// 'buff' must be freed with 'free'. Otherwise returns false.
DeepmindFileReaderType* file_reader_override;
const char* optional_temp_folder;
// Optional readonly filesystem. Set null to use local file operations.
const DeepMindReadOnlyFileSystem* read_only_file_system;
};
// Starts an instance of DeepMind Lab and exports the single-player RL
// Environment API to *env_c_api. This function may be called at most once
// per process unless called via dmlab_so_loader. (DeepMind Lab is not
// modular and reusable.)
//
// 'params' must be dereferenceable; the DeepMindLabLaunchParams that it
// points to is owned by the caller.
//
// Returns 0 on success and non-zero otherwise.
int dmlab_connect(
const DeepMindLabLaunchParams* params,
EnvCApi* env_c_api,
void** context);
#ifdef __cplusplus
} // extern "C"
#endif
#endif // DML_PUBLIC_DMLAB_H_
| 412 | 0.880815 | 1 | 0.880815 | game-dev | MEDIA | 0.348007 | game-dev | 0.530032 | 1 | 0.530032 |
Darkrp-community/OpenKeep | 1,104 | code/game/objects/structures/hivebot.dm | /obj/structure/hivebot_beacon
name = "beacon"
desc = ""
icon = 'icons/mob/hivebot.dmi'
icon_state = "def_radar-off"
anchored = TRUE
density = TRUE
var/bot_type = "norm"
var/bot_amt = 10
/obj/structure/hivebot_beacon/Initialize()
. = ..()
var/datum/effect_system/smoke_spread/smoke = new
smoke.set_up(2, loc)
smoke.start()
visible_message("<span class='boldannounce'>[src] warps in!</span>")
playsound(src.loc, 'sound/blank.ogg', 25, TRUE)
addtimer(CALLBACK(src, PROC_REF(warpbots)), rand(10, 600))
/obj/structure/hivebot_beacon/proc/warpbots()
icon_state = "def_radar"
visible_message("<span class='danger'>[src] turns on!</span>")
while(bot_amt > 0)
bot_amt--
switch(bot_type)
if("norm")
new /mob/living/simple_animal/hostile/hivebot(get_turf(src))
if("range")
new /mob/living/simple_animal/hostile/hivebot/range(get_turf(src))
if("rapid")
new /mob/living/simple_animal/hostile/hivebot/rapid(get_turf(src))
sleep(100)
visible_message("<span class='boldannounce'>[src] warps out!</span>")
playsound(src.loc, 'sound/blank.ogg', 25, TRUE)
qdel(src)
return
| 412 | 0.951876 | 1 | 0.951876 | game-dev | MEDIA | 0.713566 | game-dev | 0.985865 | 1 | 0.985865 |
SQLab/CRAXplusplus | 3,057 | src/Techniques/Technique.h | // Copyright 2021-2022 Software Quality Laboratory, NYCU.
//
// 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.
#ifndef S2E_PLUGINS_CRAX_TECHNIQUE_H
#define S2E_PLUGINS_CRAX_TECHNIQUE_H
#include <llvm/ADT/SmallVector.h>
#include <s2e/Plugins/CRAX/API/Logging.h>
#include <s2e/Plugins/CRAX/Expr/Expr.h>
#include <atomic>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include <typeindex>
namespace s2e::plugins::crax {
using RopPayload = std::vector<klee::ref<klee::Expr>>;
// The abstract base class of all concrete exploitation techniques,
// e.g., stack pivoting, ret2csu, orw, etc.
class Technique {
protected:
using BaseType = klee::BaseOffsetExpr::BaseType;
public:
virtual ~Technique() = default;
virtual void initialize();
virtual bool checkRequirements() const;
virtual void resolveRequiredGadgets();
virtual std::string toString() const = 0;
virtual std::vector<RopPayload> getRopPayloadList() const = 0;
virtual RopPayload getExtraRopPayload() const = 0;
std::string getConfigKey() const;
static std::unique_ptr<Technique> create(const std::string &name);
static std::map<std::type_index, Technique *> s_mapper;
protected:
Technique()
: m_hasPopulatedRequiredGadgets(true),
m_requiredGadgets() {}
[[gnu::always_inline]]
inline void blockUntilRequiredGadgetsPopulated() const {
if (m_hasPopulatedRequiredGadgets) {
return;
}
log<WARN>() << toString() << " is still running, please wait...\n";
while (!m_hasPopulatedRequiredGadgets) {}
}
// Some techniques determines the required gadgets in a background thread.
// In such cases, this atomic bool must be set to false, and the
// background thread must set it back to true when it finishes.
std::atomic<bool> m_hasPopulatedRequiredGadgets;
llvm::SmallVector<std::pair<const ELF *, std::string>, 8> m_requiredGadgets;
};
} // namespace s2e::plugins::crax
#endif // S2E_PLUGINS_CRAX_TECHNIQUE_H
| 412 | 0.880322 | 1 | 0.880322 | game-dev | MEDIA | 0.494597 | game-dev | 0.632479 | 1 | 0.632479 |
RafaelDeJongh/cap | 3,016 | lua/effects/energy_muzzle_asuran.lua | /*
Energy Weapon Muzzle for GarrysMod10
Copyright (C) 2007 aVoN
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/>.
*/
if (StarGate==nil or StarGate.MaterialFromVMT==nil) then return end
EFFECT.Glow = StarGate.MaterialFromVMT(
"MuzzleSprite",
[["UnLitGeneric"
{
"$basetexture" "sprites/light_glow01"
"$nocull" 1
"$additive" 1
"$vertexalpha" 1
"$vertexcolor" 1
}]]
);
EFFECT.Size = 64;
EFFECT.Color = Color(255,200,120);
--################### Init @aVoN
function EFFECT:Init(data)
self.Parent = data:GetEntity();
if(not IsValid(self.Parent)) then return end;
self.Entity:SetParent(self.Parent);
local radius = tonumber(data:GetRadius()) or 1;
if(radius > 1) then
self.Size = radius;
end
self.Entity:SetRenderBounds(Vector(1,1,1)*self.Size*(-2),Vector(1,1,1)*self.Size*2);
local color = data:GetAngles();
if(color ~= Angle(0,0,0)) then
self.Color = Color(119,176,255,215)
end
-- ######################## Dynamic light
-- Gets the visual-setting's name according to the weapon.
local e = self.Parent;
local class = e:GetClass();
if(e:IsPlayer()) then e = e:GetActiveWeapon() end;
if(IsValid(e)) then class = e:GetClass():gsub("weapon_","") end;
if(class == "staff_weapon_glider") then class = "staff" end; -- Damn workaround!
if(StarGate.VisualsWeapons("cl_"..(class or "").."_dynlights")) then
local dynlight = DynamicLight(0);
dynlight.Pos = data:GetOrigin();
dynlight.Size = 300;
dynlight.Decay = 300;
dynlight.R = self.Color.r;
dynlight.G = self.Color.g;
dynlight.B = self.Color.b;
dynlight.DieTime = CurTime()+1;
end
self.Draw = true;
end
--################### Render the effect @aVoN
function EFFECT:Render()
if(not IsValid(self.Parent)) then return end;
local start = self.Parent:GetPos();
if(self.Parent.GetShootPos) then
start =self.Parent:GetShootPos();
end
local viewmodel
if(self.Parent == LocalPlayer()) then
viewmodel = self.Parent:GetViewModel();
else
if(self.Parent.GetActiveWeapon) then
viewmodel = self.Parent:GetActiveWeapon();
end
end
if(not IsValid(viewmodel)) then return end;
local attach = viewmodel:GetAttachment(1);
if(not attach) then return end;
start = attach.Pos;
render.SetMaterial(self.Glow);
render.DrawSprite(
start,
self.Size,
self.Size,
self.Color
);
end
--################### Think @aVoN
function EFFECT:Think()
self.Size = math.Clamp(self.Size-150*FrameTime(),0,1337);
return (self.Size > 0 and self.Draw);
end
| 412 | 0.931907 | 1 | 0.931907 | game-dev | MEDIA | 0.8201 | game-dev,graphics-rendering | 0.981027 | 1 | 0.981027 |
SkytAsul/BeautyQuests | 1,183 | v1_9_R2/src/main/java/fr/skytasul/quests/utils/nms/v1_9_R2.java | package fr.skytasul.quests.utils.nms;
import org.bukkit.craftbukkit.v1_9_R2.entity.CraftEntity;
import org.bukkit.craftbukkit.v1_9_R2.entity.CraftPlayer;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_9_R2.EnumChatFormat;
import net.minecraft.server.v1_9_R2.IChatBaseComponent;
import net.minecraft.server.v1_9_R2.PacketDataSerializer;
import net.minecraft.server.v1_9_R2.PacketPlayOutCustomPayload;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
public class v1_9_R2 extends NMS{
@Override
public void openBookInHand(Player p) {
ByteBuf buf = Unpooled.buffer(256);
buf.setByte(0, (byte) 0);
buf.writerIndex(1);
PacketPlayOutCustomPayload packet = new PacketPlayOutCustomPayload("MC|BOpen", new PacketDataSerializer(buf));
((CraftPlayer) p).getHandle().playerConnection.sendPacket(packet);
}
@Override
public double entityNameplateHeight(Entity en){
return ((CraftEntity) en).getHandle().length;
}
public Object getIChatBaseComponent(String text){
return IChatBaseComponent.ChatSerializer.b(text);
}
public Object getEnumChatFormat(int value){
return EnumChatFormat.a(value);
}
} | 412 | 0.778578 | 1 | 0.778578 | game-dev | MEDIA | 0.992661 | game-dev | 0.892101 | 1 | 0.892101 |
spiralstorm/Pixelwave | 2,508 | PixelKit/ExternalFrameworks/Box2D/Box2D/Dynamics/b2Island.h | /*
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef B2_ISLAND_H
#define B2_ISLAND_H
#include "b2Math.h"
#include "b2Body.h"
#include "b2TimeStep.h"
class b2Contact;
class b2Joint;
class b2StackAllocator;
class b2ContactListener;
struct b2ContactConstraint;
/// This is an internal structure.
struct b2Position
{
b2Vec2 x;
float32 a;
};
/// This is an internal structure.
struct b2Velocity
{
b2Vec2 v;
float32 w;
};
/// This is an internal class.
class b2Island
{
public:
b2Island(int32 bodyCapacity, int32 contactCapacity, int32 jointCapacity,
b2StackAllocator* allocator, b2ContactListener* listener);
~b2Island();
void Clear()
{
m_bodyCount = 0;
m_contactCount = 0;
m_jointCount = 0;
}
void Solve(const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep);
void SolveTOI(const b2TimeStep& subStep, const b2Body* bodyA, const b2Body* bodyB);
void Add(b2Body* body)
{
b2Assert(m_bodyCount < m_bodyCapacity);
body->m_islandIndex = m_bodyCount;
m_bodies[m_bodyCount++] = body;
}
void Add(b2Contact* contact)
{
b2Assert(m_contactCount < m_contactCapacity);
m_contacts[m_contactCount++] = contact;
}
void Add(b2Joint* joint)
{
b2Assert(m_jointCount < m_jointCapacity);
m_joints[m_jointCount++] = joint;
}
void Report(const b2ContactConstraint* constraints);
b2StackAllocator* m_allocator;
b2ContactListener* m_listener;
b2Body** m_bodies;
b2Contact** m_contacts;
b2Joint** m_joints;
b2Position* m_positions;
b2Velocity* m_velocities;
int32 m_bodyCount;
int32 m_jointCount;
int32 m_contactCount;
int32 m_bodyCapacity;
int32 m_contactCapacity;
int32 m_jointCapacity;
};
#endif
| 412 | 0.722513 | 1 | 0.722513 | game-dev | MEDIA | 0.859809 | game-dev | 0.671416 | 1 | 0.671416 |
FreeFalcon/freefalcon-central | 1,271 | src/falclib/include/msginc/senddogfightinfo.h | #ifndef _SENDDOGFIGHTINFO_H
#define _SENDDOGFIGHTINFO_H
#include "F4vu.h"
#include "falcmesg.h"
#include "mission.h"
#include "dogfight.h"
#include "InvalidBufferException.h"
#pragma pack (1)
/*
* Message Type Send Dogfight Info
*/
class UI_SendDogfightInfo : public FalconEvent
{
public:
UI_SendDogfightInfo(VU_ID entityId, VuTargetEntity *target, VU_BOOL loopback = TRUE);
UI_SendDogfightInfo(VU_MSG_TYPE type, VU_ID senderid, VU_ID target);
~UI_SendDogfightInfo(void);
virtual int Size() const
{
return sizeof(dataBlock) + FalconEvent::Size();
};
//sfr: changed to long *
int Decode(VU_BYTE **buf, long *rem)
{
long init = *rem;
FalconEvent::Decode(buf, rem);
memcpychk(&dataBlock, buf, sizeof(dataBlock), rem);
return init - *rem;
};
int Encode(VU_BYTE **buf)
{
int size;
size = FalconEvent::Encode(buf);
memcpy(*buf, &dataBlock, sizeof(dataBlock));
*buf += sizeof(dataBlock);
size += sizeof(dataBlock);
return size;
};
class DATA_BLOCK
{
public:
VU_ID from;
VU_ID game;
DogfightClass settings;
} dataBlock;
protected:
int Process(uchar autodisp);
};
#pragma pack ()
#endif
| 412 | 0.838281 | 1 | 0.838281 | game-dev | MEDIA | 0.393236 | game-dev | 0.52556 | 1 | 0.52556 |
magefree/mage | 2,061 | Mage.Sets/src/mage/cards/g/GhituAmplifier.java | package mage.cards.g;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.EntersBattlefieldTriggeredAbility;
import mage.abilities.common.SpellCastControllerTriggeredAbility;
import mage.abilities.condition.common.KickedCondition;
import mage.abilities.effects.common.ReturnToHandTargetEffect;
import mage.abilities.effects.common.continuous.BoostSourceEffect;
import mage.abilities.keyword.KickerAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Duration;
import mage.constants.SubType;
import mage.filter.StaticFilters;
import mage.target.common.TargetOpponentsCreaturePermanent;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class GhituAmplifier extends CardImpl {
public GhituAmplifier(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{R}");
this.subtype.add(SubType.HUMAN);
this.subtype.add(SubType.WIZARD);
this.power = new MageInt(1);
this.toughness = new MageInt(2);
// Kicker {2}{U}
this.addAbility(new KickerAbility("{2}{U}"));
// When Ghitu Amplifier enters the battlefield, if it was kicked, return target creature an opponent controls to its owner's hand.
Ability ability = new EntersBattlefieldTriggeredAbility(new ReturnToHandTargetEffect()).withInterveningIf(KickedCondition.ONCE);
ability.addTarget(new TargetOpponentsCreaturePermanent());
this.addAbility(ability);
// Whenever you cast an instant or sorcery spell, Ghitu Amplifier gets +2/+0 until end of turn.
this.addAbility(new SpellCastControllerTriggeredAbility(
new BoostSourceEffect(2, 0, Duration.EndOfTurn),
StaticFilters.FILTER_SPELL_AN_INSTANT_OR_SORCERY, false
));
}
private GhituAmplifier(final GhituAmplifier card) {
super(card);
}
@Override
public GhituAmplifier copy() {
return new GhituAmplifier(this);
}
}
| 412 | 0.92634 | 1 | 0.92634 | game-dev | MEDIA | 0.967346 | game-dev | 0.996383 | 1 | 0.996383 |
coolwanglu/BrowserHack | 36,508 | src/mkmaze.c | /* SCCS Id: @(#)mkmaze.c 3.4 2002/04/04 */
/* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
/* NetHack may be freely redistributed. See license for details. */
#include "hack.h"
#include "sp_lev.h"
#include "lev.h" /* save & restore info */
/* from sp_lev.c, for fixup_special() */
extern char *lev_message;
extern lev_region *lregions;
extern int num_lregions;
STATIC_DCL boolean FDECL(iswall,(int,int));
STATIC_DCL boolean FDECL(iswall_or_stone,(int,int));
STATIC_DCL boolean FDECL(is_solid,(int,int));
STATIC_DCL int FDECL(extend_spine, (int [3][3], int, int, int));
STATIC_DCL boolean FDECL(okay,(int,int,int));
STATIC_DCL void FDECL(maze0xy,(coord *));
STATIC_DCL boolean FDECL(put_lregion_here,(XCHAR_P,XCHAR_P,XCHAR_P,
XCHAR_P,XCHAR_P,XCHAR_P,XCHAR_P,BOOLEAN_P,d_level *));
STATIC_DCL void NDECL(fixup_special);
STATIC_DCL void FDECL(move, (int *,int *,int));
STATIC_DCL void NDECL(setup_waterlevel);
STATIC_DCL void NDECL(unsetup_waterlevel);
STATIC_OVL boolean
iswall(x,y)
int x,y;
{
register int type;
if (!isok(x,y)) return FALSE;
type = levl[x][y].typ;
return (IS_WALL(type) || IS_DOOR(type) ||
type == SDOOR || type == IRONBARS);
}
STATIC_OVL boolean
iswall_or_stone(x,y)
int x,y;
{
register int type;
/* out of bounds = stone */
if (!isok(x,y)) return TRUE;
type = levl[x][y].typ;
return (type == STONE || IS_WALL(type) || IS_DOOR(type) ||
type == SDOOR || type == IRONBARS);
}
/* return TRUE if out of bounds, wall or rock */
STATIC_OVL boolean
is_solid(x,y)
int x, y;
{
return (!isok(x,y) || IS_STWALL(levl[x][y].typ));
}
/*
* Return 1 (not TRUE - we're doing bit vectors here) if we want to extend
* a wall spine in the (dx,dy) direction. Return 0 otherwise.
*
* To extend a wall spine in that direction, first there must be a wall there.
* Then, extend a spine unless the current position is surrounded by walls
* in the direction given by (dx,dy). E.g. if 'x' is our location, 'W'
* a wall, '.' a room, 'a' anything (we don't care), and our direction is
* (0,1) - South or down - then:
*
* a a a
* W x W This would not extend a spine from x down
* W W W (a corridor of walls is formed).
*
* a a a
* W x W This would extend a spine from x down.
* . W W
*/
STATIC_OVL int
extend_spine(locale, wall_there, dx, dy)
int locale[3][3];
int wall_there, dx, dy;
{
int spine, nx, ny;
nx = 1 + dx;
ny = 1 + dy;
if (wall_there) { /* wall in that direction */
if (dx) {
if (locale[ 1][0] && locale[ 1][2] && /* EW are wall/stone */
locale[nx][0] && locale[nx][2]) { /* diag are wall/stone */
spine = 0;
} else {
spine = 1;
}
} else { /* dy */
if (locale[0][ 1] && locale[2][ 1] && /* NS are wall/stone */
locale[0][ny] && locale[2][ny]) { /* diag are wall/stone */
spine = 0;
} else {
spine = 1;
}
}
} else {
spine = 0;
}
return spine;
}
/*
* Wall cleanup. This function has two purposes: (1) remove walls that
* are totally surrounded by stone - they are redundant. (2) correct
* the types so that they extend and connect to each other.
*/
void
wallification(x1, y1, x2, y2)
int x1, y1, x2, y2;
{
uchar type;
register int x,y;
struct rm *lev;
int bits;
int locale[3][3]; /* rock or wall status surrounding positions */
/*
* Value 0 represents a free-standing wall. It could be anything,
* so even though this table says VWALL, we actually leave whatever
* typ was there alone.
*/
static xchar spine_array[16] = {
VWALL, HWALL, HWALL, HWALL,
VWALL, TRCORNER, TLCORNER, TDWALL,
VWALL, BRCORNER, BLCORNER, TUWALL,
VWALL, TLWALL, TRWALL, CROSSWALL
};
/* sanity check on incoming variables */
if (x1<0 || x2>=COLNO || x1>x2 || y1<0 || y2>=ROWNO || y1>y2)
panic("wallification: bad bounds (%d,%d) to (%d,%d)",x1,y1,x2,y2);
/* Step 1: change walls surrounded by rock to rock. */
for(x = x1; x <= x2; x++)
for(y = y1; y <= y2; y++) {
lev = &levl[x][y];
type = lev->typ;
if (IS_WALL(type) && type != DBWALL) {
if (is_solid(x-1,y-1) &&
is_solid(x-1,y ) &&
is_solid(x-1,y+1) &&
is_solid(x, y-1) &&
is_solid(x, y+1) &&
is_solid(x+1,y-1) &&
is_solid(x+1,y ) &&
is_solid(x+1,y+1))
lev->typ = STONE;
}
}
/*
* Step 2: set the correct wall type. We can't combine steps
* 1 and 2 into a single sweep because we depend on knowing if
* the surrounding positions are stone.
*/
for(x = x1; x <= x2; x++)
for(y = y1; y <= y2; y++) {
lev = &levl[x][y];
type = lev->typ;
if ( !(IS_WALL(type) && type != DBWALL)) continue;
/* set the locations TRUE if rock or wall or out of bounds */
locale[0][0] = iswall_or_stone(x-1,y-1);
locale[1][0] = iswall_or_stone( x,y-1);
locale[2][0] = iswall_or_stone(x+1,y-1);
locale[0][1] = iswall_or_stone(x-1, y);
locale[2][1] = iswall_or_stone(x+1, y);
locale[0][2] = iswall_or_stone(x-1,y+1);
locale[1][2] = iswall_or_stone( x,y+1);
locale[2][2] = iswall_or_stone(x+1,y+1);
/* determine if wall should extend to each direction NSEW */
bits = (extend_spine(locale, iswall(x,y-1), 0, -1) << 3)
| (extend_spine(locale, iswall(x,y+1), 0, 1) << 2)
| (extend_spine(locale, iswall(x+1,y), 1, 0) << 1)
| extend_spine(locale, iswall(x-1,y), -1, 0);
/* don't change typ if wall is free-standing */
if (bits) lev->typ = spine_array[bits];
}
}
STATIC_OVL boolean
okay(x,y,dir)
int x,y;
register int dir;
{
move(&x,&y,dir);
move(&x,&y,dir);
if(x<3 || y<3 || x>x_maze_max || y>y_maze_max || levl[x][y].typ != 0)
return(FALSE);
return(TRUE);
}
STATIC_OVL void
maze0xy(cc) /* find random starting point for maze generation */
coord *cc;
{
cc->x = 3 + 2*rn2((x_maze_max>>1) - 1);
cc->y = 3 + 2*rn2((y_maze_max>>1) - 1);
return;
}
/*
* Bad if:
* pos is occupied OR
* pos is inside restricted region (lx,ly,hx,hy) OR
* NOT (pos is corridor and a maze level OR pos is a room OR pos is air)
*/
boolean
bad_location(x, y, lx, ly, hx, hy)
xchar x, y;
xchar lx, ly, hx, hy;
{
return((boolean)(occupied(x, y) ||
within_bounded_area(x,y, lx,ly, hx,hy) ||
!((levl[x][y].typ == CORR && level.flags.is_maze_lev) ||
levl[x][y].typ == ROOM || levl[x][y].typ == AIR)));
}
/* pick a location in area (lx, ly, hx, hy) but not in (nlx, nly, nhx, nhy) */
/* and place something (based on rtype) in that region */
void
place_lregion(lx, ly, hx, hy, nlx, nly, nhx, nhy, rtype, lev)
xchar lx, ly, hx, hy;
xchar nlx, nly, nhx, nhy;
xchar rtype;
d_level *lev;
{
int trycnt;
boolean oneshot;
xchar x, y;
if(!lx) { /* default to whole level */
/*
* if there are rooms and this a branch, let place_branch choose
* the branch location (to avoid putting branches in corridors).
*/
if(rtype == LR_BRANCH && nroom) {
place_branch(Is_branchlev(&u.uz), 0, 0);
return;
}
lx = 1; hx = COLNO-1;
ly = 1; hy = ROWNO-1;
}
/* first a probabilistic approach */
oneshot = (lx == hx && ly == hy);
for (trycnt = 0; trycnt < 200; trycnt++) {
x = rn1((hx - lx) + 1, lx);
y = rn1((hy - ly) + 1, ly);
if (put_lregion_here(x,y,nlx,nly,nhx,nhy,rtype,oneshot,lev))
return;
}
/* then a deterministic one */
oneshot = TRUE;
for (x = lx; x <= hx; x++)
for (y = ly; y <= hy; y++)
if (put_lregion_here(x,y,nlx,nly,nhx,nhy,rtype,oneshot,lev))
return;
impossible("Couldn't place lregion type %d!", rtype);
}
STATIC_OVL boolean
put_lregion_here(x,y,nlx,nly,nhx,nhy,rtype,oneshot,lev)
xchar x, y;
xchar nlx, nly, nhx, nhy;
xchar rtype;
boolean oneshot;
d_level *lev;
{
if (bad_location(x, y, nlx, nly, nhx, nhy)) {
if (!oneshot) {
return FALSE; /* caller should try again */
} else {
/* Must make do with the only location possible;
avoid failure due to a misplaced trap.
It might still fail if there's a dungeon feature here. */
struct trap *t = t_at(x,y);
if (t && t->ttyp != MAGIC_PORTAL) deltrap(t);
if (bad_location(x, y, nlx, nly, nhx, nhy)) return FALSE;
}
}
switch (rtype) {
case LR_TELE:
case LR_UPTELE:
case LR_DOWNTELE:
/* "something" means the player in this case */
if(MON_AT(x, y)) {
/* move the monster if no choice, or just try again */
if(oneshot) (void) rloc(m_at(x,y), FALSE);
else return(FALSE);
}
u_on_newpos(x, y);
break;
case LR_PORTAL:
mkportal(x, y, lev->dnum, lev->dlevel);
break;
case LR_DOWNSTAIR:
case LR_UPSTAIR:
mkstairs(x, y, (char)rtype, (struct mkroom *)0);
break;
case LR_BRANCH:
place_branch(Is_branchlev(&u.uz), x, y);
break;
}
return(TRUE);
}
static boolean was_waterlevel; /* ugh... this shouldn't be needed */
/* this is special stuff that the level compiler cannot (yet) handle */
STATIC_OVL void
fixup_special()
{
register lev_region *r = lregions;
struct d_level lev;
register int x, y;
struct mkroom *croom;
boolean added_branch = FALSE;
if (was_waterlevel) {
was_waterlevel = FALSE;
u.uinwater = 0;
unsetup_waterlevel();
} else if (Is_waterlevel(&u.uz)) {
level.flags.hero_memory = 0;
was_waterlevel = TRUE;
/* water level is an odd beast - it has to be set up
before calling place_lregions etc. */
setup_waterlevel();
}
for(x = 0; x < num_lregions; x++, r++) {
switch(r->rtype) {
case LR_BRANCH:
added_branch = TRUE;
goto place_it;
case LR_PORTAL:
if(*r->rname.str >= '0' && *r->rname.str <= '9') {
/* "chutes and ladders" */
lev = u.uz;
lev.dlevel = atoi(r->rname.str);
} else {
s_level *sp = find_level(r->rname.str);
lev = sp->dlevel;
}
/* fall into... */
case LR_UPSTAIR:
case LR_DOWNSTAIR:
place_it:
place_lregion(r->inarea.x1, r->inarea.y1,
r->inarea.x2, r->inarea.y2,
r->delarea.x1, r->delarea.y1,
r->delarea.x2, r->delarea.y2,
r->rtype, &lev);
break;
case LR_TELE:
case LR_UPTELE:
case LR_DOWNTELE:
/* save the region outlines for goto_level() */
if(r->rtype == LR_TELE || r->rtype == LR_UPTELE) {
updest.lx = r->inarea.x1; updest.ly = r->inarea.y1;
updest.hx = r->inarea.x2; updest.hy = r->inarea.y2;
updest.nlx = r->delarea.x1; updest.nly = r->delarea.y1;
updest.nhx = r->delarea.x2; updest.nhy = r->delarea.y2;
}
if(r->rtype == LR_TELE || r->rtype == LR_DOWNTELE) {
dndest.lx = r->inarea.x1; dndest.ly = r->inarea.y1;
dndest.hx = r->inarea.x2; dndest.hy = r->inarea.y2;
dndest.nlx = r->delarea.x1; dndest.nly = r->delarea.y1;
dndest.nhx = r->delarea.x2; dndest.nhy = r->delarea.y2;
}
/* place_lregion gets called from goto_level() */
break;
}
if (r->rname.str) free((genericptr_t) r->rname.str), r->rname.str = 0;
}
/* place dungeon branch if not placed above */
if (!added_branch && Is_branchlev(&u.uz)) {
place_lregion(0,0,0,0,0,0,0,0,LR_BRANCH,(d_level *)0);
}
/* KMH -- Sokoban levels */
if(In_sokoban(&u.uz))
sokoban_detect();
/* Still need to add some stuff to level file */
if (Is_medusa_level(&u.uz)) {
struct obj *otmp;
int tryct;
croom = &rooms[0]; /* only one room on the medusa level */
for (tryct = rnd(4); tryct; tryct--) {
x = somex(croom); y = somey(croom);
if (goodpos(x, y, (struct monst *)0, 0)) {
otmp = mk_tt_object(STATUE, x, y);
while (otmp && (poly_when_stoned(&mons[otmp->corpsenm]) ||
pm_resistance(&mons[otmp->corpsenm],MR_STONE))) {
otmp->corpsenm = rndmonnum();
otmp->owt = weight(otmp);
}
}
}
if (rn2(2))
otmp = mk_tt_object(STATUE, somex(croom), somey(croom));
else /* Medusa statues don't contain books */
otmp = mkcorpstat(STATUE, (struct monst *)0, (struct permonst *)0,
somex(croom), somey(croom), FALSE);
if (otmp) {
while (pm_resistance(&mons[otmp->corpsenm],MR_STONE)
|| poly_when_stoned(&mons[otmp->corpsenm])) {
otmp->corpsenm = rndmonnum();
otmp->owt = weight(otmp);
}
}
} else if(Is_wiz1_level(&u.uz)) {
croom = search_special(MORGUE);
create_secret_door(croom, W_SOUTH|W_EAST|W_WEST);
} else if(Is_knox(&u.uz)) {
/* using an unfilled morgue for rm id */
croom = search_special(MORGUE);
/* avoid inappropriate morgue-related messages */
level.flags.graveyard = level.flags.has_morgue = 0;
croom->rtype = OROOM; /* perhaps it should be set to VAULT? */
/* stock the main vault */
for(x = croom->lx; x <= croom->hx; x++)
for(y = croom->ly; y <= croom->hy; y++) {
(void) mkgold((long) rn1(300, 600), x, y);
if (!rn2(3) && !is_pool(x,y))
(void)maketrap(x, y, rn2(3) ? LANDMINE : SPIKED_PIT);
}
} else if (Role_if(PM_PRIEST) && In_quest(&u.uz)) {
/* less chance for undead corpses (lured from lower morgues) */
level.flags.graveyard = 1;
} else if (Is_stronghold(&u.uz)) {
level.flags.graveyard = 1;
} else if(Is_sanctum(&u.uz)) {
croom = search_special(TEMPLE);
create_secret_door(croom, W_ANY);
} else if(on_level(&u.uz, &orcus_level)) {
register struct monst *mtmp, *mtmp2;
/* it's a ghost town, get rid of shopkeepers */
for(mtmp = fmon; mtmp; mtmp = mtmp2) {
mtmp2 = mtmp->nmon;
if(mtmp->isshk) mongone(mtmp);
}
}
if(lev_message) {
char *str, *nl;
for(str = lev_message; (nl = index(str, '\n')) != 0; str = nl+1) {
*nl = '\0';
pline("%s", str);
}
if(*str)
pline("%s", str);
free((genericptr_t)lev_message);
lev_message = 0;
}
if (lregions)
free((genericptr_t) lregions), lregions = 0;
num_lregions = 0;
}
void
makemaz(s)
register const char *s;
{
int x,y;
char protofile[20];
s_level *sp = Is_special(&u.uz);
coord mm;
if(*s) {
if(sp && sp->rndlevs) Sprintf(protofile, "%s-%d", s,
rnd((int) sp->rndlevs));
else Strcpy(protofile, s);
} else if(*(dungeons[u.uz.dnum].proto)) {
if(dunlevs_in_dungeon(&u.uz) > 1) {
if(sp && sp->rndlevs)
Sprintf(protofile, "%s%d-%d", dungeons[u.uz.dnum].proto,
dunlev(&u.uz),
rnd((int) sp->rndlevs));
else Sprintf(protofile, "%s%d", dungeons[u.uz.dnum].proto,
dunlev(&u.uz));
} else if(sp && sp->rndlevs) {
Sprintf(protofile, "%s-%d", dungeons[u.uz.dnum].proto,
rnd((int) sp->rndlevs));
} else Strcpy(protofile, dungeons[u.uz.dnum].proto);
} else Strcpy(protofile, "");
#ifdef WIZARD
/* SPLEVTYPE format is "level-choice,level-choice"... */
if (wizard && *protofile && sp && sp->rndlevs) {
char *ep = getenv("SPLEVTYPE"); /* not nh_getenv */
if (ep) {
/* rindex always succeeds due to code in prior block */
int len = (rindex(protofile, '-') - protofile) + 1;
while (ep && *ep) {
if (!strncmp(ep, protofile, len)) {
int pick = atoi(ep + len);
/* use choice only if valid */
if (pick > 0 && pick <= (int) sp->rndlevs)
Sprintf(protofile + len, "%d", pick);
break;
} else {
ep = index(ep, ',');
if (ep) ++ep;
}
}
}
}
#endif
if(*protofile) {
Strcat(protofile, LEV_EXT);
if(load_special(protofile)) {
fixup_special();
/* some levels can end up with monsters
on dead mon list, including light source monsters */
dmonsfree();
return; /* no mazification right now */
}
impossible("Couldn't load \"%s\" - making a maze.", protofile);
}
level.flags.is_maze_lev = TRUE;
#ifndef WALLIFIED_MAZE
for(x = 2; x < x_maze_max; x++)
for(y = 2; y < y_maze_max; y++)
levl[x][y].typ = STONE;
#else
for(x = 2; x <= x_maze_max; x++)
for(y = 2; y <= y_maze_max; y++)
levl[x][y].typ = ((x % 2) && (y % 2)) ? STONE : HWALL;
#endif
maze0xy(&mm);
walkfrom((int) mm.x, (int) mm.y);
/* put a boulder at the maze center */
(void) mksobj_at(BOULDER, (int) mm.x, (int) mm.y, TRUE, FALSE);
#ifdef WALLIFIED_MAZE
wallification(2, 2, x_maze_max, y_maze_max);
#endif
mazexy(&mm);
mkstairs(mm.x, mm.y, 1, (struct mkroom *)0); /* up */
if (!Invocation_lev(&u.uz)) {
mazexy(&mm);
mkstairs(mm.x, mm.y, 0, (struct mkroom *)0); /* down */
} else { /* choose "vibrating square" location */
#define x_maze_min 2
#define y_maze_min 2
/*
* Pick a position where the stairs down to Moloch's Sanctum
* level will ultimately be created. At that time, an area
* will be altered: walls removed, moat and traps generated,
* boulders destroyed. The position picked here must ensure
* that that invocation area won't extend off the map.
*
* We actually allow up to 2 squares around the usual edge of
* the area to get truncated; see mkinvokearea(mklev.c).
*/
#define INVPOS_X_MARGIN (6 - 2)
#define INVPOS_Y_MARGIN (5 - 2)
#define INVPOS_DISTANCE 11
int x_range = x_maze_max - x_maze_min - 2*INVPOS_X_MARGIN - 1,
y_range = y_maze_max - y_maze_min - 2*INVPOS_Y_MARGIN - 1;
#ifdef DEBUG
if (x_range <= INVPOS_X_MARGIN || y_range <= INVPOS_Y_MARGIN ||
(x_range * y_range) <= (INVPOS_DISTANCE * INVPOS_DISTANCE))
panic("inv_pos: maze is too small! (%d x %d)",
x_maze_max, y_maze_max);
#endif
inv_pos.x = inv_pos.y = 0; /*{occupied() => invocation_pos()}*/
do {
x = rn1(x_range, x_maze_min + INVPOS_X_MARGIN + 1);
y = rn1(y_range, y_maze_min + INVPOS_Y_MARGIN + 1);
/* we don't want it to be too near the stairs, nor
to be on a spot that's already in use (wall|trap) */
} while (x == xupstair || y == yupstair || /*(direct line)*/
abs(x - xupstair) == abs(y - yupstair) ||
distmin(x, y, xupstair, yupstair) <= INVPOS_DISTANCE ||
!SPACE_POS(levl[x][y].typ) || occupied(x, y));
inv_pos.x = x;
inv_pos.y = y;
#undef INVPOS_X_MARGIN
#undef INVPOS_Y_MARGIN
#undef INVPOS_DISTANCE
#undef x_maze_min
#undef y_maze_min
}
/* place branch stair or portal */
place_branch(Is_branchlev(&u.uz), 0, 0);
for(x = rn1(8,11); x; x--) {
mazexy(&mm);
(void) mkobj_at(rn2(2) ? GEM_CLASS : 0, mm.x, mm.y, TRUE);
}
for(x = rn1(10,2); x; x--) {
mazexy(&mm);
(void) mksobj_at(BOULDER, mm.x, mm.y, TRUE, FALSE);
}
for (x = rn2(3); x; x--) {
mazexy(&mm);
(void) makemon(&mons[PM_MINOTAUR], mm.x, mm.y, NO_MM_FLAGS);
}
for(x = rn1(5,7); x; x--) {
mazexy(&mm);
(void) makemon((struct permonst *) 0, mm.x, mm.y, NO_MM_FLAGS);
}
for(x = rn1(6,7); x; x--) {
mazexy(&mm);
(void) mkgold(0L,mm.x,mm.y);
}
for(x = rn1(6,7); x; x--)
mktrap(0,1,(struct mkroom *) 0, (coord*) 0);
}
#ifdef MICRO
/* Make the mazewalk iterative by faking a stack. This is needed to
* ensure the mazewalk is successful in the limited stack space of
* the program. This iterative version uses the minimum amount of stack
* that is totally safe.
*/
void
walkfrom(x,y)
int x,y;
{
#define CELLS (ROWNO * COLNO) / 4 /* a maze cell is 4 squares */
char mazex[CELLS + 1], mazey[CELLS + 1]; /* char's are OK */
int q, a, dir, pos;
int dirs[4];
pos = 1;
mazex[pos] = (char) x;
mazey[pos] = (char) y;
while (pos) {
x = (int) mazex[pos];
y = (int) mazey[pos];
if(!IS_DOOR(levl[x][y].typ)) {
/* might still be on edge of MAP, so don't overwrite */
#ifndef WALLIFIED_MAZE
levl[x][y].typ = CORR;
#else
levl[x][y].typ = ROOM;
#endif
levl[x][y].flags = 0;
}
q = 0;
for (a = 0; a < 4; a++)
if(okay(x, y, a)) dirs[q++]= a;
if (!q)
pos--;
else {
dir = dirs[rn2(q)];
move(&x, &y, dir);
#ifndef WALLIFIED_MAZE
levl[x][y].typ = CORR;
#else
levl[x][y].typ = ROOM;
#endif
move(&x, &y, dir);
pos++;
if (pos > CELLS)
panic("Overflow in walkfrom");
mazex[pos] = (char) x;
mazey[pos] = (char) y;
}
}
}
#else
void
walkfrom(x,y)
int x,y;
{
register int q,a,dir;
int dirs[4];
if(!IS_DOOR(levl[x][y].typ)) {
/* might still be on edge of MAP, so don't overwrite */
#ifndef WALLIFIED_MAZE
levl[x][y].typ = CORR;
#else
levl[x][y].typ = ROOM;
#endif
levl[x][y].flags = 0;
}
while(1) {
q = 0;
for(a = 0; a < 4; a++)
if(okay(x,y,a)) dirs[q++]= a;
if(!q) return;
dir = dirs[rn2(q)];
move(&x,&y,dir);
#ifndef WALLIFIED_MAZE
levl[x][y].typ = CORR;
#else
levl[x][y].typ = ROOM;
#endif
move(&x,&y,dir);
walkfrom(x,y);
}
}
#endif /* MICRO */
STATIC_OVL void
move(x,y,dir)
register int *x, *y;
register int dir;
{
switch(dir){
case 0: --(*y); break;
case 1: (*x)++; break;
case 2: (*y)++; break;
case 3: --(*x); break;
default: panic("move: bad direction");
}
}
void
mazexy(cc) /* find random point in generated corridors,
so we don't create items in moats, bunkers, or walls */
coord *cc;
{
int cpt=0;
do {
cc->x = 3 + 2*rn2((x_maze_max>>1) - 1);
cc->y = 3 + 2*rn2((y_maze_max>>1) - 1);
cpt++;
} while (cpt < 100 && levl[cc->x][cc->y].typ !=
#ifdef WALLIFIED_MAZE
ROOM
#else
CORR
#endif
);
if (cpt >= 100) {
register int x, y;
/* last try */
for (x = 0; x < (x_maze_max>>1) - 1; x++)
for (y = 0; y < (y_maze_max>>1) - 1; y++) {
cc->x = 3 + 2 * x;
cc->y = 3 + 2 * y;
if (levl[cc->x][cc->y].typ ==
#ifdef WALLIFIED_MAZE
ROOM
#else
CORR
#endif
) return;
}
panic("mazexy: can't find a place!");
}
return;
}
void
bound_digging()
/* put a non-diggable boundary around the initial portion of a level map.
* assumes that no level will initially put things beyond the isok() range.
*
* we can't bound unconditionally on the last line with something in it,
* because that something might be a niche which was already reachable,
* so the boundary would be breached
*
* we can't bound unconditionally on one beyond the last line, because
* that provides a window of abuse for WALLIFIED_MAZE special levels
*/
{
register int x,y;
register unsigned typ;
register struct rm *lev;
boolean found, nonwall;
int xmin,xmax,ymin,ymax;
if(Is_earthlevel(&u.uz)) return; /* everything diggable here */
found = nonwall = FALSE;
for(xmin=0; !found; xmin++) {
lev = &levl[xmin][0];
for(y=0; y<=ROWNO-1; y++, lev++) {
typ = lev->typ;
if(typ != STONE) {
found = TRUE;
if(!IS_WALL(typ)) nonwall = TRUE;
}
}
}
xmin -= (nonwall || !level.flags.is_maze_lev) ? 2 : 1;
if (xmin < 0) xmin = 0;
found = nonwall = FALSE;
for(xmax=COLNO-1; !found; xmax--) {
lev = &levl[xmax][0];
for(y=0; y<=ROWNO-1; y++, lev++) {
typ = lev->typ;
if(typ != STONE) {
found = TRUE;
if(!IS_WALL(typ)) nonwall = TRUE;
}
}
}
xmax += (nonwall || !level.flags.is_maze_lev) ? 2 : 1;
if (xmax >= COLNO) xmax = COLNO-1;
found = nonwall = FALSE;
for(ymin=0; !found; ymin++) {
lev = &levl[xmin][ymin];
for(x=xmin; x<=xmax; x++, lev += ROWNO) {
typ = lev->typ;
if(typ != STONE) {
found = TRUE;
if(!IS_WALL(typ)) nonwall = TRUE;
}
}
}
ymin -= (nonwall || !level.flags.is_maze_lev) ? 2 : 1;
found = nonwall = FALSE;
for(ymax=ROWNO-1; !found; ymax--) {
lev = &levl[xmin][ymax];
for(x=xmin; x<=xmax; x++, lev += ROWNO) {
typ = lev->typ;
if(typ != STONE) {
found = TRUE;
if(!IS_WALL(typ)) nonwall = TRUE;
}
}
}
ymax += (nonwall || !level.flags.is_maze_lev) ? 2 : 1;
for (x = 0; x < COLNO; x++)
for (y = 0; y < ROWNO; y++)
if (y <= ymin || y >= ymax || x <= xmin || x >= xmax) {
#ifdef DCC30_BUG
lev = &levl[x][y];
lev->wall_info |= W_NONDIGGABLE;
#else
levl[x][y].wall_info |= W_NONDIGGABLE;
#endif
}
}
void
mkportal(x, y, todnum, todlevel)
register xchar x, y, todnum, todlevel;
{
/* a portal "trap" must be matched by a */
/* portal in the destination dungeon/dlevel */
register struct trap *ttmp = maketrap(x, y, MAGIC_PORTAL);
if (!ttmp) {
impossible("portal on top of portal??");
return;
}
#ifdef DEBUG
pline("mkportal: at (%d,%d), to %s, level %d",
x, y, dungeons[todnum].dname, todlevel);
#endif
ttmp->dst.dnum = todnum;
ttmp->dst.dlevel = todlevel;
return;
}
/*
* Special waterlevel stuff in endgame (TH).
*
* Some of these functions would probably logically belong to some
* other source files, but they are all so nicely encapsulated here.
*/
/* to ease the work of debuggers at this stage */
#define register
#define CONS_OBJ 0
#define CONS_MON 1
#define CONS_HERO 2
#define CONS_TRAP 3
static struct bubble *bbubbles, *ebubbles;
static struct trap *wportal;
static int xmin, ymin, xmax, ymax; /* level boundaries */
/* bubble movement boundaries */
#define bxmin (xmin + 1)
#define bymin (ymin + 1)
#define bxmax (xmax - 1)
#define bymax (ymax - 1)
STATIC_DCL void NDECL(set_wportal);
STATIC_DCL void FDECL(mk_bubble, (int,int,int));
STATIC_DCL void FDECL(mv_bubble, (struct bubble *,int,int,BOOLEAN_P));
void
movebubbles()
{
static boolean up;
register struct bubble *b;
register int x, y, i, j;
struct trap *btrap;
static const struct rm water_pos =
{ cmap_to_glyph(S_water), WATER, 0, 0, 0, 0, 0, 0, 0 };
/* set up the portal the first time bubbles are moved */
if (!wportal) set_wportal();
vision_recalc(2);
/* keep attached ball&chain separate from bubble objects */
if (Punished) unplacebc();
/*
* Pick up everything inside of a bubble then fill all bubble
* locations.
*/
for (b = up ? bbubbles : ebubbles; b; b = up ? b->next : b->prev) {
if (b->cons) panic("movebubbles: cons != null");
for (i = 0, x = b->x; i < (int) b->bm[0]; i++, x++)
for (j = 0, y = b->y; j < (int) b->bm[1]; j++, y++)
if (b->bm[j + 2] & (1 << i)) {
if (!isok(x,y)) {
impossible("movebubbles: bad pos (%d,%d)", x,y);
continue;
}
/* pick up objects, monsters, hero, and traps */
if (OBJ_AT(x,y)) {
struct obj *olist = (struct obj *) 0, *otmp;
struct container *cons = (struct container *)
alloc(sizeof(struct container));
while ((otmp = level.objects[x][y]) != 0) {
remove_object(otmp);
otmp->ox = otmp->oy = 0;
otmp->nexthere = olist;
olist = otmp;
}
cons->x = x;
cons->y = y;
cons->what = CONS_OBJ;
cons->list = (genericptr_t) olist;
cons->next = b->cons;
b->cons = cons;
}
if (MON_AT(x,y)) {
struct monst *mon = m_at(x,y);
struct container *cons = (struct container *)
alloc(sizeof(struct container));
cons->x = x;
cons->y = y;
cons->what = CONS_MON;
cons->list = (genericptr_t) mon;
cons->next = b->cons;
b->cons = cons;
if(mon->wormno)
remove_worm(mon);
else
remove_monster(x, y);
newsym(x,y); /* clean up old position */
mon->mx = mon->my = 0;
}
if (!u.uswallow && x == u.ux && y == u.uy) {
struct container *cons = (struct container *)
alloc(sizeof(struct container));
cons->x = x;
cons->y = y;
cons->what = CONS_HERO;
cons->list = (genericptr_t) 0;
cons->next = b->cons;
b->cons = cons;
}
if ((btrap = t_at(x,y)) != 0) {
struct container *cons = (struct container *)
alloc(sizeof(struct container));
cons->x = x;
cons->y = y;
cons->what = CONS_TRAP;
cons->list = (genericptr_t) btrap;
cons->next = b->cons;
b->cons = cons;
}
levl[x][y] = water_pos;
block_point(x,y);
}
}
/*
* Every second time traverse down. This is because otherwise
* all the junk that changes owners when bubbles overlap
* would eventually end up in the last bubble in the chain.
*/
up = !up;
for (b = up ? bbubbles : ebubbles; b; b = up ? b->next : b->prev) {
register int rx = rn2(3), ry = rn2(3);
mv_bubble(b,b->dx + 1 - (!b->dx ? rx : (rx ? 1 : 0)),
b->dy + 1 - (!b->dy ? ry : (ry ? 1 : 0)),
FALSE);
}
/* put attached ball&chain back */
if (Punished) placebc();
vision_full_recalc = 1;
}
/* when moving in water, possibly (1 in 3) alter the intended destination */
void
water_friction()
{
register int x, y, dx, dy;
register boolean eff = FALSE;
if (Swimming && rn2(4))
return; /* natural swimmers have advantage */
if (u.dx && !rn2(!u.dy ? 3 : 6)) { /* 1/3 chance or half that */
/* cancel delta x and choose an arbitrary delta y value */
x = u.ux;
do {
dy = rn2(3) - 1; /* -1, 0, 1 */
y = u.uy + dy;
} while (dy && (!isok(x,y) || !is_pool(x,y)));
u.dx = 0;
u.dy = dy;
eff = TRUE;
} else if (u.dy && !rn2(!u.dx ? 3 : 5)) { /* 1/3 or 1/5*(5/6) */
/* cancel delta y and choose an arbitrary delta x value */
y = u.uy;
do {
dx = rn2(3) - 1; /* -1 .. 1 */
x = u.ux + dx;
} while (dx && (!isok(x,y) || !is_pool(x,y)));
u.dy = 0;
u.dx = dx;
eff = TRUE;
}
if (eff) pline("Water turbulence affects your movements.");
}
void
save_waterlevel(fd, mode)
int fd, mode;
{
register struct bubble *b;
if (!Is_waterlevel(&u.uz)) return;
if (perform_bwrite(mode)) {
int n = 0;
for (b = bbubbles; b; b = b->next) ++n;
bwrite(fd, (genericptr_t)&n, sizeof (int));
bwrite(fd, (genericptr_t)&xmin, sizeof (int));
bwrite(fd, (genericptr_t)&ymin, sizeof (int));
bwrite(fd, (genericptr_t)&xmax, sizeof (int));
bwrite(fd, (genericptr_t)&ymax, sizeof (int));
for (b = bbubbles; b; b = b->next)
bwrite(fd, (genericptr_t)b, sizeof (struct bubble));
}
if (release_data(mode))
unsetup_waterlevel();
}
void
restore_waterlevel(fd)
register int fd;
{
register struct bubble *b = (struct bubble *)0, *btmp;
register int i;
int n;
if (!Is_waterlevel(&u.uz)) return;
set_wportal();
mread(fd,(genericptr_t)&n,sizeof(int));
mread(fd,(genericptr_t)&xmin,sizeof(int));
mread(fd,(genericptr_t)&ymin,sizeof(int));
mread(fd,(genericptr_t)&xmax,sizeof(int));
mread(fd,(genericptr_t)&ymax,sizeof(int));
for (i = 0; i < n; i++) {
btmp = b;
b = (struct bubble *)alloc(sizeof(struct bubble));
mread(fd,(genericptr_t)b,sizeof(struct bubble));
if (bbubbles) {
btmp->next = b;
b->prev = btmp;
} else {
bbubbles = b;
b->prev = (struct bubble *)0;
}
mv_bubble(b,0,0,TRUE);
}
ebubbles = b;
b->next = (struct bubble *)0;
was_waterlevel = TRUE;
}
const char *waterbody_name(x, y)
xchar x,y;
{
register struct rm *lev;
schar ltyp;
if (!isok(x,y))
return "drink"; /* should never happen */
lev = &levl[x][y];
ltyp = lev->typ;
if (is_lava(x,y))
return "lava";
else if (ltyp == ICE ||
(ltyp == DRAWBRIDGE_UP &&
(levl[x][y].drawbridgemask & DB_UNDER) == DB_ICE))
return "ice";
else if (((ltyp != POOL) && (ltyp != WATER) &&
!Is_medusa_level(&u.uz) && !Is_waterlevel(&u.uz) && !Is_juiblex_level(&u.uz)) ||
(ltyp == DRAWBRIDGE_UP && (levl[x][y].drawbridgemask & DB_UNDER) == DB_MOAT))
return "moat";
else if ((ltyp != POOL) && (ltyp != WATER) && Is_juiblex_level(&u.uz))
return "swamp";
else if (ltyp == POOL)
return "pool of water";
else return "water";
}
STATIC_OVL void
set_wportal()
{
/* there better be only one magic portal on water level... */
for (wportal = ftrap; wportal; wportal = wportal->ntrap)
if (wportal->ttyp == MAGIC_PORTAL) return;
impossible("set_wportal(): no portal!");
}
STATIC_OVL void
setup_waterlevel()
{
register int x, y;
register int xskip, yskip;
register int water_glyph = cmap_to_glyph(S_water);
/* ouch, hardcoded... */
xmin = 3;
ymin = 1;
xmax = 78;
ymax = 20;
/* set hero's memory to water */
for (x = xmin; x <= xmax; x++)
for (y = ymin; y <= ymax; y++)
levl[x][y].glyph = water_glyph;
/* make bubbles */
xskip = 10 + rn2(10);
yskip = 4 + rn2(4);
for (x = bxmin; x <= bxmax; x += xskip)
for (y = bymin; y <= bymax; y += yskip)
mk_bubble(x,y,rn2(7));
}
STATIC_OVL void
unsetup_waterlevel()
{
register struct bubble *b, *bb;
/* free bubbles */
for (b = bbubbles; b; b = bb) {
bb = b->next;
free((genericptr_t)b);
}
bbubbles = ebubbles = (struct bubble *)0;
}
STATIC_OVL void
mk_bubble(x,y,n)
register int x, y, n;
{
/*
* These bit masks make visually pleasing bubbles on a normal aspect
* 25x80 terminal, which naturally results in them being mathematically
* anything but symmetric. For this reason they cannot be computed
* in situ, either. The first two elements tell the dimensions of
* the bubble's bounding box.
*/
static uchar
bm2[] = {2,1,0x3},
bm3[] = {3,2,0x7,0x7},
bm4[] = {4,3,0x6,0xf,0x6},
bm5[] = {5,3,0xe,0x1f,0xe},
bm6[] = {6,4,0x1e,0x3f,0x3f,0x1e},
bm7[] = {7,4,0x3e,0x7f,0x7f,0x3e},
bm8[] = {8,4,0x7e,0xff,0xff,0x7e},
*bmask[] = {bm2,bm3,bm4,bm5,bm6,bm7,bm8};
register struct bubble *b;
if (x >= bxmax || y >= bymax) return;
if (n >= SIZE(bmask)) {
impossible("n too large (mk_bubble)");
n = SIZE(bmask) - 1;
}
b = (struct bubble *)alloc(sizeof(struct bubble));
if ((x + (int) bmask[n][0] - 1) > bxmax) x = bxmax - bmask[n][0] + 1;
if ((y + (int) bmask[n][1] - 1) > bymax) y = bymax - bmask[n][1] + 1;
b->x = x;
b->y = y;
b->dx = 1 - rn2(3);
b->dy = 1 - rn2(3);
b->bm = bmask[n];
b->cons = 0;
if (!bbubbles) bbubbles = b;
if (ebubbles) {
ebubbles->next = b;
b->prev = ebubbles;
}
else
b->prev = (struct bubble *)0;
b->next = (struct bubble *)0;
ebubbles = b;
mv_bubble(b,0,0,TRUE);
}
/*
* The player, the portal and all other objects and monsters
* float along with their associated bubbles. Bubbles may overlap
* freely, and the contents may get associated with other bubbles in
* the process. Bubbles are "sticky", meaning that if the player is
* in the immediate neighborhood of one, he/she may get sucked inside.
* This property also makes leaving a bubble slightly difficult.
*/
STATIC_OVL void
mv_bubble(b,dx,dy,ini)
register struct bubble *b;
register int dx, dy;
register boolean ini;
{
register int x, y, i, j, colli = 0;
struct container *cons, *ctemp;
/* move bubble */
if (dx < -1 || dx > 1 || dy < -1 || dy > 1) {
/* pline("mv_bubble: dx = %d, dy = %d", dx, dy); */
dx = sgn(dx);
dy = sgn(dy);
}
/*
* collision with level borders?
* 1 = horizontal border, 2 = vertical, 3 = corner
*/
if (b->x <= bxmin) colli |= 2;
if (b->y <= bymin) colli |= 1;
if ((int) (b->x + b->bm[0] - 1) >= bxmax) colli |= 2;
if ((int) (b->y + b->bm[1] - 1) >= bymax) colli |= 1;
if (b->x < bxmin) {
pline("bubble xmin: x = %d, xmin = %d", b->x, bxmin);
b->x = bxmin;
}
if (b->y < bymin) {
pline("bubble ymin: y = %d, ymin = %d", b->y, bymin);
b->y = bymin;
}
if ((int) (b->x + b->bm[0] - 1) > bxmax) {
pline("bubble xmax: x = %d, xmax = %d",
b->x + b->bm[0] - 1, bxmax);
b->x = bxmax - b->bm[0] + 1;
}
if ((int) (b->y + b->bm[1] - 1) > bymax) {
pline("bubble ymax: y = %d, ymax = %d",
b->y + b->bm[1] - 1, bymax);
b->y = bymax - b->bm[1] + 1;
}
/* bounce if we're trying to move off the border */
if (b->x == bxmin && dx < 0) dx = -dx;
if (b->x + b->bm[0] - 1 == bxmax && dx > 0) dx = -dx;
if (b->y == bymin && dy < 0) dy = -dy;
if (b->y + b->bm[1] - 1 == bymax && dy > 0) dy = -dy;
b->x += dx;
b->y += dy;
/* void positions inside bubble */
for (i = 0, x = b->x; i < (int) b->bm[0]; i++, x++)
for (j = 0, y = b->y; j < (int) b->bm[1]; j++, y++)
if (b->bm[j + 2] & (1 << i)) {
levl[x][y].typ = AIR;
levl[x][y].lit = 1;
unblock_point(x,y);
}
/* replace contents of bubble */
for (cons = b->cons; cons; cons = ctemp) {
ctemp = cons->next;
cons->x += dx;
cons->y += dy;
switch(cons->what) {
case CONS_OBJ: {
struct obj *olist, *otmp;
for (olist=(struct obj *)cons->list; olist; olist=otmp) {
otmp = olist->nexthere;
place_object(olist, cons->x, cons->y);
}
break;
}
case CONS_MON: {
struct monst *mon = (struct monst *) cons->list;
(void) mnearto(mon, cons->x, cons->y, TRUE);
break;
}
case CONS_HERO: {
int ux0 = u.ux, uy0 = u.uy;
/* change u.ux0 and u.uy0? */
u.ux = cons->x;
u.uy = cons->y;
newsym(ux0, uy0); /* clean up old position */
if (MON_AT(cons->x, cons->y)) {
mnexto(m_at(cons->x,cons->y));
}
break;
}
case CONS_TRAP: {
struct trap *btrap = (struct trap *) cons->list;
btrap->tx = cons->x;
btrap->ty = cons->y;
break;
}
default:
impossible("mv_bubble: unknown bubble contents");
break;
}
free((genericptr_t)cons);
}
b->cons = 0;
/* boing? */
switch (colli) {
case 1: b->dy = -b->dy; break;
case 3: b->dy = -b->dy; /* fall through */
case 2: b->dx = -b->dx; break;
default:
/* sometimes alter direction for fun anyway
(higher probability for stationary bubbles) */
if (!ini && ((b->dx || b->dy) ? !rn2(20) : !rn2(5))) {
b->dx = 1 - rn2(3);
b->dy = 1 - rn2(3);
}
}
}
/*mkmaze.c*/
| 412 | 0.986032 | 1 | 0.986032 | game-dev | MEDIA | 0.422669 | game-dev,graphics-rendering | 0.993572 | 1 | 0.993572 |
bevyengine/bevy | 8,439 | crates/bevy_time/src/common_conditions.rs | use crate::{Real, Time, Timer, TimerMode, Virtual};
use bevy_ecs::system::Res;
use core::time::Duration;
/// Run condition that is active on a regular time interval, using [`Time`] to advance
/// the timer. The timer ticks at the rate of [`Time::relative_speed`].
///
/// ```no_run
/// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, PluginGroup, Update};
/// # use bevy_ecs::schedule::IntoScheduleConfigs;
/// # use core::time::Duration;
/// # use bevy_time::common_conditions::on_timer;
/// fn main() {
/// App::new()
/// .add_plugins(DefaultPlugins)
/// .add_systems(
/// Update,
/// tick.run_if(on_timer(Duration::from_secs(1))),
/// )
/// .run();
/// }
/// fn tick() {
/// // ran once a second
/// }
/// ```
///
/// Note that this does **not** guarantee that systems will run at exactly the
/// specified interval. If delta time is larger than the specified `duration` then
/// the system will only run once even though the timer may have completed multiple
/// times. This condition should only be used with large time durations (relative to
/// delta time).
///
/// For more accurate timers, use the [`Timer`] class directly (see
/// [`Timer::times_finished_this_tick`] to address the problem mentioned above), or
/// use fixed timesteps that allow systems to run multiple times per frame.
pub fn on_timer(duration: Duration) -> impl FnMut(Res<Time>) -> bool + Clone {
let mut timer = Timer::new(duration, TimerMode::Repeating);
move |time: Res<Time>| {
timer.tick(time.delta());
timer.just_finished()
}
}
/// Run condition that is active on a regular time interval,
/// using [`Time<Real>`] to advance the timer.
/// The timer ticks are not scaled.
///
/// ```no_run
/// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, PluginGroup, Update};
/// # use bevy_ecs::schedule::IntoScheduleConfigs;
/// # use core::time::Duration;
/// # use bevy_time::common_conditions::on_real_timer;
/// fn main() {
/// App::new()
/// .add_plugins(DefaultPlugins)
/// .add_systems(
/// Update,
/// tick.run_if(on_real_timer(Duration::from_secs(1))),
/// )
/// .run();
/// }
/// fn tick() {
/// // ran once a second
/// }
/// ```
///
/// Note that this does **not** guarantee that systems will run at exactly the
/// specified interval. If delta time is larger than the specified `duration` then
/// the system will only run once even though the timer may have completed multiple
/// times. This condition should only be used with large time durations (relative to
/// delta time).
///
/// For more accurate timers, use the [`Timer`] class directly (see
/// [`Timer::times_finished_this_tick`] to address the problem mentioned above), or
/// use fixed timesteps that allow systems to run multiple times per frame.
pub fn on_real_timer(duration: Duration) -> impl FnMut(Res<Time<Real>>) -> bool + Clone {
let mut timer = Timer::new(duration, TimerMode::Repeating);
move |time: Res<Time<Real>>| {
timer.tick(time.delta());
timer.just_finished()
}
}
/// Run condition that is active *once* after the specified delay,
/// using [`Time`] to advance the timer.
/// The timer ticks at the rate of [`Time::relative_speed`].
///
/// ```rust,no_run
/// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, PluginGroup, Update};
/// # use bevy_ecs::schedule::IntoScheduleConfigs;
/// # use core::time::Duration;
/// # use bevy_time::common_conditions::once_after_delay;
/// fn main() {
/// App::new()
/// .add_plugins(DefaultPlugins)
/// .add_systems(
/// Update,
/// tick.run_if(once_after_delay(Duration::from_secs(1))),
/// )
/// .run();
/// }
/// fn tick() {
/// // ran once, after a second
/// }
/// ```
pub fn once_after_delay(duration: Duration) -> impl FnMut(Res<Time>) -> bool + Clone {
let mut timer = Timer::new(duration, TimerMode::Once);
move |time: Res<Time>| {
timer.tick(time.delta());
timer.just_finished()
}
}
/// Run condition that is active *once* after the specified delay,
/// using [`Time<Real>`] to advance the timer.
/// The timer ticks are not scaled.
///
/// ```rust,no_run
/// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, PluginGroup, Update};
/// # use bevy_ecs::schedule::IntoScheduleConfigs;
/// # use core::time::Duration;
/// # use bevy_time::common_conditions::once_after_delay;
/// fn main() {
/// App::new()
/// .add_plugins(DefaultPlugins)
/// .add_systems(
/// Update,
/// tick.run_if(once_after_delay(Duration::from_secs(1))),
/// )
/// .run();
/// }
/// fn tick() {
/// // ran once, after a second
/// }
/// ```
pub fn once_after_real_delay(duration: Duration) -> impl FnMut(Res<Time<Real>>) -> bool + Clone {
let mut timer = Timer::new(duration, TimerMode::Once);
move |time: Res<Time<Real>>| {
timer.tick(time.delta());
timer.just_finished()
}
}
/// Run condition that is active *indefinitely* after the specified delay,
/// using [`Time`] to advance the timer.
/// The timer ticks at the rate of [`Time::relative_speed`].
///
/// ```rust,no_run
/// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, PluginGroup, Update};
/// # use bevy_ecs::schedule::IntoScheduleConfigs;
/// # use core::time::Duration;
/// # use bevy_time::common_conditions::repeating_after_delay;
/// fn main() {
/// App::new()
/// .add_plugins(DefaultPlugins)
/// .add_systems(
/// Update,
/// tick.run_if(repeating_after_delay(Duration::from_secs(1))),
/// )
/// .run();
/// }
/// fn tick() {
/// // ran every frame, after a second
/// }
/// ```
pub fn repeating_after_delay(duration: Duration) -> impl FnMut(Res<Time>) -> bool + Clone {
let mut timer = Timer::new(duration, TimerMode::Once);
move |time: Res<Time>| {
timer.tick(time.delta());
timer.is_finished()
}
}
/// Run condition that is active *indefinitely* after the specified delay,
/// using [`Time<Real>`] to advance the timer.
/// The timer ticks are not scaled.
///
/// ```rust,no_run
/// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, PluginGroup, Update};
/// # use bevy_ecs::schedule::IntoScheduleConfigs;
/// # use core::time::Duration;
/// # use bevy_time::common_conditions::repeating_after_real_delay;
/// fn main() {
/// App::new()
/// .add_plugins(DefaultPlugins)
/// .add_systems(
/// Update,
/// tick.run_if(repeating_after_real_delay(Duration::from_secs(1))),
/// )
/// .run();
/// }
/// fn tick() {
/// // ran every frame, after a second
/// }
/// ```
pub fn repeating_after_real_delay(
duration: Duration,
) -> impl FnMut(Res<Time<Real>>) -> bool + Clone {
let mut timer = Timer::new(duration, TimerMode::Once);
move |time: Res<Time<Real>>| {
timer.tick(time.delta());
timer.is_finished()
}
}
/// Run condition that is active when the [`Time<Virtual>`] clock is paused.
/// Use [`bevy_ecs::schedule::common_conditions::not`] to make it active when
/// it's not paused.
///
/// ```rust,no_run
/// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, PluginGroup, Update};
/// # use bevy_ecs::schedule::{common_conditions::not, IntoScheduleConfigs};
/// # use bevy_time::common_conditions::paused;
/// fn main() {
/// App::new()
/// .add_plugins(DefaultPlugins)
/// .add_systems(
/// Update,
/// (
/// is_paused.run_if(paused),
/// not_paused.run_if(not(paused)),
/// )
/// )
/// .run();
/// }
/// fn is_paused() {
/// // ran when time is paused
/// }
///
/// fn not_paused() {
/// // ran when time is not paused
/// }
/// ```
pub fn paused(time: Res<Time<Virtual>>) -> bool {
time.is_paused()
}
#[cfg(test)]
mod tests {
use super::*;
use bevy_ecs::schedule::{IntoScheduleConfigs, Schedule};
fn test_system() {}
// Ensure distributive_run_if compiles with the common conditions.
#[test]
fn distributive_run_if_compiles() {
Schedule::default().add_systems(
(test_system, test_system)
.distributive_run_if(on_timer(Duration::new(1, 0)))
.distributive_run_if(paused),
);
}
}
| 412 | 0.820384 | 1 | 0.820384 | game-dev | MEDIA | 0.433202 | game-dev | 0.923052 | 1 | 0.923052 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.