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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
rpgboss/rpgboss | 5,545 | core/src/test/scala/rpgboss/model/battle/BattleSpec.scala | package rpgboss.model.battle
import rpgboss._
import rpgboss.model._
import rpgboss.model.battle._
object BattleTest {
class BattleFixture(aiOpt: Option[BattleAI] = None) {
val pData = ProjectData("fake-uuid", "fake-title")
val characterFast =
Character(progressions = StatProgressions(spd = Curve(10, 2)))
val characterSlow =
Character(progressions = StatProgressions(spd = Curve(4, 2)))
val enemyMedium =
Enemy(spd = 8)
pData.enums.characters = Array(characterFast, characterSlow)
pData.enums.enemies = Array(enemyMedium)
def encounter =
Encounter(units = Array(EncounterUnit(0, 100, 100)))
def initialCharacterHps = Array(1, 1)
val battle = new Battle(
pData = pData,
partyIds = Array(0, 1),
PartyParameters(
characterLevels = Array(1, 1),
initialCharacterHps = initialCharacterHps,
initialCharacterMps = Array(1, 1),
characterEquip = Array(Array(), Array()),
initialCharacterTempStatusEffectIds = Array(Array(), Array()),
learnedSkills = Array(Array(), Array()),
characterRows = Array(0, 0)),
encounter = encounter,
aiOpt = aiOpt)
}
}
class BattleSpec extends UnitSpec {
"Battle" should "make fastest unit go first" in {
val f = new BattleTest.BattleFixture
f.battle.readyEntity should be ('isDefined)
f.battle.readyEntity.get.entityType should equal (BattleEntityType.Party)
f.battle.readyEntity.get.entityId should equal (0)
f.battle.takeAction(NullAction(f.battle.partyStatus(0)))
f.battle.readyEntity should equal (None)
}
"Battle" should "have battle units act in order of speed" in {
val f = new BattleTest.BattleFixture
f.battle.advanceTime(f.battle.baseTurnTime)
f.battle.readyEntity should be ('isDefined)
f.battle.readyEntity.get.entityType should equal (BattleEntityType.Party)
f.battle.readyEntity.get.entityId should equal (0)
f.battle.takeAction(NullAction(f.battle.partyStatus(0)))
f.battle.readyEntity should be ('isDefined)
f.battle.readyEntity.get.entityType should equal (BattleEntityType.Enemy)
f.battle.readyEntity.get.entityId should equal (0)
f.battle.takeAction(NullAction(f.battle.enemyStatus(0)))
f.battle.readyEntity should be ('isDefined)
f.battle.readyEntity.get.entityType should equal (BattleEntityType.Party)
f.battle.readyEntity.get.entityId should equal (1)
f.battle.takeAction(NullAction(f.battle.partyStatus(1)))
f.battle.readyEntity should equal (None)
}
"Battle" should "use AI to automatically handle enemy actions" in {
val f = new BattleTest.BattleFixture(aiOpt = Some(new RandomEnemyAI))
f.battle.advanceTime(f.battle.baseTurnTime)
f.battle.readyEntity should be ('isDefined)
f.battle.readyEntity.get.entityType should equal (BattleEntityType.Party)
f.battle.readyEntity.get.entityId should equal (0)
f.battle.takeAction(NullAction(f.battle.partyStatus(0)))
f.battle.readyEntity should be ('isDefined)
f.battle.readyEntity.get.entityType should equal (BattleEntityType.Party)
f.battle.readyEntity.get.entityId should equal (1)
f.battle.takeAction(NullAction(f.battle.partyStatus(1)))
f.battle.readyEntity should equal (None)
}
"Battle" should "reassign attacks on dead party members to live ones" in {
val f = new BattleTest.BattleFixture(aiOpt = Some(new RandomEnemyAI)) {
override def initialCharacterHps = Array(0, 1)
}
val action =
AttackAction(f.battle.enemyStatus.head, Array(f.battle.partyStatus.head))
val (hits, success) = action.process(f.battle)
hits.length should equal (1)
hits.head.hitActor should equal (f.battle.partyStatus(1))
}
"Battle" should "reassign attacks on dead enemies to live ones" in {
val f = new BattleTest.BattleFixture {
override def encounter = Encounter(
units = Array(EncounterUnit(0, 100, 100), EncounterUnit(0, 100, 100)))
}
f.battle.enemyStatus.head.hp = 0
f.battle.enemyStatus.head.alive should equal (false)
val action =
AttackAction(f.battle.partyStatus.head, Array(f.battle.enemyStatus.head))
val (hits, success) = action.process(f.battle)
hits.length should equal (1)
hits.head.hitActor should equal (f.battle.enemyStatus(1))
}
"Battle" should "heal targets up to, but not exceeding, their max HP" in {
val f = new BattleTest.BattleFixture
f.pData.enums.skills =
Array(
Skill(damages = Array(
DamageFormula(typeId = DamageType.Magic.id, elementId = 0,
formula = "-a.mag*10")))
)
val partyHead = f.battle.partyStatus.head
val action = SkillAction(partyHead, Array(partyHead), skillId = 0)
val (hits, success) = action.process(f.battle)
hits.length should equal (1)
hits.head.hitActor should equal (partyHead)
// The reported healing value should exceed the HP
hits.head.damage should equal (Damage(DamageType.Magic, 0, -91))
// But the final HP should equal the max HP
partyHead.hp should equal(partyHead.stats.mhp)
}
"Battle" should "handle victory correctly" in {
val f = new BattleTest.BattleFixture
f.battle.enemyStatus.map(_.hp = 0)
f.battle.advanceTime(0f)
f.battle.state should equal(Battle.VICTORY)
}
"Battle" should "handle defeat correctly" in {
val f = new BattleTest.BattleFixture
f.battle.partyStatus.map(_.hp = 0)
f.battle.advanceTime(0f)
f.battle.state should equal(Battle.DEFEAT)
}
} | 412 | 0.814383 | 1 | 0.814383 | game-dev | MEDIA | 0.953687 | game-dev | 0.945347 | 1 | 0.945347 |
CleanroomMC/GroovyScript | 1,962 | src/main/java/com/cleanroommc/groovyscript/helper/ingredient/itemstack/ItemStack2IntProxyMap.java | package com.cleanroommc.groovyscript.helper.ingredient.itemstack;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenCustomHashMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
/**
* Some Minecraft logic functions different when interacting with
* {@link ItemStack}s with metadata equal to {@link Short#MAX_VALUE} ({@link net.minecraftforge.oredict.OreDictionary#WILDCARD_VALUE}.
* <p>
* This class handles this logic via two maps -
* {@link Object2IntOpenHashMap} and {@link Object2IntOpenCustomHashMap} (with the hash strategy being {@link ItemStackHashStrategy#STRATEGY}.
* The former is for if the {@link ItemStack} being checked has wildcard metadata,
* and the latter is for if it doesn't.
* <p>
* This means that insertion inserts into one of two maps depending on metadata,
* and retrieval first checks the wildcard map before checking the metadata-specific map.
*/
public class ItemStack2IntProxyMap {
private final Object2IntMap<Item> wildcard = new Object2IntOpenHashMap<>();
private final Object2IntMap<ItemStack> metadata = new Object2IntOpenCustomHashMap<>(ItemStackHashStrategy.STRATEGY);
public int put(ItemStack key, int value) {
if (key.getItemDamage() == OreDictionary.WILDCARD_VALUE) return wildcard.put(key.getItem(), value);
return metadata.put(key, value);
}
public int removeInt(ItemStack key) {
if (key.getItemDamage() == OreDictionary.WILDCARD_VALUE) return wildcard.removeInt(key.getItem());
return metadata.removeInt(key);
}
public int getInt(ItemStack key) {
if (wildcard.containsKey(key.getItem())) wildcard.getInt(key.getItem());
return metadata.getInt(key);
}
public void clear() {
wildcard.clear();
metadata.clear();
}
}
| 412 | 0.843876 | 1 | 0.843876 | game-dev | MEDIA | 0.977366 | game-dev | 0.934855 | 1 | 0.934855 |
jdisho/TinyNetworking | 4,377 | Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift | //
// TailRecursiveSink.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
enum TailRecursiveSinkCommand {
case moveNext
case dispose
}
#if DEBUG || TRACE_RESOURCES
public var maxTailRecursiveSinkStackSize = 0
#endif
/// This class is usually used with `Generator` version of the operators.
class TailRecursiveSink<Sequence: Swift.Sequence, Observer: ObserverType>
: Sink<Observer>
, InvocableWithValueType where Sequence.Element: ObservableConvertibleType, Sequence.Element.Element == Observer.Element {
typealias Value = TailRecursiveSinkCommand
typealias Element = Observer.Element
typealias SequenceGenerator = (generator: Sequence.Iterator, remaining: IntMax?)
var generators: [SequenceGenerator] = []
var disposed = false
var subscription = SerialDisposable()
// this is thread safe object
var gate = AsyncLock<InvocableScheduledItem<TailRecursiveSink<Sequence, Observer>>>()
override init(observer: Observer, cancel: Cancelable) {
super.init(observer: observer, cancel: cancel)
}
func run(_ sources: SequenceGenerator) -> Disposable {
self.generators.append(sources)
self.schedule(.moveNext)
return self.subscription
}
func invoke(_ command: TailRecursiveSinkCommand) {
switch command {
case .dispose:
self.disposeCommand()
case .moveNext:
self.moveNextCommand()
}
}
// simple implementation for now
func schedule(_ command: TailRecursiveSinkCommand) {
self.gate.invoke(InvocableScheduledItem(invocable: self, state: command))
}
func done() {
self.forwardOn(.completed)
self.dispose()
}
func extract(_ observable: Observable<Element>) -> SequenceGenerator? {
rxAbstractMethod()
}
// should be done on gate locked
private func moveNextCommand() {
var next: Observable<Element>?
repeat {
guard let (g, left) = self.generators.last else {
break
}
if self.isDisposed {
return
}
self.generators.removeLast()
var e = g
guard let nextCandidate = e.next()?.asObservable() else {
continue
}
// `left` is a hint of how many elements are left in generator.
// In case this is the last element, then there is no need to push
// that generator on stack.
//
// This is an optimization used to make sure in tail recursive case
// there is no memory leak in case this operator is used to generate non terminating
// sequence.
if let knownOriginalLeft = left {
// `- 1` because generator.next() has just been called
if knownOriginalLeft - 1 >= 1 {
self.generators.append((e, knownOriginalLeft - 1))
}
}
else {
self.generators.append((e, nil))
}
let nextGenerator = self.extract(nextCandidate)
if let nextGenerator = nextGenerator {
self.generators.append(nextGenerator)
#if DEBUG || TRACE_RESOURCES
if maxTailRecursiveSinkStackSize < self.generators.count {
maxTailRecursiveSinkStackSize = self.generators.count
}
#endif
}
else {
next = nextCandidate
}
} while next == nil
guard let existingNext = next else {
self.done()
return
}
let disposable = SingleAssignmentDisposable()
self.subscription.disposable = disposable
disposable.setDisposable(self.subscribeToNext(existingNext))
}
func subscribeToNext(_ source: Observable<Element>) -> Disposable {
rxAbstractMethod()
}
func disposeCommand() {
self.disposed = true
self.generators.removeAll(keepingCapacity: false)
}
override func dispose() {
super.dispose()
self.subscription.dispose()
self.gate.dispose()
self.schedule(.dispose)
}
}
| 412 | 0.938029 | 1 | 0.938029 | game-dev | MEDIA | 0.852195 | game-dev | 0.958529 | 1 | 0.958529 |
joekoolade/JOE | 14,191 | classpath-0.98/external/jsr166/java/util/concurrent/atomic/AtomicLongFieldUpdater.java | /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
package java.util.concurrent.atomic;
import sun.misc.Unsafe;
import java.lang.reflect.*;
/**
* A reflection-based utility that enables atomic updates to
* designated <tt>volatile long</tt> fields of designated classes.
* This class is designed for use in atomic data structures in which
* several fields of the same node are independently subject to atomic
* updates.
*
* <p>Note that the guarantees of the {@code compareAndSet}
* method in this class are weaker than in other atomic classes.
* Because this class cannot ensure that all uses of the field
* are appropriate for purposes of atomic access, it can
* guarantee atomicity only with respect to other invocations of
* {@code compareAndSet} and {@code set} on the same updater.
*
* @since 1.5
* @author Doug Lea
* @param <T> The type of the object holding the updatable field
*/
public abstract class AtomicLongFieldUpdater<T> {
/**
* Creates and returns an updater for objects with the given field.
* The Class argument is needed to check that reflective types and
* generic types match.
*
* @param tclass the class of the objects holding the field
* @param fieldName the name of the field to be updated.
* @return the updater
* @throws IllegalArgumentException if the field is not a
* volatile long type.
* @throws RuntimeException with a nested reflection-based
* exception if the class does not hold field or is the wrong type.
*/
public static <U> AtomicLongFieldUpdater<U> newUpdater(Class<U> tclass, String fieldName) {
if (AtomicLong.VM_SUPPORTS_LONG_CAS)
return new CASUpdater<U>(tclass, fieldName);
else
return new LockedUpdater<U>(tclass, fieldName);
}
/**
* Protected do-nothing constructor for use by subclasses.
*/
protected AtomicLongFieldUpdater() {
}
/**
* Atomically sets the field of the given object managed by this updater
* to the given updated value if the current value <tt>==</tt> the
* expected value. This method is guaranteed to be atomic with respect to
* other calls to <tt>compareAndSet</tt> and <tt>set</tt>, but not
* necessarily with respect to other changes in the field.
*
* @param obj An object whose field to conditionally set
* @param expect the expected value
* @param update the new value
* @return true if successful.
* @throws ClassCastException if <tt>obj</tt> is not an instance
* of the class possessing the field established in the constructor.
*/
public abstract boolean compareAndSet(T obj, long expect, long update);
/**
* Atomically sets the field of the given object managed by this updater
* to the given updated value if the current value <tt>==</tt> the
* expected value. This method is guaranteed to be atomic with respect to
* other calls to <tt>compareAndSet</tt> and <tt>set</tt>, but not
* necessarily with respect to other changes in the field.
* May fail spuriously and does not provide ordering guarantees,
* so is only rarely an appropriate alternative to <tt>compareAndSet</tt>.
*
* @param obj An object whose field to conditionally set
* @param expect the expected value
* @param update the new value
* @return true if successful.
* @throws ClassCastException if <tt>obj</tt> is not an instance
* of the class possessing the field established in the constructor.
*/
public abstract boolean weakCompareAndSet(T obj, long expect, long update);
/**
* Sets the field of the given object managed by this updater to the
* given updated value. This operation is guaranteed to act as a volatile
* store with respect to subsequent invocations of
* <tt>compareAndSet</tt>.
*
* @param obj An object whose field to set
* @param newValue the new value
*/
public abstract void set(T obj, long newValue);
/**
* Eventually sets the field of the given object managed by this
* updater to the given updated value.
*
* @param obj An object whose field to set
* @param newValue the new value
* @since 1.6
*/
public abstract void lazySet(T obj, long newValue);
/**
* Gets the current value held in the field of the given object managed
* by this updater.
*
* @param obj An object whose field to get
* @return the current value
*/
public abstract long get(T obj);
/**
* Atomically sets the field of the given object managed by this updater
* to the given value and returns the old value.
*
* @param obj An object whose field to get and set
* @param newValue the new value
* @return the previous value
*/
public long getAndSet(T obj, long newValue) {
for (;;) {
long current = get(obj);
if (compareAndSet(obj, current, newValue))
return current;
}
}
/**
* Atomically increments by one the current value of the field of the
* given object managed by this updater.
*
* @param obj An object whose field to get and set
* @return the previous value
*/
public long getAndIncrement(T obj) {
for (;;) {
long current = get(obj);
long next = current + 1;
if (compareAndSet(obj, current, next))
return current;
}
}
/**
* Atomically decrements by one the current value of the field of the
* given object managed by this updater.
*
* @param obj An object whose field to get and set
* @return the previous value
*/
public long getAndDecrement(T obj) {
for (;;) {
long current = get(obj);
long next = current - 1;
if (compareAndSet(obj, current, next))
return current;
}
}
/**
* Atomically adds the given value to the current value of the field of
* the given object managed by this updater.
*
* @param obj An object whose field to get and set
* @param delta the value to add
* @return the previous value
*/
public long getAndAdd(T obj, long delta) {
for (;;) {
long current = get(obj);
long next = current + delta;
if (compareAndSet(obj, current, next))
return current;
}
}
/**
* Atomically increments by one the current value of the field of the
* given object managed by this updater.
*
* @param obj An object whose field to get and set
* @return the updated value
*/
public long incrementAndGet(T obj) {
for (;;) {
long current = get(obj);
long next = current + 1;
if (compareAndSet(obj, current, next))
return next;
}
}
/**
* Atomically decrements by one the current value of the field of the
* given object managed by this updater.
*
* @param obj An object whose field to get and set
* @return the updated value
*/
public long decrementAndGet(T obj) {
for (;;) {
long current = get(obj);
long next = current - 1;
if (compareAndSet(obj, current, next))
return next;
}
}
/**
* Atomically adds the given value to the current value of the field of
* the given object managed by this updater.
*
* @param obj An object whose field to get and set
* @param delta the value to add
* @return the updated value
*/
public long addAndGet(T obj, long delta) {
for (;;) {
long current = get(obj);
long next = current + delta;
if (compareAndSet(obj, current, next))
return next;
}
}
private static class CASUpdater<T> extends AtomicLongFieldUpdater<T> {
private static final Unsafe unsafe = Unsafe.getUnsafe();
private final long offset;
private final Class<T> tclass;
private final Class cclass;
CASUpdater(Class<T> tclass, String fieldName) {
Field field = null;
Class caller = null;
int modifiers = 0;
try {
field = tclass.getDeclaredField(fieldName);
caller = sun.reflect.Reflection.getCallerClass(3);
modifiers = field.getModifiers();
sun.reflect.misc.ReflectUtil.ensureMemberAccess(
caller, tclass, null, modifiers);
sun.reflect.misc.ReflectUtil.checkPackageAccess(tclass);
} catch(Exception ex) {
throw new RuntimeException(ex);
}
Class fieldt = field.getType();
if (fieldt != long.class)
throw new IllegalArgumentException("Must be long type");
if (!Modifier.isVolatile(modifiers))
throw new IllegalArgumentException("Must be volatile type");
this.cclass = (Modifier.isProtected(modifiers) &&
caller != tclass) ? caller : null;
this.tclass = tclass;
offset = unsafe.objectFieldOffset(field);
}
private void fullCheck(T obj) {
if (!tclass.isInstance(obj))
throw new ClassCastException();
if (cclass != null)
ensureProtectedAccess(obj);
}
public boolean compareAndSet(T obj, long expect, long update) {
if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj);
return unsafe.compareAndSwapLong(obj, offset, expect, update);
}
public boolean weakCompareAndSet(T obj, long expect, long update) {
if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj);
return unsafe.compareAndSwapLong(obj, offset, expect, update);
}
public void set(T obj, long newValue) {
if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj);
unsafe.putLongVolatile(obj, offset, newValue);
}
public void lazySet(T obj, long newValue) {
if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj);
unsafe.putOrderedLong(obj, offset, newValue);
}
public long get(T obj) {
if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj);
return unsafe.getLongVolatile(obj, offset);
}
private void ensureProtectedAccess(T obj) {
if (cclass.isInstance(obj)) {
return;
}
throw new RuntimeException (
new IllegalAccessException("Class " +
cclass.getName() +
" can not access a protected member of class " +
tclass.getName() +
" using an instance of " +
obj.getClass().getName()
)
);
}
}
private static class LockedUpdater<T> extends AtomicLongFieldUpdater<T> {
private static final Unsafe unsafe = Unsafe.getUnsafe();
private final long offset;
private final Class<T> tclass;
private final Class cclass;
LockedUpdater(Class<T> tclass, String fieldName) {
Field field = null;
Class caller = null;
int modifiers = 0;
try {
field = tclass.getDeclaredField(fieldName);
caller = sun.reflect.Reflection.getCallerClass(3);
modifiers = field.getModifiers();
sun.reflect.misc.ReflectUtil.ensureMemberAccess(
caller, tclass, null, modifiers);
sun.reflect.misc.ReflectUtil.checkPackageAccess(tclass);
} catch(Exception ex) {
throw new RuntimeException(ex);
}
Class fieldt = field.getType();
if (fieldt != long.class)
throw new IllegalArgumentException("Must be long type");
if (!Modifier.isVolatile(modifiers))
throw new IllegalArgumentException("Must be volatile type");
this.cclass = (Modifier.isProtected(modifiers) &&
caller != tclass) ? caller : null;
this.tclass = tclass;
offset = unsafe.objectFieldOffset(field);
}
private void fullCheck(T obj) {
if (!tclass.isInstance(obj))
throw new ClassCastException();
if (cclass != null)
ensureProtectedAccess(obj);
}
public boolean compareAndSet(T obj, long expect, long update) {
if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj);
synchronized(this) {
long v = unsafe.getLong(obj, offset);
if (v != expect)
return false;
unsafe.putLong(obj, offset, update);
return true;
}
}
public boolean weakCompareAndSet(T obj, long expect, long update) {
return compareAndSet(obj, expect, update);
}
public void set(T obj, long newValue) {
if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj);
synchronized(this) {
unsafe.putLong(obj, offset, newValue);
}
}
public void lazySet(T obj, long newValue) {
set(obj, newValue);
}
public long get(T obj) {
if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj);
synchronized(this) {
return unsafe.getLong(obj, offset);
}
}
private void ensureProtectedAccess(T obj) {
if (cclass.isInstance(obj)) {
return;
}
throw new RuntimeException (
new IllegalAccessException("Class " +
cclass.getName() +
" can not access a protected member of class " +
tclass.getName() +
" using an instance of " +
obj.getClass().getName()
)
);
}
}
}
| 412 | 0.94679 | 1 | 0.94679 | game-dev | MEDIA | 0.140199 | game-dev | 0.954274 | 1 | 0.954274 |
SinlessDevil/EcsStickmanSurvivors | 2,104 | src/ecs_stickman_survivors/Assets/Code/Generated/Game/Components/GameActiveComponent.cs | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by Entitas.CodeGeneration.Plugins.ComponentMatcherApiGenerator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public sealed partial class GameMatcher {
static Entitas.IMatcher<GameEntity> _matcherActive;
public static Entitas.IMatcher<GameEntity> Active {
get {
if (_matcherActive == null) {
var matcher = (Entitas.Matcher<GameEntity>)Entitas.Matcher<GameEntity>.AllOf(GameComponentsLookup.Active);
matcher.componentNames = GameComponentsLookup.componentNames;
_matcherActive = matcher;
}
return _matcherActive;
}
}
}
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by Entitas.CodeGeneration.Plugins.ComponentEntityApiGenerator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public partial class GameEntity {
static readonly Code.Gameplay.Common.Active activeComponent = new Code.Gameplay.Common.Active();
public bool isActive {
get { return HasComponent(GameComponentsLookup.Active); }
set {
if (value != isActive) {
var index = GameComponentsLookup.Active;
if (value) {
var componentPool = GetComponentPool(index);
var component = componentPool.Count > 0
? componentPool.Pop()
: activeComponent;
AddComponent(index, component);
} else {
RemoveComponent(index);
}
}
}
}
}
| 412 | 0.548879 | 1 | 0.548879 | game-dev | MEDIA | 0.581541 | game-dev | 0.879404 | 1 | 0.879404 |
shanapu/MyJailbreak | 29,245 | addons/sourcemod/scripting/MyJailbreak/zeus.sp | /*
* MyJailbreak - Zeus Event Day Plugin.
* by: shanapu
* https://github.com/shanapu/MyJailbreak/
*
* Copyright (C) 2016-2017 Thomas Schmidt (shanapu)
*
* This file is part of the MyJailbreak SourceMod Plugin.
* Contributer: Hexer10, olegtsvetkov
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
/******************************************************************************
STARTUP
******************************************************************************/
// Includes
#include <sourcemod>
#include <sdktools>
#include <sdkhooks>
#include <cstrike>
#include <emitsoundany>
#include <colors>
#include <autoexecconfig>
#include <mystocks>
// Optional Plugins
#undef REQUIRE_PLUGIN
#include <hosties>
#include <lastrequest>
#include <warden>
#include <myjbwarden>
#include <myjailbreak>
#include <myweapons>
#include <smartjaildoors>
#define REQUIRE_PLUGIN
// Compiler Options
#pragma semicolon 1
#pragma newdecls required
// Booleans
bool g_bIsLateLoad = false;
bool g_bIsZeus = false;
bool g_bStartZeus = false;
bool g_bIsRoundEnd = true;
// Plugin bools
bool gp_bWarden;
bool gp_bMyJBWarden;
bool gp_bHosties;
bool gp_bSmartJailDoors;
bool gp_bMyJailbreak;
bool gp_bMyWeapons;
// Console Variables
ConVar gc_bPlugin;
ConVar gc_sPrefix;
ConVar gc_bSetW;
ConVar gc_iCooldownStart;
ConVar gc_bSetA;
ConVar gc_bSetABypassCooldown;
ConVar gc_bSpawnCell;
ConVar gc_bVote;
ConVar gc_iCooldownDay;
ConVar gc_iRoundTime;
ConVar gc_iTruceTime;
ConVar gc_bOverlays;
ConVar gc_sOverlayStartPath;
ConVar gc_bSounds;
ConVar gc_iRounds;
ConVar gc_sSoundStartPath;
ConVar gc_fBeaconTime;
ConVar gc_sCustomCommandVote;
ConVar gc_sCustomCommandSet;
ConVar gc_sAdminFlag;
ConVar gc_bAllowLR;
ConVar gc_bDrop;
ConVar gc_bBeginSetA;
ConVar gc_bBeginSetW;
ConVar gc_bBeginSetV;
ConVar gc_bBeginSetVW;
ConVar gc_bTeleportSpawn;
// Extern Convars
ConVar g_iTerrorForLR;
// Integers
int g_iCoolDown;
int g_iTruceTime;
int g_iVoteCount;
int g_iRound;
int g_iMaxRound;
int g_iTsLR;
// Handles
Handle g_hTimerTruce;
Handle g_hTimerBeacon;
// Strings
char g_sPrefix[64];
char g_sHasVoted[1500];
char g_sSoundStartPath[256];
char g_sEventsLogFile[PLATFORM_MAX_PATH];
char g_sOverlayStartPath[256];
// Floats
float g_fPos[3];
// Info
public Plugin myinfo = {
name = "MyJailbreak - Zeus",
author = "shanapu",
description = "Event Day for Jailbreak Server",
version = MYJB_VERSION,
url = MYJB_URL_LINK
};
public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max)
{
g_bIsLateLoad = late;
return APLRes_Success;
}
// Start
public void OnPluginStart()
{
// Translation
LoadTranslations("MyJailbreak.Warden.phrases");
LoadTranslations("MyJailbreak.Zeus.phrases");
// Client Commands
RegConsoleCmd("sm_setzeus", Command_SetZeus, "Allows the Admin or Warden to set zeus as next round");
RegConsoleCmd("sm_zeus", Command_VoteZeus, "Allows players to vote for a zeus");
// AutoExecConfig
AutoExecConfig_SetFile("Zeus", "MyJailbreak/EventDays");
AutoExecConfig_SetCreateFile(true);
AutoExecConfig_CreateConVar("sm_zeus_version", MYJB_VERSION, "The version of this MyJailbreak SourceMod plugin", FCVAR_SPONLY|FCVAR_REPLICATED|FCVAR_NOTIFY|FCVAR_DONTRECORD);
gc_bPlugin = AutoExecConfig_CreateConVar("sm_zeus_enable", "1", "0 - disabled, 1 - enable this MyJailbreak SourceMod plugin", _, true, 0.0, true, 1.0);
gc_sPrefix = AutoExecConfig_CreateConVar("sm_zeus_prefix", "[{green}MyJB.Zeus{default}]", "Set your chat prefix for this plugin.");
gc_sCustomCommandVote = AutoExecConfig_CreateConVar("sm_zeus_cmds_vote", "taser", "Set your custom chat command for Event voting(!zeus (no 'sm_'/'!')(seperate with comma ', ')(max. 12 commands))");
gc_sCustomCommandSet = AutoExecConfig_CreateConVar("sm_zeus_cmds_set", "szeus, staser", "Set your custom chat command for set Event(!setzeus (no 'sm_'/'!')(seperate with comma ', ')(max. 12 commands))");
gc_bSetW = AutoExecConfig_CreateConVar("sm_zeus_warden", "1", "0 - disabled, 1 - allow warden to set zeus round", _, true, 0.0, true, 1.0);
gc_bSetA = AutoExecConfig_CreateConVar("sm_zeus_admin", "1", "0 - disabled, 1 - allow admin/vip to set zeus round", _, true, 0.0, true, 1.0);
gc_sAdminFlag = AutoExecConfig_CreateConVar("sm_zeus_flag", "g", "Set flag for admin/vip to set this Event Day.");
gc_bVote = AutoExecConfig_CreateConVar("sm_zeus_vote", "1", "0 - disabled, 1 - allow player to vote for zeus", _, true, 0.0, true, 1.0);
gc_bSpawnCell = AutoExecConfig_CreateConVar("sm_zeus_spawn", "0", "0 - T teleport to CT spawn, 1 - cell doors auto open", _, true, 0.0, true, 1.0);
gc_bDrop = AutoExecConfig_CreateConVar("sm_zeus_drop", "0", "0 - disabled, 1 - allow player to drop their zeus", _, true, 0.0, true, 1.0);
gc_bBeginSetA = AutoExecConfig_CreateConVar("sm_zeus_begin_admin", "1", "When admin set event (!setzeus) = 0 - start event next round, 1 - start event current round", _, true, 0.0, true, 1.0);
gc_bBeginSetW = AutoExecConfig_CreateConVar("sm_zeus_begin_warden", "1", "When warden set event (!setzeus) = 0 - start event next round, 1 - start event current round", _, true, 0.0, true, 1.0);
gc_bBeginSetV = AutoExecConfig_CreateConVar("sm_zeus_begin_vote", "0", "When users vote for event (!zeus) = 0 - start event next round, 1 - start event current round", _, true, 0.0, true, 1.0);
gc_bBeginSetVW = AutoExecConfig_CreateConVar("sm_zeus_begin_daysvote", "0", "When warden/admin start eventday voting (!sm_voteday) and event wins = 0 - start event next round, 1 - start event current round", _, true, 0.0, true, 1.0);
gc_bTeleportSpawn = AutoExecConfig_CreateConVar("sm_zeus_teleport_spawn", "0", "0 - start event in current round from current player positions, 1 - teleport players to spawn when start event on current round(only when sm_*_begin_admin, sm_*_begin_warden, sm_*_begin_vote or sm_*_begin_daysvote is on '1')", _, true, 0.0, true, 1.0);
gc_iRounds = AutoExecConfig_CreateConVar("sm_zeus_rounds", "3", "Rounds to play in a row", _, true, 1.0);
gc_iRoundTime = AutoExecConfig_CreateConVar("sm_zeus_roundtime", "5", "Round time in minutes for a single zeus round", _, true, 1.0);
gc_fBeaconTime = AutoExecConfig_CreateConVar("sm_zeus_beacon_time", "240", "Time in seconds until the beacon turned on (set to 0 to disable)", _, true, 0.0);
gc_iTruceTime = AutoExecConfig_CreateConVar("sm_zeus_trucetime", "15", "Time in seconds players can't deal damage", _, true, 0.0);
gc_iCooldownDay = AutoExecConfig_CreateConVar("sm_zeus_cooldown_day", "3", "Rounds cooldown after a event until event can be start again", _, true, 0.0);
gc_iCooldownStart = AutoExecConfig_CreateConVar("sm_zeus_cooldown_start", "3", "Rounds until event can be start after mapchange.", _, true, 0.0);
gc_bSetABypassCooldown = AutoExecConfig_CreateConVar("sm_zeus_cooldown_admin", "1", "0 - disabled, 1 - ignore the cooldown when admin/vip set zeus round", _, true, 0.0, true, 1.0);
gc_bSounds = AutoExecConfig_CreateConVar("sm_zeus_sounds_enable", "1", "0 - disabled, 1 - enable sounds ", _, true, 0.1, true, 1.0);
gc_sSoundStartPath = AutoExecConfig_CreateConVar("sm_zeus_sounds_start", "music/MyJailbreak/start.mp3", "Path to the soundfile which should be played for a start.");
gc_bOverlays = AutoExecConfig_CreateConVar("sm_zeus_overlays_enable", "1", "0 - disabled, 1 - enable overlays", _, true, 0.0, true, 1.0);
gc_sOverlayStartPath = AutoExecConfig_CreateConVar("sm_zeus_overlays_start", "overlays/MyJailbreak/start", "Path to the start Overlay DONT TYPE .vmt or .vft");
gc_bAllowLR = AutoExecConfig_CreateConVar("sm_zeus_allow_lr", "0", "0 - disabled, 1 - enable LR for last round and end eventday", _, true, 0.0, true, 1.0);
AutoExecConfig_ExecuteFile();
AutoExecConfig_CleanFile();
// Hooks
HookEvent("round_start", Event_RoundStart);
HookEvent("player_death", Event_PlayerDeath);
HookEvent("round_end", Event_RoundEnd);
HookConVarChange(gc_sOverlayStartPath, OnSettingChanged);
HookConVarChange(gc_sSoundStartPath, OnSettingChanged);
HookConVarChange(gc_sPrefix, OnSettingChanged);
// Find
g_iCoolDown = gc_iCooldownDay.IntValue + 1;
g_iTruceTime = gc_iTruceTime.IntValue;
gc_sOverlayStartPath.GetString(g_sOverlayStartPath, sizeof(g_sOverlayStartPath));
gc_sSoundStartPath.GetString(g_sSoundStartPath, sizeof(g_sSoundStartPath));
// Logs
SetLogFile(g_sEventsLogFile, "Events", "MyJailbreak");
// Late loading
if (g_bIsLateLoad)
{
for (int i = 1; i <= MaxClients; i++)
{
if (!IsClientInGame(i))
continue;
OnClientPutInServer(i);
}
g_bIsLateLoad = false;
}
}
// ConVarChange for Strings
public void OnSettingChanged(Handle convar, const char[] oldValue, const char[] newValue)
{
if (convar == gc_sOverlayStartPath)
{
strcopy(g_sOverlayStartPath, sizeof(g_sOverlayStartPath), newValue);
if (gc_bOverlays.BoolValue)
{
PrecacheDecalAnyDownload(g_sOverlayStartPath);
}
}
else if (convar == gc_sSoundStartPath)
{
strcopy(g_sSoundStartPath, sizeof(g_sSoundStartPath), newValue);
if (gc_bSounds.BoolValue)
{
PrecacheSoundAnyDownload(g_sSoundStartPath);
}
}
else if (convar == gc_sPrefix)
{
strcopy(g_sPrefix, sizeof(g_sPrefix), newValue);
}
}
public void OnAllPluginsLoaded()
{
gp_bWarden = LibraryExists("warden");
gp_bMyJBWarden = LibraryExists("myjbwarden");
gp_bHosties = LibraryExists("lastrequest");
gp_bSmartJailDoors = LibraryExists("smartjaildoors");
gp_bMyJailbreak = LibraryExists("myjailbreak");
gp_bMyWeapons = LibraryExists("myweapons");
}
public void OnLibraryRemoved(const char[] name)
{
if (StrEqual(name, "warden"))
{
gp_bWarden = false;
}
else if (StrEqual(name, "myjbwarden"))
{
gp_bMyJBWarden = false;
}
else if (StrEqual(name, "lastrequest"))
{
gp_bHosties = false;
}
else if (StrEqual(name, "smartjaildoors"))
{
gp_bSmartJailDoors = false;
}
else if (StrEqual(name, "myjailbreak"))
{
gp_bMyJailbreak = false;
}
else if (StrEqual(name, "myweapons"))
{
gp_bMyWeapons = false;
}
}
public void OnLibraryAdded(const char[] name)
{
if (StrEqual(name, "warden"))
{
gp_bWarden = true;
}
else if (StrEqual(name, "myjbwarden"))
{
gp_bMyJBWarden = true;
}
else if (StrEqual(name, "lastrequest"))
{
gp_bHosties = true;
}
else if (StrEqual(name, "smartjaildoors"))
{
gp_bSmartJailDoors = true;
}
else if (StrEqual(name, "myjailbreak"))
{
gp_bMyJailbreak = true;
}
else if (StrEqual(name, "myweapons"))
{
gp_bMyWeapons = true;
}
}
// Initialize Plugin
public void OnConfigsExecuted()
{
// FindConVar
g_iTruceTime = gc_iTruceTime.IntValue;
g_iCoolDown = gc_iCooldownStart.IntValue + 1;
g_iMaxRound = gc_iRounds.IntValue;
gc_sPrefix.GetString(g_sPrefix, sizeof(g_sPrefix));
gc_sOverlayStartPath.GetString(g_sOverlayStartPath, sizeof(g_sOverlayStartPath));
gc_sSoundStartPath.GetString(g_sSoundStartPath, sizeof(g_sSoundStartPath));
if (gp_bHosties)
{
g_iTerrorForLR = FindConVar("sm_hosties_lr_ts_max");
}
// Set custom Commands
int iCount = 0;
char sCommands[128], sCommandsL[12][32], sCommand[32];
// Vote
gc_sCustomCommandVote.GetString(sCommands, sizeof(sCommands));
ReplaceString(sCommands, sizeof(sCommands), " ", "");
iCount = ExplodeString(sCommands, ",", sCommandsL, sizeof(sCommandsL), sizeof(sCommandsL[]));
for (int i = 0; i < iCount; i++)
{
Format(sCommand, sizeof(sCommand), "sm_%s", sCommandsL[i]);
if (GetCommandFlags(sCommand) == INVALID_FCVAR_FLAGS) // if command not already exist
{
RegConsoleCmd(sCommand, Command_VoteZeus, "Allows players to vote for a zeus");
}
}
// Set
gc_sCustomCommandSet.GetString(sCommands, sizeof(sCommands));
ReplaceString(sCommands, sizeof(sCommands), " ", "");
iCount = ExplodeString(sCommands, ",", sCommandsL, sizeof(sCommandsL), sizeof(sCommandsL[]));
for (int i = 0; i < iCount; i++)
{
Format(sCommand, sizeof(sCommand), "sm_%s", sCommandsL[i]);
if (GetCommandFlags(sCommand) == INVALID_FCVAR_FLAGS) // if command not already exist
{
RegConsoleCmd(sCommand, Command_SetZeus, "Allows the Admin or Warden to set zeus as next round");
}
}
if (!gp_bMyJailbreak)
return;
MyJailbreak_AddEventDay("zeus");
}
public void OnPluginEnd()
{
if (!gp_bMyJailbreak)
return;
MyJailbreak_RemoveEventDay("zeus");
}
/******************************************************************************
COMMANDS
******************************************************************************/
// Admin & Warden set Event
public Action Command_SetZeus(int client, int args)
{
if (!gc_bPlugin.BoolValue)
{
CReplyToCommand(client, "%s %t", g_sPrefix, "zeus_disabled");
return Plugin_Handled;
}
if (client == 0) // Called by a server/voting
{
StartEventRound(gc_bBeginSetVW.BoolValue);
if (!gp_bMyJailbreak)
return Plugin_Handled;
if (MyJailbreak_ActiveLogging())
{
LogToFileEx(g_sEventsLogFile, "Event Zeus was started by groupvoting");
}
}
else if (MyJailbreak_CheckVIPFlags(client, "sm_zeus_flag", gc_sAdminFlag, "sm_zeus_flag")) // Called by admin/VIP
{
if (!gc_bSetA.BoolValue)
{
CReplyToCommand(client, "%s %t", g_sPrefix, "zeus_setbyadmin");
return Plugin_Handled;
}
if (GetTeamClientCount(CS_TEAM_CT) == 0 || GetTeamClientCount(CS_TEAM_T) == 0)
{
CReplyToCommand(client, "%s %t", g_sPrefix, "zeus_minplayer");
return Plugin_Handled;
}
if (gp_bMyJailbreak)
{
char EventDay[64];
MyJailbreak_GetEventDayName(EventDay);
if (!StrEqual(EventDay, "none", false))
{
CReplyToCommand(client, "%s %t", g_sPrefix, "zeus_progress", EventDay);
return Plugin_Handled;
}
}
if (g_iCoolDown > 0 && !gc_bSetABypassCooldown.BoolValue)
{
CReplyToCommand(client, "%s %t", g_sPrefix, "zeus_wait", g_iCoolDown);
return Plugin_Handled;
}
StartEventRound(gc_bBeginSetA.BoolValue);
if (!gp_bMyJailbreak)
return Plugin_Handled;
if (MyJailbreak_ActiveLogging())
{
LogToFileEx(g_sEventsLogFile, "Event Zeus was started by admin %L", client);
}
}
else if (gp_bWarden) // Called by warden
{
if (!warden_iswarden(client))
{
CReplyToCommand(client, "%s %t", g_sPrefix, "warden_notwarden");
return Plugin_Handled;
}
if (!gc_bSetW.BoolValue)
{
CReplyToCommand(client, "%s %t", g_sPrefix, "zeus_setbywarden");
return Plugin_Handled;
}
if (GetTeamClientCount(CS_TEAM_CT) == 0 || GetTeamClientCount(CS_TEAM_T) == 0)
{
CReplyToCommand(client, "%s %t", g_sPrefix, "zeus_minplayer");
return Plugin_Handled;
}
if (gp_bMyJailbreak)
{
char EventDay[64];
MyJailbreak_GetEventDayName(EventDay);
if (!StrEqual(EventDay, "none", false))
{
CReplyToCommand(client, "%s %t", g_sPrefix, "zeus_progress", EventDay);
return Plugin_Handled;
}
}
if (g_iCoolDown > 0)
{
CReplyToCommand(client, "%s %t", g_sPrefix, "zeus_wait", g_iCoolDown);
return Plugin_Handled;
}
StartEventRound(gc_bBeginSetW.BoolValue);
if (!gp_bMyJailbreak)
return Plugin_Handled;
if (MyJailbreak_ActiveLogging())
{
LogToFileEx(g_sEventsLogFile, "Event Zeus was started by warden %L", client);
}
}
else
{
CReplyToCommand(client, "%s %t", g_sPrefix, "warden_notwarden");
}
return Plugin_Handled;
}
// Voting for Event
public Action Command_VoteZeus(int client, int args)
{
if (!gc_bPlugin.BoolValue)
{
CReplyToCommand(client, "%s %t", g_sPrefix, "zeus_disabled");
return Plugin_Handled;
}
if (!gc_bVote.BoolValue)
{
CReplyToCommand(client, "%s %t", g_sPrefix, "zeus_voting");
return Plugin_Handled;
}
if (GetTeamClientCount(CS_TEAM_CT) == 0 || GetTeamClientCount(CS_TEAM_T) == 0)
{
CReplyToCommand(client, "%s %t", g_sPrefix, "zeus_minplayer");
return Plugin_Handled;
}
if (gp_bMyJailbreak)
{
char EventDay[64];
MyJailbreak_GetEventDayName(EventDay);
if (!StrEqual(EventDay, "none", false))
{
CReplyToCommand(client, "%s %t", g_sPrefix, "zeus_progress", EventDay);
return Plugin_Handled;
}
}
if (g_iCoolDown > 0)
{
CReplyToCommand(client, "%s %t", g_sPrefix, "zeus_wait", g_iCoolDown);
return Plugin_Handled;
}
char steamid[24];
GetClientAuthId(client, AuthId_Steam2, steamid, sizeof(steamid));
if (StrContains(g_sHasVoted, steamid, true) != -1)
{
CReplyToCommand(client, "%s %t", g_sPrefix, "zeus_voted");
return Plugin_Handled;
}
int playercount = (GetClientCount(true) / 2);
g_iVoteCount += 1;
int Missing = playercount - g_iVoteCount + 1;
Format(g_sHasVoted, sizeof(g_sHasVoted), "%s, %s", g_sHasVoted, steamid);
if (g_iVoteCount > playercount)
{
StartEventRound(gc_bBeginSetV.BoolValue);
if (!gp_bMyJailbreak)
return Plugin_Handled;
if (MyJailbreak_ActiveLogging())
{
LogToFileEx(g_sEventsLogFile, "Event Zeus was started by voting");
}
}
else
{
CPrintToChatAll("%s %t", g_sPrefix, "zeus_need", Missing, client);
}
return Plugin_Handled;
}
/******************************************************************************
EVENTS
******************************************************************************/
// Round start
public void Event_RoundStart(Event event, char[] name, bool dontBroadcast)
{
g_bIsRoundEnd = false;
if (!g_bStartZeus && !g_bIsZeus)
{
if (gp_bMyJailbreak)
{
char EventDay[64];
MyJailbreak_GetEventDayName(EventDay);
if (!StrEqual(EventDay, "none", false))
{
g_iCoolDown = gc_iCooldownDay.IntValue + 1;
}
else if (g_iCoolDown > 0)
{
g_iCoolDown -= 1;
}
}
else if (g_iCoolDown > 0)
{
g_iCoolDown -= 1;
}
return;
}
g_bIsZeus = true;
g_bStartZeus = false;
PrepareDay(false);
}
// Round End
public void Event_RoundEnd(Event event, char[] name, bool dontBroadcast)
{
g_bIsRoundEnd = true;
if (g_bIsZeus)
{
for (int i = 1; i <= MaxClients; i++)
{
if (!IsClientInGame(i))
continue;
SetEntProp(i, Prop_Send, "m_CollisionGroup", 5); // 2 - none / 5 - 'default'
}
delete g_hTimerTruce;
delete g_hTimerBeacon;
g_iTruceTime = gc_iTruceTime.IntValue;
int winner = event.GetInt("winner");
if (winner == 2)
{
PrintCenterTextAll("%t", "zeus_twin_nc");
}
if (winner == 3)
{
PrintCenterTextAll("%t", "zeus_ctwin_nc");
}
if (g_iRound == g_iMaxRound)
{
g_bIsZeus = false;
g_bStartZeus = false;
g_iRound = 0;
Format(g_sHasVoted, sizeof(g_sHasVoted), "");
if (gp_bHosties)
{
SetCvar("sm_hosties_lr", 1);
}
if (gp_bMyJBWarden)
{
warden_enable(true);
}
if (gp_bMyWeapons)
{
MyWeapons_AllowTeam(CS_TEAM_T, false);
MyWeapons_AllowTeam(CS_TEAM_CT, true);
}
SetCvar("sv_infinite_ammo", 0);
SetCvar("mp_teammates_are_enemies", 0);
if (gp_bMyJailbreak)
{
SetCvar("sm_menu_enable", 1);
MyJailbreak_SetEventDayRunning(false, winner);
MyJailbreak_SetEventDayName("none");
}
CPrintToChatAll("%s %t", g_sPrefix, "zeus_end");
}
}
if (g_bStartZeus)
{
for (int i = 1; i <= MaxClients; i++)
{
if (!IsClientInGame(i))
continue;
CreateInfoPanel(i);
}
CPrintToChatAll("%s %t", g_sPrefix, "zeus_next");
PrintCenterTextAll("%t", "zeus_next_nc");
}
}
// Give new Zeus on Kill
public void Event_PlayerDeath(Event event, char[] name, bool dontBroadcast)
{
if (g_bIsZeus)
{
int userid = event.GetInt("attacker");
CreateTimer(0.5, Timer_GiveZeus, userid);
}
}
/******************************************************************************
FORWARDS LISTEN
******************************************************************************/
// Initialize Event
public void OnMapStart()
{
g_iVoteCount = 0;
g_iRound = 0;
g_bIsZeus = false;
g_bStartZeus = false;
g_iCoolDown = gc_iCooldownStart.IntValue + 1;
g_iTruceTime = gc_iTruceTime.IntValue;
if (gc_bOverlays.BoolValue)
{
PrecacheDecalAnyDownload(g_sOverlayStartPath);
}
if (gc_bSounds.BoolValue)
{
PrecacheSoundAnyDownload(g_sSoundStartPath);
}
}
public void MyJailbreak_ResetEventDay()
{
g_bStartZeus = false;
if (g_bIsZeus)
{
g_iRound = g_iMaxRound;
ResetEventDay();
}
}
// Listen for Last Lequest
public void OnAvailableLR(int Announced)
{
if (g_bIsZeus && gc_bAllowLR.BoolValue && (g_iTsLR > g_iTerrorForLR.IntValue))
{
ResetEventDay();
}
}
void ResetEventDay()
{
for (int i = 1; i <= MaxClients; i++)
{
if (!IsClientInGame(i))
continue;
SetEntProp(i, Prop_Send, "m_CollisionGroup", 5); // 2 - none / 5 - 'default'
StripAllPlayerWeapons(i);
if (GetClientTeam(i) == CS_TEAM_CT)
{
FakeClientCommand(i, "sm_weapons");
}
GivePlayerItem(i, "weapon_knife");
SetEntityMoveType(i, MOVETYPE_WALK);
SetEntProp(i, Prop_Data, "m_takedamage", 2, 1);
EnableWeaponFire(i, true);
}
delete g_hTimerBeacon;
delete g_hTimerTruce;
g_iTruceTime = gc_iTruceTime.IntValue;
if (g_iRound == g_iMaxRound)
{
g_bIsZeus = false;
g_bStartZeus = false;
g_iRound = 0;
Format(g_sHasVoted, sizeof(g_sHasVoted), "");
SetCvar("sm_hosties_lr", 1);
SetCvar("sv_infinite_ammo", 0);
SetCvar("mp_teammates_are_enemies", 0);
if (gp_bMyJBWarden)
{
warden_enable(true);
}
if (gp_bMyWeapons)
{
MyWeapons_AllowTeam(CS_TEAM_T, false);
MyWeapons_AllowTeam(CS_TEAM_CT, true);
}
if (gp_bMyJailbreak)
{
SetCvar("sm_menu_enable", 1);
MyJailbreak_SetEventDayName("none");
MyJailbreak_SetEventDayRunning(false, 0);
}
CPrintToChatAll("%s %t", g_sPrefix, "zeus_end");
}
}
// Map End
public void OnMapEnd()
{
g_bIsZeus = false;
g_bStartZeus = false;
delete g_hTimerTruce;
delete g_hTimerBeacon;
g_iVoteCount = 0;
g_iRound = 0;
g_sHasVoted[0] = '\0';
}
// Set Client Hook
public void OnClientPutInServer(int client)
{
SDKHook(client, SDKHook_WeaponCanUse, OnWeaponCanUse);
SDKHook(client, SDKHook_WeaponDrop, OnWeaponDrop);
}
// Knife & Taser only
public Action OnWeaponCanUse(int client, int weapon)
{
if (!g_bIsZeus)
{
return Plugin_Continue;
}
char sWeapon[32];
GetEdictClassname(weapon, sWeapon, sizeof(sWeapon));
if (StrContains(sWeapon, "knife", false) != -1 || StrContains(sWeapon, "bayonet", false) != -1 || StrEqual(sWeapon, "weapon_taser", false))
return Plugin_Continue;
return Plugin_Handled;
}
//Deny weapon drops
public Action OnWeaponDrop(int client, int weapon)
{
if (!g_bIsZeus || gc_bDrop.BoolValue)
return Plugin_Continue;
return Plugin_Handled;
}
/******************************************************************************
FUNCTIONS
******************************************************************************/
// Prepare Event for next round
// Prepare Event
void StartEventRound(bool thisround)
{
g_iCoolDown = gc_iCooldownDay.IntValue;
g_iVoteCount = 0;
if (gp_bMyJailbreak)
{
char buffer[32];
Format(buffer, sizeof(buffer), "%T", "zeus_name", LANG_SERVER);
MyJailbreak_SetEventDayName(buffer);
MyJailbreak_SetEventDayPlanned(true);
}
if (thisround && g_bIsRoundEnd)
{
thisround = false;
}
if (thisround)
{
g_bIsZeus = true;
for (int i = 1; i <= MaxClients; i++)
{
if (!IsValidClient(i, true, true))
continue;
SetEntProp(i, Prop_Data, "m_takedamage", 0, 1);
EnableWeaponFire(i, false);
SetEntityMoveType(i, MOVETYPE_NONE);
}
CreateTimer(3.0, Timer_PrepareEvent);
CPrintToChatAll("%s %t", g_sPrefix, "zeus_now");
PrintCenterTextAll("%t", "zeus_now_nc");
}
else
{
g_bStartZeus = true;
g_iCoolDown++;
CPrintToChatAll("%s %t", g_sPrefix, "zeus_next");
PrintCenterTextAll("%t", "zeus_next_nc");
}
}
public Action Timer_PrepareEvent(Handle timer)
{
if (!g_bIsZeus)
return Plugin_Handled;
PrepareDay(true);
return Plugin_Handled;
}
void PrepareDay(bool thisround)
{
g_iRound++;
if (gp_bSmartJailDoors)
{
SJD_OpenDoors();
}
if ((thisround && gc_bTeleportSpawn.BoolValue) || !gc_bSpawnCell.BoolValue || !gp_bSmartJailDoors || (gc_bSpawnCell.BoolValue && (SJD_IsCurrentMapConfigured() != true))) // spawn Terrors to CT Spawn
{
int RandomCT = 0;
for (int i = 1; i <= MaxClients; i++)
{
if (!IsValidClient(i, true, false))
continue;
if (GetClientTeam(i) == CS_TEAM_CT)
{
CS_RespawnPlayer(i);
RandomCT = i;
break;
}
}
if (RandomCT)
{
for (int i = 1; i <= MaxClients; i++)
{
if (!IsValidClient(i, true, false))
continue;
GetClientAbsOrigin(RandomCT, g_fPos);
g_fPos[2] = g_fPos[2] + 5;
TeleportEntity(i, g_fPos, NULL_VECTOR, NULL_VECTOR);
}
}
}
for (int i = 1; i <= MaxClients; i++)
{
if (!IsClientInGame(i))
continue;
SetEntProp(i, Prop_Send, "m_CollisionGroup", 2); // 2 - none / 5 - 'default'
SetEntProp(i, Prop_Data, "m_takedamage", 0, 1);
EnableWeaponFire(i, false);
SetEntityMoveType(i, MOVETYPE_NONE);
CreateInfoPanel(i);
CreateTimer(0.5, Timer_GiveZeus, GetClientUserId(i));
}
if (gp_bMyJailbreak)
{
SetCvar("sm_menu_enable", 0);
MyJailbreak_SetEventDayPlanned(false);
MyJailbreak_SetEventDayRunning(true, 0);
if (gc_fBeaconTime.FloatValue > 0.0)
{
g_hTimerBeacon = CreateTimer(gc_fBeaconTime.FloatValue, Timer_BeaconOn, TIMER_FLAG_NO_MAPCHANGE);
}
}
if (gp_bMyJBWarden)
{
warden_enable(false);
}
if (gp_bHosties)
{
SetCvar("sm_hosties_lr", 0);
}
SetCvar("mp_teammates_are_enemies", 1);
if (gp_bMyWeapons)
{
MyWeapons_AllowTeam(CS_TEAM_T, false);
MyWeapons_AllowTeam(CS_TEAM_CT, false);
}
if (gp_bHosties)
{
// enable lr on last round
g_iTsLR = GetAlivePlayersCount(CS_TEAM_T);
if (gc_bAllowLR.BoolValue)
{
if (g_iRound == g_iMaxRound && g_iTsLR > g_iTerrorForLR.IntValue)
{
SetCvar("sm_hosties_lr", 1);
}
}
}
GameRules_SetProp("m_iRoundTime", gc_iRoundTime.IntValue*60, 4, 0, true);
g_hTimerTruce = CreateTimer(1.0, Timer_StartEvent, _, TIMER_REPEAT);
CPrintToChatAll("%s %t", g_sPrefix, "zeus_rounds", g_iRound, g_iMaxRound);
}
/******************************************************************************
MENUS
******************************************************************************/
void CreateInfoPanel(int client)
{
// Create info Panel
char info[255];
Panel InfoPanel = new Panel();
Format(info, sizeof(info), "%T", "zeus_info_title", client);
InfoPanel.SetTitle(info);
InfoPanel.DrawText(" ");
Format(info, sizeof(info), "%T", "zeus_info_line1", client);
InfoPanel.DrawText(info);
InfoPanel.DrawText("-----------------------------------");
Format(info, sizeof(info), "%T", "zeus_info_line2", client);
InfoPanel.DrawText(info);
Format(info, sizeof(info), "%T", "zeus_info_line3", client);
InfoPanel.DrawText(info);
Format(info, sizeof(info), "%T", "zeus_info_line4", client);
InfoPanel.DrawText(info);
Format(info, sizeof(info), "%T", "zeus_info_line5", client);
InfoPanel.DrawText(info);
Format(info, sizeof(info), "%T", "zeus_info_line6", client);
InfoPanel.DrawText(info);
Format(info, sizeof(info), "%T", "zeus_info_line7", client);
InfoPanel.DrawText(info);
InfoPanel.DrawText("-----------------------------------");
Format(info, sizeof(info), "%T", "warden_close", client);
InfoPanel.DrawItem(info);
InfoPanel.Send(client, Handler_NullCancel, 20);
}
/******************************************************************************
TIMER
******************************************************************************/
// Start Timer
public Action Timer_StartEvent(Handle timer)
{
g_iTruceTime--;
if (g_iTruceTime > 0)
{
if (g_iTruceTime == gc_iTruceTime.IntValue-3)
{
for (int i = 1; i <= MaxClients; i++)
{
if (!IsValidClient(i, true, false))
continue;
SetEntityMoveType(i, MOVETYPE_WALK);
}
}
PrintCenterTextAll("%t", "zeus_timeuntilstart_nc", g_iTruceTime);
return Plugin_Continue;
}
for (int i = 1; i <= MaxClients; i++)
{
if (!IsValidClient(i, true, true))
continue;
SetEntProp(i, Prop_Data, "m_takedamage", 2, 1);
EnableWeaponFire(i, true);
SetEntityMoveType(i, MOVETYPE_WALK);
if (gc_bOverlays.BoolValue)
{
ShowOverlay(i, g_sOverlayStartPath, 2.0);
}
}
if (gc_bSounds.BoolValue)
{
EmitSoundToAllAny(g_sSoundStartPath);
}
PrintCenterTextAll("%t", "zeus_start_nc");
CPrintToChatAll("%s %t", g_sPrefix, "zeus_start");
g_hTimerTruce = null;
return Plugin_Stop;
}
// Beacon Timer
public Action Timer_BeaconOn(Handle timer)
{
for (int i = 1; i <= MaxClients; i++)
{
if (!IsValidClient(i, true, false))
continue;
MyJailbreak_BeaconOn(i, 2.0);
}
g_hTimerBeacon = null;
}
// Delay give Zeus
public Action Timer_GiveZeus(Handle timer, int userid)
{
int client = GetClientOfUserId(userid);
if (IsValidClient(client, true, false))
{
StripAllPlayerWeapons(client);
GivePlayerItem(client, "weapon_knife");
GivePlayerItem(client, "weapon_taser");
}
}
| 412 | 0.938702 | 1 | 0.938702 | game-dev | MEDIA | 0.490563 | game-dev | 0.879981 | 1 | 0.879981 |
GPUOpen-Archive/CodeXL | 5,147 | CodeXL/AMDTApplicationFramework/src/afGeneralActionsCreator.cpp | //==================================================================================
// Copyright (c) 2016 , Advanced Micro Devices, Inc. All rights reserved.
//
/// \author AMD Developer Tools Team
/// \file afGeneralActionsCreator.cpp
///
//==================================================================================
// QT:
#include <QAction>
// Infra:
#include <AMDTBaseTools/Include/gtAssert.h>
// AMDTApplicationFramework:
#include <AMDTApplicationFramework/Include/afAppStringConstants.h>
#include <AMDTApplicationFramework/Include/afCommandIds.h>
#include <AMDTApplicationFramework/Include/afGeneralActionsCreator.h>
// ---------------------------------------------------------------------------
// Name: afGeneralActionsCreator::afGeneralActionsCreator
// Description: Constructor
// Author: Sigal Algranaty
// Date: 16/9/2011
// ---------------------------------------------------------------------------
afGeneralActionsCreator::afGeneralActionsCreator()
{
}
// ---------------------------------------------------------------------------
// Name: afGeneralActionsCreator::~afGeneralActionsCreator
// Description: Destructor
// Author: Sigal Algranaty
// Date: 16/9/2011
// ---------------------------------------------------------------------------
afGeneralActionsCreator::~afGeneralActionsCreator()
{
}
// ---------------------------------------------------------------------------
// Name: afGeneralActionsCreator::populateSupportedCommandIds
// Description: Create a vector of command Ids that are supported by this actions creator object
// Author: Doron Ofek
// Date: Mar-3, 2015
// ---------------------------------------------------------------------------
void afGeneralActionsCreator::populateSupportedCommandIds()
{
// fill the vector of supported command ids:
m_supportedCommandIds.push_back(ID_CUT);
m_supportedCommandIds.push_back(ID_COPY);
m_supportedCommandIds.push_back(ID_PASTE);
m_supportedCommandIds.push_back(ID_FIND);
m_supportedCommandIds.push_back(ID_FIND_NEXT);
m_supportedCommandIds.push_back(ID_FIND_PREV);
m_supportedCommandIds.push_back(ID_SELECT_ALL);
m_supportedCommandIds.push_back(AF_ID_SAVE_FILE);
m_supportedCommandIds.push_back(AF_ID_SAVE_FILE_AS);
m_supportedCommandIds.push_back(ID_GO_TO);
}
// ---------------------------------------------------------------------------
// Name: afGeneralActionsCreator::menuPosition
// Description: Menu position
// Each hierarchy on the ,emu include name/priority.
// If separator is needed after the item then 's' after the priority is needed
// in case of a sub menu if one item is marked with an 's' it is enough to mark a separator after it:
// Arguments: int actionIndex
// positionData - defines the item position within its parent menu
// Author: Sigal Algranaty
// Date: 16/9/2011
// ---------------------------------------------------------------------------
gtString afGeneralActionsCreator::menuPosition(int actionIndex, afActionPositionData& positionData)
{
gtString retVal;
positionData.m_actionSeparatorType = afActionPositionData::AF_SEPARATOR_NONE;
// Get the command id:
int commandId = actionIndexToCommandId(actionIndex);
switch (commandId)
{
case ID_CUT:
case ID_COPY:
case ID_PASTE:
case ID_FIND_NEXT:
case ID_FIND_PREV:
{
retVal = AF_STR_EditMenuString;
}
break;
case ID_FIND:
case ID_SELECT_ALL:
case ID_GO_TO:
{
positionData.m_actionSeparatorType = afActionPositionData::AF_SEPARATOR_BEFORE_COMMAND;
retVal = AF_STR_EditMenuString;
}
break;
case AF_ID_SAVE_FILE:
case AF_ID_SAVE_FILE_AS:
{
retVal = AF_STR_FileMenuString;
positionData.m_beforeActionMenuPosition = AF_STR_FileMenuString;
positionData.m_beforeActionText = AF_STR_ProjectSettings;
}
break;
default:
GT_ASSERT(false);
break;
};
return retVal;
}
// ---------------------------------------------------------------------------
// Name: afGeneralActionsCreator::toolbarPosition
// Description: Toolbar position
// Arguments: int actionIndex
// Author: Sigal Algranaty
// Date: 16/9/2011
// ---------------------------------------------------------------------------
gtString afGeneralActionsCreator::toolbarPosition(int actionIndex)
{
GT_UNREFERENCED_PARAMETER(actionIndex);
gtString retVal;
return retVal;
}
// ---------------------------------------------------------------------------
// Name: afGeneralActionsCreator::groupAction
// Description: Group actions if needed
// Arguments: int actionIndex
// Author: Sigal Algranaty
// Date: 16/9/2011
// ---------------------------------------------------------------------------
void afGeneralActionsCreator::groupAction(int actionIndex)
{
GT_UNREFERENCED_PARAMETER(actionIndex);
}
| 412 | 0.914133 | 1 | 0.914133 | game-dev | MEDIA | 0.750875 | game-dev | 0.957132 | 1 | 0.957132 |
killop/UnityResourceSolution | 21,604 | Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEngine_GUISkin.cs | //This file was automatically generated by kuroneko.
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace NinjaBeats.ReflectionHelper
{
public partial struct UnityEngine_GUISkin
{
/// <summary>
/// <see cref="UnityEngine.GUISkin"/>
/// </summary>
public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEngine.GUISkin");
public delegate void SkinChangedDelegate();
public UnityEngine.GUIStyle horizontalSliderThumbExtent
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUIStyle)(__horizontalSliderThumbExtent?.GetValue(__self__));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __horizontalSliderThumbExtent?.SetValue(__self__, value);
}
public UnityEngine.GUIStyle sliderMixed
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUIStyle)(__sliderMixed?.GetValue(__self__));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __sliderMixed?.SetValue(__self__, value);
}
public UnityEngine.GUIStyle verticalSliderThumbExtent
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUIStyle)(__verticalSliderThumbExtent?.GetValue(__self__));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __verticalSliderThumbExtent?.SetValue(__self__, value);
}
public static UnityEngine.GUIStyle error
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUIStyle)(__error?.GetValue(null));
}
public UnityEngine.Font m_Font
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.Font)(__m_Font?.GetValue(__self__));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __m_Font?.SetValue(__self__, value);
}
public UnityEngine.GUIStyle m_box
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUIStyle)(__m_box?.GetValue(__self__));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __m_box?.SetValue(__self__, value);
}
public UnityEngine.GUIStyle m_button
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUIStyle)(__m_button?.GetValue(__self__));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __m_button?.SetValue(__self__, value);
}
public UnityEngine.GUIStyle m_toggle
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUIStyle)(__m_toggle?.GetValue(__self__));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __m_toggle?.SetValue(__self__, value);
}
public UnityEngine.GUIStyle m_label
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUIStyle)(__m_label?.GetValue(__self__));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __m_label?.SetValue(__self__, value);
}
public UnityEngine.GUIStyle m_textField
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUIStyle)(__m_textField?.GetValue(__self__));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __m_textField?.SetValue(__self__, value);
}
public UnityEngine.GUIStyle m_textArea
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUIStyle)(__m_textArea?.GetValue(__self__));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __m_textArea?.SetValue(__self__, value);
}
public UnityEngine.GUIStyle m_window
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUIStyle)(__m_window?.GetValue(__self__));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __m_window?.SetValue(__self__, value);
}
public UnityEngine.GUIStyle m_horizontalSlider
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUIStyle)(__m_horizontalSlider?.GetValue(__self__));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __m_horizontalSlider?.SetValue(__self__, value);
}
public UnityEngine.GUIStyle m_horizontalSliderThumb
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUIStyle)(__m_horizontalSliderThumb?.GetValue(__self__));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __m_horizontalSliderThumb?.SetValue(__self__, value);
}
public UnityEngine.GUIStyle m_horizontalSliderThumbExtent
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUIStyle)(__m_horizontalSliderThumbExtent?.GetValue(__self__));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __m_horizontalSliderThumbExtent?.SetValue(__self__, value);
}
public UnityEngine.GUIStyle m_verticalSlider
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUIStyle)(__m_verticalSlider?.GetValue(__self__));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __m_verticalSlider?.SetValue(__self__, value);
}
public UnityEngine.GUIStyle m_verticalSliderThumb
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUIStyle)(__m_verticalSliderThumb?.GetValue(__self__));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __m_verticalSliderThumb?.SetValue(__self__, value);
}
public UnityEngine.GUIStyle m_verticalSliderThumbExtent
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUIStyle)(__m_verticalSliderThumbExtent?.GetValue(__self__));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __m_verticalSliderThumbExtent?.SetValue(__self__, value);
}
public UnityEngine.GUIStyle m_SliderMixed
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUIStyle)(__m_SliderMixed?.GetValue(__self__));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __m_SliderMixed?.SetValue(__self__, value);
}
public UnityEngine.GUIStyle m_horizontalScrollbar
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUIStyle)(__m_horizontalScrollbar?.GetValue(__self__));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __m_horizontalScrollbar?.SetValue(__self__, value);
}
public UnityEngine.GUIStyle m_horizontalScrollbarThumb
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUIStyle)(__m_horizontalScrollbarThumb?.GetValue(__self__));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __m_horizontalScrollbarThumb?.SetValue(__self__, value);
}
public UnityEngine.GUIStyle m_horizontalScrollbarLeftButton
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUIStyle)(__m_horizontalScrollbarLeftButton?.GetValue(__self__));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __m_horizontalScrollbarLeftButton?.SetValue(__self__, value);
}
public UnityEngine.GUIStyle m_horizontalScrollbarRightButton
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUIStyle)(__m_horizontalScrollbarRightButton?.GetValue(__self__));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __m_horizontalScrollbarRightButton?.SetValue(__self__, value);
}
public UnityEngine.GUIStyle m_verticalScrollbar
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUIStyle)(__m_verticalScrollbar?.GetValue(__self__));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __m_verticalScrollbar?.SetValue(__self__, value);
}
public UnityEngine.GUIStyle m_verticalScrollbarThumb
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUIStyle)(__m_verticalScrollbarThumb?.GetValue(__self__));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __m_verticalScrollbarThumb?.SetValue(__self__, value);
}
public UnityEngine.GUIStyle m_verticalScrollbarUpButton
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUIStyle)(__m_verticalScrollbarUpButton?.GetValue(__self__));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __m_verticalScrollbarUpButton?.SetValue(__self__, value);
}
public UnityEngine.GUIStyle m_verticalScrollbarDownButton
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUIStyle)(__m_verticalScrollbarDownButton?.GetValue(__self__));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __m_verticalScrollbarDownButton?.SetValue(__self__, value);
}
public UnityEngine.GUIStyle m_ScrollView
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUIStyle)(__m_ScrollView?.GetValue(__self__));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __m_ScrollView?.SetValue(__self__, value);
}
public UnityEngine.GUIStyle[] m_CustomStyles
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUIStyle[])(__m_CustomStyles?.GetValue(__self__));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __m_CustomStyles?.SetValue(__self__, value);
}
public UnityEngine.GUISettings m_Settings
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUISettings)(__m_Settings?.GetValue(__self__));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __m_Settings?.SetValue(__self__, value);
}
public static UnityEngine.GUIStyle ms_Error
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUIStyle)(__ms_Error?.GetValue(null));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __ms_Error?.SetValue(null, value);
}
public System.Collections.Generic.Dictionary<string, UnityEngine.GUIStyle> m_Styles
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (System.Collections.Generic.Dictionary<string, UnityEngine.GUIStyle>)(__m_Styles?.GetValue(__self__));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __m_Styles?.SetValue(__self__, value);
}
public static SkinChangedDelegate m_SkinChanged
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (__m_SkinChanged?.GetValue(null) as Delegate)?.Cast<SkinChangedDelegate>();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __m_SkinChanged?.SetValue(null, value?.Cast(__m_SkinChanged.FieldType));
}
public static UnityEngine.GUISkin current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUISkin)(__current?.GetValue(null));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => __current?.SetValue(null, value);
}
public void OnEnable()
{
__OnEnable?.Invoke(__self__, System.Array.Empty<object>());
}
public static void CleanupRoots()
{
__CleanupRoots?.Invoke(null, System.Array.Empty<object>());
}
public void Apply()
{
__Apply?.Invoke(__self__, System.Array.Empty<object>());
}
public void BuildStyleCache()
{
__BuildStyleCache?.Invoke(__self__, System.Array.Empty<object>());
}
public void MakeCurrent()
{
__MakeCurrent?.Invoke(__self__, System.Array.Empty<object>());
}
public UnityEngine_GUISkin(object __self__) => this.__self__ = __self__ as UnityEngine.Object;
public UnityEngine.Object __self__;
public bool __valid__
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => __self__ != null && __type__ != null;
}
public UnityEngine.GUISkin __super__
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (UnityEngine.GUISkin)(__self__);
}
private static FieldInfo ___m_Font;
private static FieldInfo __m_Font
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___m_Font ??= __type__?.GetField("m_Font", (BindingFlags)(-1));
}
private static FieldInfo ___m_box;
private static FieldInfo __m_box
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___m_box ??= __type__?.GetField("m_box", (BindingFlags)(-1));
}
private static FieldInfo ___m_button;
private static FieldInfo __m_button
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___m_button ??= __type__?.GetField("m_button", (BindingFlags)(-1));
}
private static FieldInfo ___m_toggle;
private static FieldInfo __m_toggle
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___m_toggle ??= __type__?.GetField("m_toggle", (BindingFlags)(-1));
}
private static FieldInfo ___m_label;
private static FieldInfo __m_label
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___m_label ??= __type__?.GetField("m_label", (BindingFlags)(-1));
}
private static FieldInfo ___m_textField;
private static FieldInfo __m_textField
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___m_textField ??= __type__?.GetField("m_textField", (BindingFlags)(-1));
}
private static FieldInfo ___m_textArea;
private static FieldInfo __m_textArea
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___m_textArea ??= __type__?.GetField("m_textArea", (BindingFlags)(-1));
}
private static FieldInfo ___m_window;
private static FieldInfo __m_window
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___m_window ??= __type__?.GetField("m_window", (BindingFlags)(-1));
}
private static FieldInfo ___m_horizontalSlider;
private static FieldInfo __m_horizontalSlider
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___m_horizontalSlider ??= __type__?.GetField("m_horizontalSlider", (BindingFlags)(-1));
}
private static FieldInfo ___m_horizontalSliderThumb;
private static FieldInfo __m_horizontalSliderThumb
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___m_horizontalSliderThumb ??= __type__?.GetField("m_horizontalSliderThumb", (BindingFlags)(-1));
}
private static FieldInfo ___m_horizontalSliderThumbExtent;
private static FieldInfo __m_horizontalSliderThumbExtent
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___m_horizontalSliderThumbExtent ??= __type__?.GetField("m_horizontalSliderThumbExtent", (BindingFlags)(-1));
}
private static FieldInfo ___m_verticalSlider;
private static FieldInfo __m_verticalSlider
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___m_verticalSlider ??= __type__?.GetField("m_verticalSlider", (BindingFlags)(-1));
}
private static FieldInfo ___m_verticalSliderThumb;
private static FieldInfo __m_verticalSliderThumb
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___m_verticalSliderThumb ??= __type__?.GetField("m_verticalSliderThumb", (BindingFlags)(-1));
}
private static FieldInfo ___m_verticalSliderThumbExtent;
private static FieldInfo __m_verticalSliderThumbExtent
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___m_verticalSliderThumbExtent ??= __type__?.GetField("m_verticalSliderThumbExtent", (BindingFlags)(-1));
}
private static FieldInfo ___m_SliderMixed;
private static FieldInfo __m_SliderMixed
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___m_SliderMixed ??= __type__?.GetField("m_SliderMixed", (BindingFlags)(-1));
}
private static FieldInfo ___m_horizontalScrollbar;
private static FieldInfo __m_horizontalScrollbar
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___m_horizontalScrollbar ??= __type__?.GetField("m_horizontalScrollbar", (BindingFlags)(-1));
}
private static FieldInfo ___m_horizontalScrollbarThumb;
private static FieldInfo __m_horizontalScrollbarThumb
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___m_horizontalScrollbarThumb ??= __type__?.GetField("m_horizontalScrollbarThumb", (BindingFlags)(-1));
}
private static FieldInfo ___m_horizontalScrollbarLeftButton;
private static FieldInfo __m_horizontalScrollbarLeftButton
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___m_horizontalScrollbarLeftButton ??= __type__?.GetField("m_horizontalScrollbarLeftButton", (BindingFlags)(-1));
}
private static FieldInfo ___m_horizontalScrollbarRightButton;
private static FieldInfo __m_horizontalScrollbarRightButton
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___m_horizontalScrollbarRightButton ??= __type__?.GetField("m_horizontalScrollbarRightButton", (BindingFlags)(-1));
}
private static FieldInfo ___m_verticalScrollbar;
private static FieldInfo __m_verticalScrollbar
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___m_verticalScrollbar ??= __type__?.GetField("m_verticalScrollbar", (BindingFlags)(-1));
}
private static FieldInfo ___m_verticalScrollbarThumb;
private static FieldInfo __m_verticalScrollbarThumb
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___m_verticalScrollbarThumb ??= __type__?.GetField("m_verticalScrollbarThumb", (BindingFlags)(-1));
}
private static FieldInfo ___m_verticalScrollbarUpButton;
private static FieldInfo __m_verticalScrollbarUpButton
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___m_verticalScrollbarUpButton ??= __type__?.GetField("m_verticalScrollbarUpButton", (BindingFlags)(-1));
}
private static FieldInfo ___m_verticalScrollbarDownButton;
private static FieldInfo __m_verticalScrollbarDownButton
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___m_verticalScrollbarDownButton ??= __type__?.GetField("m_verticalScrollbarDownButton", (BindingFlags)(-1));
}
private static FieldInfo ___m_ScrollView;
private static FieldInfo __m_ScrollView
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___m_ScrollView ??= __type__?.GetField("m_ScrollView", (BindingFlags)(-1));
}
private static FieldInfo ___m_CustomStyles;
private static FieldInfo __m_CustomStyles
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___m_CustomStyles ??= __type__?.GetField("m_CustomStyles", (BindingFlags)(-1));
}
private static FieldInfo ___m_Settings;
private static FieldInfo __m_Settings
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___m_Settings ??= __type__?.GetField("m_Settings", (BindingFlags)(-1));
}
private static FieldInfo ___ms_Error;
private static FieldInfo __ms_Error
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___ms_Error ??= __type__?.GetField("ms_Error", (BindingFlags)(-1));
}
private static FieldInfo ___m_Styles;
private static FieldInfo __m_Styles
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___m_Styles ??= __type__?.GetField("m_Styles", (BindingFlags)(-1));
}
private static FieldInfo ___m_SkinChanged;
private static FieldInfo __m_SkinChanged
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___m_SkinChanged ??= __type__?.GetField("m_SkinChanged", (BindingFlags)(-1));
}
private static FieldInfo ___current;
private static FieldInfo __current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___current ??= __type__?.GetField("current", (BindingFlags)(-1));
}
private static PropertyInfo ___horizontalSliderThumbExtent;
private static PropertyInfo __horizontalSliderThumbExtent
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___horizontalSliderThumbExtent ??= __type__?.GetProperty("horizontalSliderThumbExtent", (BindingFlags)(-1));
}
private static PropertyInfo ___sliderMixed;
private static PropertyInfo __sliderMixed
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___sliderMixed ??= __type__?.GetProperty("sliderMixed", (BindingFlags)(-1));
}
private static PropertyInfo ___verticalSliderThumbExtent;
private static PropertyInfo __verticalSliderThumbExtent
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___verticalSliderThumbExtent ??= __type__?.GetProperty("verticalSliderThumbExtent", (BindingFlags)(-1));
}
private static PropertyInfo ___error;
private static PropertyInfo __error
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___error ??= __type__?.GetProperty("error", (BindingFlags)(-1));
}
private static MethodInfo ___OnEnable;
private static MethodInfo __OnEnable
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___OnEnable ??= __type__?.GetMethodInfoByParameterTypeNames("OnEnable");
}
private static MethodInfo ___CleanupRoots;
private static MethodInfo __CleanupRoots
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___CleanupRoots ??= __type__?.GetMethodInfoByParameterTypeNames("CleanupRoots");
}
private static MethodInfo ___Apply;
private static MethodInfo __Apply
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___Apply ??= __type__?.GetMethodInfoByParameterTypeNames("Apply");
}
private static MethodInfo ___BuildStyleCache;
private static MethodInfo __BuildStyleCache
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___BuildStyleCache ??= __type__?.GetMethodInfoByParameterTypeNames("BuildStyleCache");
}
private static MethodInfo ___MakeCurrent;
private static MethodInfo __MakeCurrent
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ___MakeCurrent ??= __type__?.GetMethodInfoByParameterTypeNames("MakeCurrent");
}
}
public static class UnityEngine_GUISkin_Extension
{
public static UnityEngine_GUISkin ReflectionHelper(this UnityEngine.GUISkin self) => new(self);
}
}
| 412 | 0.806191 | 1 | 0.806191 | game-dev | MEDIA | 0.883962 | game-dev | 0.760205 | 1 | 0.760205 |
IdleLands/IdleLands | 1,183 | src/server/core/game/achievements/TinyTerror.ts | import { AchievementType, AchievementRewardType, Achievement } from '../../../../shared/interfaces';
import { Player } from '../../../../shared/models';
export class TinyTerror extends Achievement {
static readonly statWatches = ['Item/Collectible/Find'];
static readonly type = AchievementType.Explore;
static descriptionForTier(tier: number): string {
const baseStr = `Gain two tiny genders and a title for being a master of the dwarves.`;
return baseStr;
}
static calculateTier(player: Player): number {
const coll1 = player.$collectibles.has('Dwarven Coin');
const coll2 = player.$collectibles.has('Dwarven Protection Rune');
const coll3 = player.$collectibles.has('Crystal Maul');
const kill = player.$statistics.get('BossKill/Boss/Venerable Dwarven Lord');
return coll1 && coll2 && coll3 && kill ? 1 : 0;
}
static rewardsForTier(tier: number): any[] {
const baseRewards: any[] = [
{ type: AchievementRewardType.Title, title: 'Dwarven Lord' },
{ type: AchievementRewardType.Gender, gender: 'dwarf male' },
{ type: AchievementRewardType.Gender, gender: 'dwarf female' }
];
return baseRewards;
}
}
| 412 | 0.872893 | 1 | 0.872893 | game-dev | MEDIA | 0.52949 | game-dev | 0.957768 | 1 | 0.957768 |
Impostor/Impostor | 1,070 | src/Impostor.Server/Net/Inner/Objects/GameManager/Logic/LogicOptions.cs | using System.Threading.Tasks;
using Impostor.Api.Events.Managers;
using Impostor.Api.Innersloth.GameOptions;
using Impostor.Server.Events;
using Impostor.Server.Net.State;
namespace Impostor.Server.Net.Inner.Objects.GameManager.Logic;
internal abstract class LogicOptions : GameLogicComponent
{
private readonly Game _game;
private readonly IEventManager _eventManager;
protected LogicOptions(Game game, IEventManager eventManager)
{
_game = game;
_eventManager = eventManager;
}
public override ValueTask<bool> SerializeAsync(IMessageWriter writer, bool initialState)
{
GameOptionsFactory.Serialize(writer, _game.Options);
return ValueTask.FromResult(true);
}
public override async ValueTask DeserializeAsync(IMessageReader reader, bool initialState)
{
GameOptionsFactory.DeserializeInto(reader, _game.Options);
await _eventManager.CallAsync(new GameOptionsChangedEvent(
_game,
Api.Events.IGameOptionsChangedEvent.ChangeReason.Host
));
}
}
| 412 | 0.755227 | 1 | 0.755227 | game-dev | MEDIA | 0.53458 | game-dev | 0.704788 | 1 | 0.704788 |
joschu/trajopt | 3,136 | ext/bullet/src/BulletCollision/CollisionShapes/btMultiSphereShape.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_MULTI_SPHERE_MINKOWSKI_H
#define BT_MULTI_SPHERE_MINKOWSKI_H
#include "btConvexInternalShape.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" // for the types
#include "LinearMath/btAlignedObjectArray.h"
#include "LinearMath/btAabbUtil2.h"
///The btMultiSphereShape represents the convex hull of a collection of spheres. You can create special capsules or other smooth volumes.
///It is possible to animate the spheres for deformation, but call 'recalcLocalAabb' after changing any sphere position/radius
ATTRIBUTE_ALIGNED16(class) btMultiSphereShape : public btConvexInternalAabbCachingShape
{
btAlignedObjectArray<btVector3> m_localPositionArray;
btAlignedObjectArray<btScalar> m_radiArray;
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
btMultiSphereShape (const btVector3* positions,const btScalar* radi,int numSpheres);
///CollisionShape Interface
virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const;
/// btConvexShape Interface
virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec)const;
virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const;
int getSphereCount() const
{
return m_localPositionArray.size();
}
const btVector3& getSpherePosition(int index) const
{
return m_localPositionArray[index];
}
btScalar getSphereRadius(int index) const
{
return m_radiArray[index];
}
virtual const char* getName()const
{
return "MultiSphere";
}
virtual int calculateSerializeBufferSize() const;
///fills the dataBuffer and returns the struct name (and 0 on failure)
virtual const char* serialize(void* dataBuffer, btSerializer* serializer) const;
};
struct btPositionAndRadius
{
btVector3FloatData m_pos;
float m_radius;
};
struct btMultiSphereShapeData
{
btConvexInternalShapeData m_convexInternalShapeData;
btPositionAndRadius *m_localPositionArrayPtr;
int m_localPositionArraySize;
char m_padding[4];
};
SIMD_FORCE_INLINE int btMultiSphereShape::calculateSerializeBufferSize() const
{
return sizeof(btMultiSphereShapeData);
}
#endif //BT_MULTI_SPHERE_MINKOWSKI_H
| 412 | 0.926926 | 1 | 0.926926 | game-dev | MEDIA | 0.979092 | game-dev | 0.822789 | 1 | 0.822789 |
glKarin/com.n0n3m4.diii4a | 13,843 | Q3E/src/main/jni/source/utils/vcdupdate/vcdupdate.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// The copyright to the contents herein is the property of Valve, L.L.C.
// The contents may be used and/or copied only with the written permission of
// Valve, L.L.C., or in accordance with the terms and conditions stipulated in
// the agreement/contract under which the contents have been supplied.
//
// $Header: $
// $NoKeywords: $
//
//=============================================================================
// Valve includes
#include "appframework/tier3app.h"
#include "datamodel/idatamodel.h"
#include "filesystem.h"
#include "icommandline.h"
#include "materialsystem/imaterialsystem.h"
#include "istudiorender.h"
#include "mathlib/mathlib.h"
#include "tier2/p4helpers.h"
#include "p4lib/ip4.h"
#include "sfmobjects/sfmsession.h"
#include "datacache/idatacache.h"
#include "datacache/imdlcache.h"
#include "vphysics_interface.h"
#include "studio.h"
#include "soundemittersystem/isoundemittersystembase.h"
#include "tier2/soundutils.h"
#include "tier2/fileutils.h"
#include "tier3/choreoutils.h"
#include "tier3/scenetokenprocessor.h"
#include "soundchars.h"
#include "choreoscene.h"
#include "choreoactor.h"
#include "choreochannel.h"
#include "choreoevent.h"
#include <ctype.h>
#ifdef _DEBUG
#include <windows.h>
#undef GetCurrentDirectory
#endif
//-----------------------------------------------------------------------------
// Standard spew functions
//-----------------------------------------------------------------------------
static SpewRetval_t SpewStdout( SpewType_t spewType, char const *pMsg )
{
if ( !pMsg )
return SPEW_CONTINUE;
#ifdef _DEBUG
OutputDebugString( pMsg );
#endif
printf( pMsg );
fflush( stdout );
return ( spewType == SPEW_ASSERT ) ? SPEW_DEBUGGER : SPEW_CONTINUE;
}
//-----------------------------------------------------------------------------
// The application object
//-----------------------------------------------------------------------------
class CVcdUpdateApp : public CTier3SteamApp
{
typedef CTier3SteamApp BaseClass;
public:
// Methods of IApplication
virtual bool Create();
virtual bool PreInit( );
virtual int Main();
virtual void Destroy() {}
void PrintHelp( );
private:
struct VcdUpdateInfo_t
{
const char *m_pChangedWAVFile;
const char *m_pChangedMDLFile;
bool m_bWarnMissingMDL;
bool m_bWarnNotMatchingMDL;
};
void UpdateVcdFiles( const VcdUpdateInfo_t& info );
void UpdateVcd( const char *pFullPath, const VcdUpdateInfo_t& info, studiohdr_t *pStudioHdr, float flWavDuration );
bool UpdateVcd( CChoreoScene *pScene, const VcdUpdateInfo_t& info, studiohdr_t *pStudioHdr, float flWavDuration );
};
DEFINE_CONSOLE_STEAM_APPLICATION_OBJECT( CVcdUpdateApp );
//-----------------------------------------------------------------------------
// The application object
//-----------------------------------------------------------------------------
bool CVcdUpdateApp::Create()
{
SpewOutputFunc( SpewStdout );
AppSystemInfo_t appSystems[] =
{
{ "materialsystem.dll", MATERIAL_SYSTEM_INTERFACE_VERSION },
{ "p4lib.dll", P4_INTERFACE_VERSION },
{ "datacache.dll", DATACACHE_INTERFACE_VERSION },
{ "datacache.dll", MDLCACHE_INTERFACE_VERSION },
{ "studiorender.dll", STUDIO_RENDER_INTERFACE_VERSION },
{ "vphysics.dll", VPHYSICS_INTERFACE_VERSION },
{ "soundemittersystem.dll", SOUNDEMITTERSYSTEM_INTERFACE_VERSION },
{ "", "" } // Required to terminate the list
};
AddSystems( appSystems );
IMaterialSystem *pMaterialSystem = reinterpret_cast< IMaterialSystem * >( FindSystem( MATERIAL_SYSTEM_INTERFACE_VERSION ) );
if ( !pMaterialSystem )
{
Error( "// ERROR: Unable to connect to material system interface!\n" );
return false;
}
pMaterialSystem->SetShaderAPI( "shaderapiempty.dll" );
return true;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
bool CVcdUpdateApp::PreInit( )
{
MathLib_Init( 2.2f, 2.2f, 0.0f, 2.0f, false, false, false, false );
if ( !BaseClass::PreInit() )
return false;
if ( !g_pFullFileSystem || !g_pMDLCache )
{
Error( "// ERROR: vcdupdate is missing a required interface!\n" );
return false;
}
// Add paths...
if ( !SetupSearchPaths( NULL, false, true ) )
return false;
return true;
}
//-----------------------------------------------------------------------------
// Print help
//-----------------------------------------------------------------------------
void CVcdUpdateApp::PrintHelp( )
{
Msg( "Usage: vcdupdate [-w <modified .wav file>] [-m <modified .mdl file>] [-e] [-n]\n" );
Msg( " [-nop4] [-vproject <path to gameinfo.txt>]\n" );
Msg( "vcdupdate will fixup all vcd files in the tree to account for other asset changes.\n" );
Msg( "\t-w\t: Specifies the relative path to a .wav file that has changed.\n" );
Msg( "\t-m\t: Specifies the relative path to a .mdl file that has changed.\n" );
Msg( "\t-e\t: [Optional] Displays a warning about all .vcds that don't have actors w/ associated .mdls\n" );
Msg( "\t\tSuch files cannot be auto-updated by vcdupdate and also can generate bugs.\n" );
Msg( "\t-n\t: [Optional] Displays a warning about all .vcds whose actor names\n" );
Msg( "\t\tare suspiciously different from the associated .mdl\n" );
Msg( "\t-nop4\t: Disables auto perforce checkout/add.\n" );
Msg( "\t-vproject\t: Specifies path to a gameinfo.txt file (which mod to build for).\n" );
}
//-----------------------------------------------------------------------------
// Checks a single VCD to see if it needs to be updated or not.
//-----------------------------------------------------------------------------
bool CVcdUpdateApp::UpdateVcd( CChoreoScene *pScene, const VcdUpdateInfo_t& info, studiohdr_t *pStudioHdr, float flWavDuration )
{
CStudioHdr studioHdr( pStudioHdr, g_pMDLCache );
float pPoseParameters[MAXSTUDIOPOSEPARAM];
memset( pPoseParameters, 0, MAXSTUDIOPOSEPARAM * sizeof(float) );
char pModelPath[MAX_PATH];
if ( pStudioHdr )
{
g_pFullFileSystem->FullPathToRelativePathEx( info.m_pChangedMDLFile, "GAME", pModelPath, sizeof(pModelPath) );
}
bool bChanged = false;
int c = pScene->GetNumEvents();
for ( int i = 0; i < c; i++ )
{
CChoreoEvent *pEvent = pScene->GetEvent( i );
if ( !pEvent )
continue;
switch ( pEvent->GetType() )
{
default:
break;
case CChoreoEvent::SPEAK:
{
if ( !info.m_pChangedWAVFile )
continue;
const char *pWavFile = GetSoundForEvent( pEvent, &studioHdr );
if ( !pWavFile )
continue;
char pRelativeWAVFile[MAX_PATH];
Q_ComposeFileName( "sound", pWavFile, pRelativeWAVFile, sizeof(pRelativeWAVFile) );
char pFullWAVFile[MAX_PATH];
g_pFullFileSystem->RelativePathToFullPath( pRelativeWAVFile, "GAME", pFullWAVFile, sizeof(pFullWAVFile) );
if ( Q_stricmp( pFullWAVFile, info.m_pChangedWAVFile ) )
continue;
float flEndTime = pEvent->GetStartTime() + flWavDuration;
if ( pEvent->GetEndTime() != flEndTime )
{
pEvent->SetEndTime( pEvent->GetStartTime() + flEndTime );
bChanged = true;
}
}
break;
case CChoreoEvent::SEQUENCE:
{
if ( !pStudioHdr )
continue;
CChoreoActor *pActor = pEvent->GetActor();
if ( pActor->GetName()[0] == '!' )
continue;
const char *pModelName = pActor->GetFacePoserModelName();
if ( !pModelName || !pModelName[0] || Q_stricmp( pModelPath, pModelName) )
continue;
if ( UpdateSequenceLength( pEvent, &studioHdr, pPoseParameters, false, false ) )
{
bChanged = true;
}
}
break;
case CChoreoEvent::GESTURE:
{
if ( !pStudioHdr )
continue;
CChoreoActor *pActor = pEvent->GetActor();
if ( pActor->GetName()[0] == '!' )
continue;
const char *pModelName = pActor->GetFacePoserModelName();
if ( !pModelName || !pModelName[0] || Q_stricmp( pModelPath, pModelName ) )
continue;
if ( UpdateGestureLength( pEvent, &studioHdr, pPoseParameters, false ) )
{
bChanged = true;
}
if ( AutoAddGestureKeys( pEvent, &studioHdr, pPoseParameters, false ) )
{
bChanged = true;
}
}
break;
}
}
return bChanged;
}
//-----------------------------------------------------------------------------
// Checks a single VCD to see if it needs to be updated or not.
//-----------------------------------------------------------------------------
void CVcdUpdateApp::UpdateVcd( const char *pFullPath, const VcdUpdateInfo_t& info, studiohdr_t *pStudioHdr, float flWavDuration )
{
CUtlBuffer buf;
if ( !g_pFullFileSystem->ReadFile( pFullPath, NULL, buf ) )
{
Warning( "Unable to load file %s\n", pFullPath );
return;
}
SetTokenProcessorBuffer( (char *)buf.Base() );
CChoreoScene *pScene = ChoreoLoadScene( pFullPath, NULL, GetTokenProcessor(), NULL );
if ( !pScene )
{
Warning( "Unable to parse file %s\n", pFullPath );
return;
}
// Check for validity.
if ( info.m_bWarnNotMatchingMDL || info.m_bWarnMissingMDL )
{
char pBaseModelName[MAX_PATH];
int nActorCount = pScene->GetNumActors();
for ( int i = 0; i < nActorCount; ++i )
{
CChoreoActor* pActor = pScene->GetActor( i );
const char *pActorName = pActor->GetName();
if ( pActorName[0] == '!' )
continue;
const char *pModelName = pActor->GetFacePoserModelName();
if ( !pModelName || !pModelName[0] )
{
if ( info.m_bWarnMissingMDL )
{
Warning( "\t*** Missing .mdl association: File \"%s\"\tActor \"%s\"\n", pFullPath, pActorName );
}
continue;
}
if ( info.m_bWarnNotMatchingMDL )
{
Q_FileBase( pModelName, pBaseModelName, sizeof(pBaseModelName) );
if ( !StringHasPrefix( pActorName, pBaseModelName ) )
{
Warning( "\t*** File \"%s\": Actor name and .mdl name suspiciously different:\n\t\tMDL \"%s\"\tActor \"%s\"\n", pFullPath, pModelName, pActorName );
}
}
}
}
if ( UpdateVcd( pScene, info, pStudioHdr, flWavDuration ) )
{
Warning( "*** VCD %s requires update.\n", pFullPath );
CP4AutoEditAddFile checkout( pFullPath );
pScene->SaveToFile( pFullPath );
}
}
//-----------------------------------------------------------------------------
// Loads up the changed files and builds list of vcds to convert, then converts them
//-----------------------------------------------------------------------------
void CVcdUpdateApp::UpdateVcdFiles( const VcdUpdateInfo_t& info )
{
studiohdr_t *pStudioHdr = NULL;
if ( info.m_pChangedMDLFile )
{
char pRelativeModelPath[MAX_PATH];
g_pFullFileSystem->FullPathToRelativePathEx( info.m_pChangedMDLFile, "GAME", pRelativeModelPath, sizeof(pRelativeModelPath) );
Q_SetExtension( pRelativeModelPath, ".mdl", sizeof(pRelativeModelPath) );
MDLHandle_t hMDL = g_pMDLCache->FindMDL( pRelativeModelPath );
if ( hMDL == MDLHANDLE_INVALID )
{
Warning( "vcdupdate: Model %s doesn't exist!\n", pRelativeModelPath );
return;
}
pStudioHdr = g_pMDLCache->GetStudioHdr( hMDL );
if ( !pStudioHdr || g_pMDLCache->IsErrorModel( hMDL ) )
{
Warning( "vcdupdate: Model %s doesn't exist!\n", pRelativeModelPath );
return;
}
}
float flWavDuration = -1.0f;
if ( info.m_pChangedWAVFile )
{
flWavDuration = GetWavSoundDuration( info.m_pChangedWAVFile );
}
CUtlVector< CUtlString > dirs;
CUtlVector< CUtlString > vcds;
GetSearchPath( dirs, "GAME" );
int nCount = dirs.Count();
for ( int i = 0; i < nCount; ++i )
{
char pScenePath[MAX_PATH];
Q_ComposeFileName( dirs[i], "scenes", pScenePath, sizeof(pScenePath) );
AddFilesToList( vcds, pScenePath, NULL, "vcd" );
}
int nVCDCount = vcds.Count();
Msg( "Found %d VCDs to check if update is necessary.\n", nVCDCount );
for ( int i = 0; i < nVCDCount; ++i )
{
UpdateVcd( vcds[i], info, pStudioHdr, flWavDuration );
}
}
//-----------------------------------------------------------------------------
// The application object
//-----------------------------------------------------------------------------
int CVcdUpdateApp::Main()
{
// This bit of hackery allows us to access files on the harddrive
g_pFullFileSystem->AddSearchPath( "", "LOCAL", PATH_ADD_TO_HEAD );
if ( CommandLine()->CheckParm( "-h" ) || CommandLine()->CheckParm( "-help" ) )
{
PrintHelp();
return 0;
}
VcdUpdateInfo_t info;
info.m_pChangedWAVFile = CommandLine()->ParmValue( "-w" );
info.m_pChangedMDLFile = CommandLine()->ParmValue( "-m" );
info.m_bWarnMissingMDL = CommandLine()->ParmValue( "-e" ) ? true : false;
info.m_bWarnNotMatchingMDL = CommandLine()->ParmValue( "-n" ) ? true : false;
if ( !info.m_pChangedWAVFile && !info.m_pChangedMDLFile )
{
PrintHelp();
return 0;
}
// Determine full paths
char pFullMDLPath[MAX_PATH];
char pFullWAVPath[MAX_PATH];
if ( info.m_pChangedMDLFile )
{
char pRelativeMDLPath[MAX_PATH];
if ( !Q_IsAbsolutePath( info.m_pChangedMDLFile ) )
{
Q_ComposeFileName( "models", info.m_pChangedMDLFile, pRelativeMDLPath, sizeof(pRelativeMDLPath) );
g_pFullFileSystem->RelativePathToFullPath( pRelativeMDLPath, "GAME", pFullMDLPath, sizeof(pFullMDLPath) );
}
info.m_pChangedMDLFile = pFullMDLPath;
}
if ( info.m_pChangedWAVFile )
{
char pRelativeWAVPath[MAX_PATH];
if ( !Q_IsAbsolutePath( info.m_pChangedWAVFile ) )
{
Q_ComposeFileName( "sound", info.m_pChangedWAVFile, pRelativeWAVPath, sizeof(pRelativeWAVPath) );
g_pFullFileSystem->RelativePathToFullPath( pRelativeWAVPath, "GAME", pFullWAVPath, sizeof(pFullWAVPath) );
}
info.m_pChangedWAVFile = pFullWAVPath;
}
// Do Perforce Stuff
if ( CommandLine()->FindParm( "-nop4" ) )
{
g_p4factory->SetDummyMode( true );
}
g_p4factory->SetOpenFileChangeList( "Automatically Updated VCD files" );
g_pSoundEmitterSystem->ModInit();
UpdateVcdFiles( info );
g_pSoundEmitterSystem->ModShutdown();
return -1;
} | 412 | 0.967065 | 1 | 0.967065 | game-dev | MEDIA | 0.776276 | game-dev | 0.850751 | 1 | 0.850751 |
reduz/larvita3 | 3,385 | tools/FCollada/FCDocument/FCDAnimationChannel.h | /*
Copyright (C) 2005-2007 Feeling Software Inc.
Portions of the code are:
Copyright (C) 2005-2007 Sony Computer Entertainment America
MIT License: http://www.opensource.org/licenses/mit-license.php
*/
/*
Based on the FS Import classes:
Copyright (C) 2005-2006 Feeling Software Inc
Copyright (C) 2005-2006 Autodesk Media Entertainment
MIT License: http://www.opensource.org/licenses/mit-license.php
*/
/**
@file FCDAnimationChannel.h
This file contains the FCDAnimationChannel class.
*/
#ifndef _FCD_ANIMATION_CHANNEL_H_
#define _FCD_ANIMATION_CHANNEL_H_
#ifndef __FCD_OBJECT_H_
#include "FCDocument/FCDObject.h"
#endif // __FCD_OBJECT_H_
#ifndef _FU_PARAMETER_H_
#include "FUtils/FUParameter.h"
#endif // _FU_PARAMETER_H_
class FCDAnimated;
class FCDAnimation;
class FCDAnimationCurve;
typedef fm::pvector<FCDAnimationCurve> FCDAnimationCurveList; /**< A dynamically-sized array of animation curves. */
/**
A COLLADA animation channel.
Each animation channel holds the animation curves for one animatable element,
such as a single floating-point value, a 3D vector or a matrix.
@see FCDAnimated
@ingroup FCDocument
*/
class FCOLLADA_EXPORT FCDAnimationChannel : public FCDObject
{
private:
DeclareObjectType(FCDObject);
FCDAnimation* parent;
DeclareParameterContainer(FCDAnimationCurve, curves, FC("Animation Curves"));
public:
/** Constructor: do not use directly.
Instead, call the FCDAnimation::AddChannel function.
@param document The COLLADA document that owns the animation channel.
@param parent The animation sub-tree that contains the animation channel. */
FCDAnimationChannel(FCDocument* document, FCDAnimation* parent);
/** Destructor. */
virtual ~FCDAnimationChannel();
/** Copies the animation channel into a clone.
The clone may reside in another document.
@param clone The empty clone. If this pointer is NULL, a new animation channel
will be created and you will need to release the returned pointer manually.
@return The clone. */
FCDAnimationChannel* Clone(FCDAnimationChannel* clone = NULL) const;
/** Retrieves the animation sub-tree that contains the animation channel.
@return The parent animation sub-tree. */
FCDAnimation* GetParent() { return parent; }
const FCDAnimation* GetParent() const { return parent; } /**< See above. */
/** Retrieves the list of animation curves contained within the channel.
@deprecated
@return The list of animation curves. */
DEPRECATED(3.05A, GetCurveCount and GetCurve(index))
void GetCurves() const {}
/** Retrieves the number of animation curves contained within the channel.
@return The number of animation curves. */
size_t GetCurveCount() const { return curves.size(); }
/** Retrieves an animation curve contained within the channel.
@param index The index of the animation curve.
@return The animation curve at the given index. This pointer will be NULL
if the index is out-of-bounds. */
FCDAnimationCurve* GetCurve(size_t index) { FUAssert(index < GetCurveCount(), return NULL); return curves.at(index); }
const FCDAnimationCurve* GetCurve(size_t index) const { FUAssert(index < GetCurveCount(), return NULL); return curves.at(index); } /**< See above. */
/** Adds a new animation curve to this animation channel.
@return The new animation curve. */
FCDAnimationCurve* AddCurve();
};
#endif // _FCD_ANIMATION_CHANNEL_H_
| 412 | 0.737624 | 1 | 0.737624 | game-dev | MEDIA | 0.656033 | game-dev | 0.645963 | 1 | 0.645963 |
joeyparrish/kinetoscope | 3,723 | software/stream-with-special-hardware/src/main.c | // Kinetoscope: A Sega Genesis Video Player
//
// Copyright (c) 2024 Joey Parrish
//
// See MIT License in LICENSE.txt
// Sample project and official ROM for the custom cartridge. Streams video
// over WiFi.
#include <genesis.h>
#include "segavideo_menu.h"
#include "segavideo_player.h"
#include "segavideo_state.h"
#include "kinetoscope_logo.h"
#include "kinetoscope_startup_sound.h"
static void onJoystickEvent(u16 joystick, u16 changed, u16 state) {
if (segavideo_getState() == Error) {
// Error: press start|A to continue.
if (state & (BUTTON_START | BUTTON_A)) {
segavideo_menu_clearError();
}
} else if (segavideo_getState() == Player) {
// Playing: press start to pause, C to stop.
if (state & BUTTON_START) {
segavideo_togglePause();
}
if (state & BUTTON_C) {
segavideo_stop();
}
} else if (segavideo_getState() == Menu) {
// Menu: press start|A to choose, up/down to navigate.
if (state & (BUTTON_START | BUTTON_A)) {
segavideo_menu_select(/* loop= */ false);
}
if (state & BUTTON_UP) {
segavideo_menu_previousItem();
}
if (state & BUTTON_DOWN) {
segavideo_menu_nextItem();
}
}
}
static void handleError() {
segavideo_menu_showError();
// Continue to show the error until the user presses something to clear it.
while (segavideo_getState() == Error) {
SYS_doVBlankProcess();
}
}
static void startup_sequence() {
// Set PAL0 to black.
PAL_setPalette(PAL0, palette_black, CPU);
// Load the image into VRAM.
VDP_drawImageEx(
/* plane= */ BG_B,
&kinetoscope_logo,
/* tile= */ TILE_ATTR_FULL(PAL0, FALSE, FALSE, FALSE, TILE_USER_INDEX),
/* x= */ 2,
/* y= */ 10,
/* load palette= */ FALSE,
/* use DMA= */ FALSE);
// Fade in the image over 1.5 seconds (90 frames) asynchronously
PAL_fadePalette(
/* palette= */ PAL0,
/* first colors= */ palette_black,
/* final colors= */ kinetoscope_logo.palette->data,
/* num frames= */ 90,
/* async= */ TRUE);
// Play the WAV file (2s) asynchronously, then pause for 1 more second
SND_PCM_startPlay(
/* sound= */ kinetoscope_startup_sound,
/* length= */ sizeof(kinetoscope_startup_sound),
/* rate= */ SOUND_PCM_RATE_22050,
/* pan= */ SOUND_PAN_CENTER,
/* loop= */ FALSE);
waitMs(3000);
}
int main(bool hardReset) {
JOY_setEventHandler(onJoystickEvent);
segavideo_init();
startup_sequence();
segavideo_menu_init();
// Stop immediately if we don't have the right hardware.
if (!segavideo_menu_checkHardware()) {
return 0;
}
while (true) {
// Check for errors. At this stage, most likely connection errors.
if (segavideo_menu_hasError()) {
handleError();
continue;
}
// Start in the menu.
if (segavideo_menu_load()) {
segavideo_menu_draw();
}
// Check for errors. May be download errors for the catalog.
if (segavideo_menu_hasError()) {
handleError();
continue;
}
// Redraw the menu while it is visible.
while (segavideo_getState() == Menu) {
segavideo_menu_draw();
SYS_doVBlankProcess();
}
// Check for errors. May be download errors for a video.
if (segavideo_menu_hasError()) {
handleError();
continue;
}
// While playing, process video frames.
while (segavideo_isPlaying()) {
segavideo_processFrames();
SYS_doVBlankProcess();
// Check for errors. At this stage, most likely a buffer underflow.
if (segavideo_menu_hasError()) {
segavideo_stop();
handleError();
break;
}
}
// Loop back to the menu.
}
return 0;
}
| 412 | 0.719921 | 1 | 0.719921 | game-dev | MEDIA | 0.343572 | game-dev | 0.901653 | 1 | 0.901653 |
PerpetuumOnline/PerpetuumServer | 2,234 | src/Perpetuum/Zones/Artifacts/Scanners/ArtifactScannerFactory.cs | using System.Linq;
using Perpetuum.Players;
using Perpetuum.Zones.Artifacts.Generators;
using Perpetuum.Zones.Artifacts.Generators.Loot;
using Perpetuum.Zones.Artifacts.Repositories;
namespace Perpetuum.Zones.Artifacts.Scanners
{
public class ArtifactScannerFactory
{
private readonly IZone _zone;
public ArtifactScannerFactory(IZone zone)
{
_zone = zone;
}
public IArtifactScanner CreateArtifactScanner(Player player)
{
IArtifactRepository artifactRepository;
IArtifactGenerator artifactGenerator;
IArtifactLootGenerator artifactLootGenerator;
if (_zone is TrainingZone)
{
artifactGenerator = new NullArtifactGenerator();
artifactRepository = new TrainingZoneArtifactRepository();
artifactLootGenerator = new TrainingArtifactLootGenerator(new ArtifactLootGenerator(artifactRepository));
}
else
{
var reader = new ZoneArtifactReader(player,ArtifactReadMode.Persistent);
var cr = new CompositeArtifactReader(reader);
var targets = player.MissionHandler.GetArtifactTargets();
var uniqueGuids = targets.Select(t => t.MyZoneMissionInProgress.missionGuid).Distinct().ToList();
foreach (var missionGuid in uniqueGuids)
{
cr.AddReader( new MissionArtifactReader(missionGuid));
}
artifactRepository = new ZoneArtifactRepository(_zone,cr);
var cg = new CompositeArtifactGenerator(new PersistentArtifactGenerator(_zone, artifactRepository, player));
foreach (var target in targets)
{
cg.AddGenerator(new MissionArtifactGenerator(target,artifactRepository));
}
artifactGenerator = cg;
artifactLootGenerator = new ArtifactLootGenerator(artifactRepository);
}
var scanner = new ArtifactScanner(_zone, artifactRepository, artifactGenerator ,artifactLootGenerator);
return scanner;
}
}
} | 412 | 0.872938 | 1 | 0.872938 | game-dev | MEDIA | 0.85605 | game-dev | 0.510731 | 1 | 0.510731 |
motherencore/MOTHER-Encore-Demo-Source-Code | 1,395 | Scripts/Main/Switches/ControlledTwoStatesObject.gd | class_name ControlledTwoStatesObject
extends ControlledObject
signal state_changed (state, silent)
onready var _state_anim_player = get_node_or_null(_state_anim_player) as AnimationPlayer
var _switches: Array = []
export (bool) var _is_synced_with_room := false
export (bool) var _initially_on := false
func _init():
_state_anim_player = ""
func _ready():
update_state(true)
if _is_synced_with_room:
global.currentScene.connect("synced_switches_changed", self, "_on_synced_switches_changed")
func register_switch(switch: TwoStatesSwitch):
if !switch in _switches:
_switches.append(switch)
func _get_state() -> bool:
var state := _initially_on
if _is_synced_with_room:
state = (state != global.currentScene.get_switches_state())
else:
for switch in _switches:
state = (state != switch.is_on())
return state
func _on_synced_switches_changed(emitter: TwoStatesSyncedSwitch, value: bool, silent: bool):
update_state(silent)
# Override
func update_state(silent: bool = false):
var is_on = _get_state()
if _state_anim_player:
var prefix = "Stay" if silent else ""
if is_on:
_state_anim_player.play("%sOn" % prefix)
else:
_state_anim_player.play("%sOff" % prefix)
yield(_state_anim_player, "animation_finished")
emit_signal("state_changed", is_on, silent)
# Override
func get_update_order() -> int:
return _update_order * (1 if _get_state() else -1)
| 412 | 0.793264 | 1 | 0.793264 | game-dev | MEDIA | 0.819621 | game-dev | 0.845947 | 1 | 0.845947 |
Dreamtowards/Ethertia | 2,735 | lib/jolt-3.0.1/Jolt/Physics/Collision/BroadPhase/BroadPhaseBruteForce.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/BroadPhase/BroadPhase.h>
#include <Jolt/Core/Mutex.h>
JPH_NAMESPACE_BEGIN
/// Test BroadPhase implementation that does not do anything to speed up the operations. Can be used as a reference implementation.
class BroadPhaseBruteForce final : public BroadPhase
{
public:
JPH_OVERRIDE_NEW_DELETE
// Implementing interface of BroadPhase (see BroadPhase for documentation)
virtual void AddBodiesFinalize(BodyID *ioBodies, int inNumber, AddState inAddState) override;
virtual void RemoveBodies(BodyID *ioBodies, int inNumber) override;
virtual void NotifyBodiesAABBChanged(BodyID *ioBodies, int inNumber, bool inTakeLock) override;
virtual void NotifyBodiesLayerChanged(BodyID *ioBodies, int inNumber) override;
virtual void CastRay(const RayCast &inRay, RayCastBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter) const override;
virtual void CollideAABox(const AABox &inBox, CollideShapeBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter) const override;
virtual void CollideSphere(Vec3Arg inCenter, float inRadius, CollideShapeBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter) const override;
virtual void CollidePoint(Vec3Arg inPoint, CollideShapeBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter) const override;
virtual void CollideOrientedBox(const OrientedBox &inBox, CollideShapeBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter) const override;
virtual void CastAABoxNoLock(const AABoxCast &inBox, CastShapeBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter) const override;
virtual void CastAABox(const AABoxCast &inBox, CastShapeBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter) const override;
virtual void FindCollidingPairs(BodyID *ioActiveBodies, int inNumActiveBodies, float inSpeculativeContactDistance, const ObjectVsBroadPhaseLayerFilter &inObjectVsBroadPhaseLayerFilter, const ObjectLayerPairFilter &inObjectLayerPairFilter, BodyPairCollector &ioPairCollector) const override;
private:
Array<BodyID> mBodyIDs;
mutable SharedMutex mMutex;
};
JPH_NAMESPACE_END
| 412 | 0.881388 | 1 | 0.881388 | game-dev | MEDIA | 0.87948 | game-dev | 0.532976 | 1 | 0.532976 |
terrafx/terrafx | 1,355 | sources/Core/Collections/ValuePool`1.DebugView.cs | // Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
using System;
using System.Diagnostics;
namespace TerraFX.Collections;
public partial struct ValuePool<T>
{
internal sealed class DebugView(ValuePool<T> pool)
{
private readonly ValuePool<T> _pool = pool;
public int AvailableCount => _pool._availableItems.Count;
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public T[] AvailableItems
{
get
{
ref readonly var poolAvailableItems = ref _pool._availableItems;
var availableItems = GC.AllocateUninitializedArray<T>(poolAvailableItems.Count);
poolAvailableItems.CopyTo(availableItems);
return availableItems;
}
}
public int Capacity => _pool._items.Capacity;
public int Count => _pool._items.Count;
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public T[] Items
{
get
{
ref readonly var poolItems = ref _pool._items;
var items = GC.AllocateUninitializedArray<T>(poolItems.Count);
poolItems.CopyTo(items);
return items;
}
}
}
}
| 412 | 0.779925 | 1 | 0.779925 | game-dev | MEDIA | 0.748007 | game-dev | 0.516437 | 1 | 0.516437 |
nasa/World-Wind-Java | 3,282 | WorldWind/src/gov/nasa/worldwind/formats/rpf/RPFZone.java | /*
* Copyright (C) 2011 United States Government as represented by the Administrator of the
* National Aeronautics and Space Administration.
* All Rights Reserved.
*/
package gov.nasa.worldwind.formats.rpf;
import gov.nasa.worldwind.util.Logging;
/**
* @author dcollins
* @version $Id$
*/
public enum RPFZone
{
/* [Table III, Section 70, MIL-A-89007] */
ZONE_1('1'),
ZONE_2('2'),
ZONE_3('3'),
ZONE_4('4'),
ZONE_5('5'),
ZONE_6('6'),
ZONE_7('7'),
ZONE_8('8'),
ZONE_9('9'),
ZONE_A('A'),
ZONE_B('B'),
ZONE_C('C'),
ZONE_D('D'),
ZONE_E('E'),
ZONE_F('F'),
ZONE_G('G'),
ZONE_H('H'),
ZONE_J('J'),
;
public final char zoneCode;
private RPFZone(char zoneCode)
{
this.zoneCode = zoneCode;
}
public static boolean isZoneCode(char c)
{
char upperChar = Character.toUpperCase(c);
return ((upperChar >= '1' && upperChar <= '9')
|| (upperChar >= 'A' && upperChar <= 'H')
|| (upperChar == 'J'));
}
static int indexFor(char zoneCode)
{
final int NUM_START_INDEX = 0;
final int ALPHA_START_INDEX = 9;
int index = -1;
char upperChar = Character.toUpperCase(zoneCode);
if (upperChar >= '1' && upperChar <= '9')
{
index = NUM_START_INDEX + upperChar - '1';
}
else if (upperChar >= 'A' && upperChar <= 'H')
{
index = ALPHA_START_INDEX + upperChar - 'A';
}
else if (upperChar == 'J')
{
index = ALPHA_START_INDEX + upperChar - 'A' - 1;
}
return index;
}
static boolean isZoneInUpperHemisphere(char zoneCode)
{
char upperChar = Character.toUpperCase(zoneCode);
return (upperChar >= '1' && upperChar <= '9');
}
static boolean isPolarZone(char zoneCode)
{
char upperChar = Character.toUpperCase(zoneCode);
return (upperChar == '9') || (upperChar == 'J');
}
public static RPFZone zoneFor(char zoneCode)
{
RPFZone[] alphabet = enumConstantAlphabet();
int index = indexFor(zoneCode);
if (index < 0 || index >= alphabet.length)
{
String message = Logging.getMessage("generic.EnumNotFound", zoneCode);
Logging.logger().fine(message);
throw new EnumConstantNotPresentException(RPFZone.class, message);
}
RPFZone zone = alphabet[index];
if (zone == null)
{
String message = Logging.getMessage("generic.EnumNotFound", zoneCode);
Logging.logger().fine(message);
throw new EnumConstantNotPresentException(RPFZone.class, message);
}
return zone;
}
private static RPFZone[] enumConstantAlphabet = null;
private static synchronized RPFZone[] enumConstantAlphabet()
{
if (enumConstantAlphabet == null)
{
RPFZone[] universe = RPFZone.class.getEnumConstants();
enumConstantAlphabet = new RPFZone[universe.length];
for (RPFZone zone : universe)
{
enumConstantAlphabet[indexFor(zone.zoneCode)] = zone;
}
}
return enumConstantAlphabet;
}
}
| 412 | 0.797243 | 1 | 0.797243 | game-dev | MEDIA | 0.529648 | game-dev | 0.779556 | 1 | 0.779556 |
Masuzu/ZooeyBot | 1,274 | Scripts/dimensional_halo.lua | EnableChargeAttack()
Summon(6)
--[[Use treasure hunt whenever it is off cooldown (bound to the skills at position 4 and 2 in my case)--]]
if character_1.name == "<main character name>" then
character_1:UseSkill(4)
character_1:UseSkill(3)
character_1:UseSkill(2)
end
if characters["Zooey"] ~= nil then
characters["Zooey"]:UseSkill(2)
characters["Zooey"]:UseSkill(1)
end
--[[As long as Orchid is alive, use her first and third skills whenever they are off cooldown--]]
if character_2.name == "Orchid" then
character_2:UseSkill(1)
character_2:UseSkill(3)
end
if turn == 1 then
characters["Vira"]:UseSkill(2)
end
if character_4.name == "Vira" then
character_4:UseSkill(1)
end
if turn == 2 then
characters["Vira"]:UseSkill(4)
characters["Vira"]:UseSkill(3)
end
--[[Narmaya is in my back row, should one of my frontline character fall and be replaced by Forte, use her second and first skills--]]
if characters["Narmaya"] ~= nil then
characters["Narmaya"]:UseSkill(2)
characters["Narmaya"]:UseSkill(1)
end
--[[Six is in my back row, should one of my frontline character fall and be replaced by Six, use his skills--]]
if characters["Seox"] ~= nil then
characters["Seox"]:UseSkill(3)
characters["Seox"]:UseSkill(2)
characters["Seox"]:UseSkill(1)
end | 412 | 0.573428 | 1 | 0.573428 | game-dev | MEDIA | 0.368592 | game-dev | 0.731503 | 1 | 0.731503 |
defold/defold | 71,991 | external/box2d/Box2D/src/contact_solver.c | // SPDX-FileCopyrightText: 2023 Erin Catto
// SPDX-License-Identifier: MIT
#include "contact_solver.h"
#include "body.h"
#include "constraint_graph.h"
#include "contact.h"
#include "core.h"
#include "solver_set.h"
#include "world.h"
#include <stddef.h>
// contact separation for sub-stepping
// s = s0 + dot(cB + rB - cA - rA, normal)
// normal is held constant
// body positions c can translation and anchors r can rotate
// s(t) = s0 + dot(cB(t) + rB(t) - cA(t) - rA(t), normal)
// s(t) = s0 + dot(cB0 + dpB + rot(dqB, rB0) - cA0 - dpA - rot(dqA, rA0), normal)
// s(t) = s0 + dot(cB0 - cA0, normal) + dot(dpB - dpA + rot(dqB, rB0) - rot(dqA, rA0), normal)
// s_base = s0 + dot(cB0 - cA0, normal)
void b2PrepareOverflowContacts( b2StepContext* context )
{
b2TracyCZoneNC( prepare_overflow_contact, "Prepare Overflow Contact", b2_colorYellow, true );
b2World* world = context->world;
b2ConstraintGraph* graph = context->graph;
b2GraphColor* color = graph->colors + B2_OVERFLOW_INDEX;
b2ContactConstraint* constraints = color->overflowConstraints;
int contactCount = color->contactSims.count;
b2ContactSim* contacts = color->contactSims.data;
b2BodyState* awakeStates = context->states;
#if B2_VALIDATE
b2Body* bodies = world->bodies.data;
#endif
// Stiffer for static contacts to avoid bodies getting pushed through the ground
b2Softness contactSoftness = context->contactSoftness;
b2Softness staticSoftness = context->staticSoftness;
float warmStartScale = world->enableWarmStarting ? 1.0f : 0.0f;
for ( int i = 0; i < contactCount; ++i )
{
b2ContactSim* contactSim = contacts + i;
const b2Manifold* manifold = &contactSim->manifold;
int pointCount = manifold->pointCount;
B2_ASSERT( 0 < pointCount && pointCount <= 2 );
int indexA = contactSim->bodySimIndexA;
int indexB = contactSim->bodySimIndexB;
#if B2_VALIDATE
b2Body* bodyA = bodies + contactSim->bodyIdA;
int validIndexA = bodyA->setIndex == b2_awakeSet ? bodyA->localIndex : B2_NULL_INDEX;
B2_ASSERT( indexA == validIndexA );
b2Body* bodyB = bodies + contactSim->bodyIdB;
int validIndexB = bodyB->setIndex == b2_awakeSet ? bodyB->localIndex : B2_NULL_INDEX;
B2_ASSERT( indexB == validIndexB );
#endif
b2ContactConstraint* constraint = constraints + i;
constraint->indexA = indexA;
constraint->indexB = indexB;
constraint->normal = manifold->normal;
constraint->friction = contactSim->friction;
constraint->restitution = contactSim->restitution;
constraint->rollingResistance = contactSim->rollingResistance;
constraint->rollingImpulse = warmStartScale * manifold->rollingImpulse;
constraint->tangentSpeed = contactSim->tangentSpeed;
constraint->pointCount = pointCount;
b2Vec2 vA = b2Vec2_zero;
float wA = 0.0f;
float mA = contactSim->invMassA;
float iA = contactSim->invIA;
if ( indexA != B2_NULL_INDEX )
{
b2BodyState* stateA = awakeStates + indexA;
vA = stateA->linearVelocity;
wA = stateA->angularVelocity;
}
b2Vec2 vB = b2Vec2_zero;
float wB = 0.0f;
float mB = contactSim->invMassB;
float iB = contactSim->invIB;
if ( indexB != B2_NULL_INDEX )
{
b2BodyState* stateB = awakeStates + indexB;
vB = stateB->linearVelocity;
wB = stateB->angularVelocity;
}
if ( indexA == B2_NULL_INDEX || indexB == B2_NULL_INDEX )
{
constraint->softness = staticSoftness;
}
else
{
constraint->softness = contactSoftness;
}
// copy mass into constraint to avoid cache misses during sub-stepping
constraint->invMassA = mA;
constraint->invIA = iA;
constraint->invMassB = mB;
constraint->invIB = iB;
{
float k = iA + iB;
constraint->rollingMass = k > 0.0f ? 1.0f / k : 0.0f;
}
b2Vec2 normal = constraint->normal;
b2Vec2 tangent = b2RightPerp( constraint->normal );
for ( int j = 0; j < pointCount; ++j )
{
const b2ManifoldPoint* mp = manifold->points + j;
b2ContactConstraintPoint* cp = constraint->points + j;
cp->normalImpulse = warmStartScale * mp->normalImpulse;
cp->tangentImpulse = warmStartScale * mp->tangentImpulse;
cp->totalNormalImpulse = 0.0f;
b2Vec2 rA = mp->anchorA;
b2Vec2 rB = mp->anchorB;
cp->anchorA = rA;
cp->anchorB = rB;
cp->baseSeparation = mp->separation - b2Dot( b2Sub( rB, rA ), normal );
float rnA = b2Cross( rA, normal );
float rnB = b2Cross( rB, normal );
float kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
cp->normalMass = kNormal > 0.0f ? 1.0f / kNormal : 0.0f;
float rtA = b2Cross( rA, tangent );
float rtB = b2Cross( rB, tangent );
float kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB;
cp->tangentMass = kTangent > 0.0f ? 1.0f / kTangent : 0.0f;
// Save relative velocity for restitution
b2Vec2 vrA = b2Add( vA, b2CrossSV( wA, rA ) );
b2Vec2 vrB = b2Add( vB, b2CrossSV( wB, rB ) );
cp->relativeVelocity = b2Dot( normal, b2Sub( vrB, vrA ) );
}
}
b2TracyCZoneEnd( prepare_overflow_contact );
}
void b2WarmStartOverflowContacts( b2StepContext* context )
{
b2TracyCZoneNC( warmstart_overflow_contact, "WarmStart Overflow Contact", b2_colorDarkOrange, true );
b2ConstraintGraph* graph = context->graph;
b2GraphColor* color = graph->colors + B2_OVERFLOW_INDEX;
b2ContactConstraint* constraints = color->overflowConstraints;
int contactCount = color->contactSims.count;
b2World* world = context->world;
b2SolverSet* awakeSet = b2SolverSetArray_Get( &world->solverSets, b2_awakeSet );
b2BodyState* states = awakeSet->bodyStates.data;
// This is a dummy state to represent a static body because static bodies don't have a solver body.
b2BodyState dummyState = b2_identityBodyState;
for ( int i = 0; i < contactCount; ++i )
{
const b2ContactConstraint* constraint = constraints + i;
int indexA = constraint->indexA;
int indexB = constraint->indexB;
b2BodyState* stateA = indexA == B2_NULL_INDEX ? &dummyState : states + indexA;
b2BodyState* stateB = indexB == B2_NULL_INDEX ? &dummyState : states + indexB;
b2Vec2 vA = stateA->linearVelocity;
float wA = stateA->angularVelocity;
b2Vec2 vB = stateB->linearVelocity;
float wB = stateB->angularVelocity;
float mA = constraint->invMassA;
float iA = constraint->invIA;
float mB = constraint->invMassB;
float iB = constraint->invIB;
// Stiffer for static contacts to avoid bodies getting pushed through the ground
b2Vec2 normal = constraint->normal;
b2Vec2 tangent = b2RightPerp( constraint->normal );
int pointCount = constraint->pointCount;
for ( int j = 0; j < pointCount; ++j )
{
const b2ContactConstraintPoint* cp = constraint->points + j;
// fixed anchors
b2Vec2 rA = cp->anchorA;
b2Vec2 rB = cp->anchorB;
b2Vec2 P = b2Add( b2MulSV( cp->normalImpulse, normal ), b2MulSV( cp->tangentImpulse, tangent ) );
wA -= iA * b2Cross( rA, P );
vA = b2MulAdd( vA, -mA, P );
wB += iB * b2Cross( rB, P );
vB = b2MulAdd( vB, mB, P );
}
wA -= iA * constraint->rollingImpulse;
wB += iB * constraint->rollingImpulse;
stateA->linearVelocity = vA;
stateA->angularVelocity = wA;
stateB->linearVelocity = vB;
stateB->angularVelocity = wB;
}
b2TracyCZoneEnd( warmstart_overflow_contact );
}
void b2SolveOverflowContacts( b2StepContext* context, bool useBias )
{
b2TracyCZoneNC( solve_contact, "Solve Contact", b2_colorAliceBlue, true );
b2ConstraintGraph* graph = context->graph;
b2GraphColor* color = graph->colors + B2_OVERFLOW_INDEX;
b2ContactConstraint* constraints = color->overflowConstraints;
int contactCount = color->contactSims.count;
b2World* world = context->world;
b2SolverSet* awakeSet = b2SolverSetArray_Get( &world->solverSets, b2_awakeSet );
b2BodyState* states = awakeSet->bodyStates.data;
float inv_h = context->inv_h;
const float pushout = context->world->maxContactPushSpeed;
// This is a dummy body to represent a static body since static bodies don't have a solver body.
b2BodyState dummyState = b2_identityBodyState;
for ( int i = 0; i < contactCount; ++i )
{
b2ContactConstraint* constraint = constraints + i;
float mA = constraint->invMassA;
float iA = constraint->invIA;
float mB = constraint->invMassB;
float iB = constraint->invIB;
b2BodyState* stateA = constraint->indexA == B2_NULL_INDEX ? &dummyState : states + constraint->indexA;
b2Vec2 vA = stateA->linearVelocity;
float wA = stateA->angularVelocity;
b2Rot dqA = stateA->deltaRotation;
b2BodyState* stateB = constraint->indexB == B2_NULL_INDEX ? &dummyState : states + constraint->indexB;
b2Vec2 vB = stateB->linearVelocity;
float wB = stateB->angularVelocity;
b2Rot dqB = stateB->deltaRotation;
b2Vec2 dp = b2Sub( stateB->deltaPosition, stateA->deltaPosition );
b2Vec2 normal = constraint->normal;
b2Vec2 tangent = b2RightPerp( normal );
float friction = constraint->friction;
b2Softness softness = constraint->softness;
int pointCount = constraint->pointCount;
float totalNormalImpulse = 0.0f;
// Non-penetration
for ( int j = 0; j < pointCount; ++j )
{
b2ContactConstraintPoint* cp = constraint->points + j;
// fixed anchor points
b2Vec2 rA = cp->anchorA;
b2Vec2 rB = cp->anchorB;
// compute current separation
// this is subject to round-off error if the anchor is far from the body center of mass
b2Vec2 ds = b2Add( dp, b2Sub( b2RotateVector( dqB, rB ), b2RotateVector( dqA, rA ) ) );
float s = cp->baseSeparation + b2Dot( ds, normal );
float velocityBias = 0.0f;
float massScale = 1.0f;
float impulseScale = 0.0f;
if ( s > 0.0f )
{
// speculative bias
velocityBias = s * inv_h;
}
else if ( useBias )
{
velocityBias = b2MaxFloat( softness.biasRate * s, -pushout );
massScale = softness.massScale;
impulseScale = softness.impulseScale;
}
// relative normal velocity at contact
b2Vec2 vrA = b2Add( vA, b2CrossSV( wA, rA ) );
b2Vec2 vrB = b2Add( vB, b2CrossSV( wB, rB ) );
float vn = b2Dot( b2Sub( vrB, vrA ), normal );
// incremental normal impulse
float impulse = -cp->normalMass * massScale * ( vn + velocityBias ) - impulseScale * cp->normalImpulse;
// clamp the accumulated impulse
float newImpulse = b2MaxFloat( cp->normalImpulse + impulse, 0.0f );
impulse = newImpulse - cp->normalImpulse;
cp->normalImpulse = newImpulse;
cp->totalNormalImpulse += newImpulse;
totalNormalImpulse += newImpulse;
// apply normal impulse
b2Vec2 P = b2MulSV( impulse, normal );
vA = b2MulSub( vA, mA, P );
wA -= iA * b2Cross( rA, P );
vB = b2MulAdd( vB, mB, P );
wB += iB * b2Cross( rB, P );
}
// Friction
for ( int j = 0; j < pointCount; ++j )
{
b2ContactConstraintPoint* cp = constraint->points + j;
// fixed anchor points
b2Vec2 rA = cp->anchorA;
b2Vec2 rB = cp->anchorB;
// relative tangent velocity at contact
b2Vec2 vrB = b2Add( vB, b2CrossSV( wB, rB ) );
b2Vec2 vrA = b2Add( vA, b2CrossSV( wA, rA ) );
// vt = dot(vrB - sB * tangent - (vrA + sA * tangent), tangent)
// = dot(vrB - vrA, tangent) - (sA + sB)
float vt = b2Dot( b2Sub( vrB, vrA ), tangent ) - constraint->tangentSpeed;
// incremental tangent impulse
float impulse = cp->tangentMass * ( -vt );
// clamp the accumulated force
float maxFriction = friction * cp->normalImpulse;
float newImpulse = b2ClampFloat( cp->tangentImpulse + impulse, -maxFriction, maxFriction );
impulse = newImpulse - cp->tangentImpulse;
cp->tangentImpulse = newImpulse;
// apply tangent impulse
b2Vec2 P = b2MulSV( impulse, tangent );
vA = b2MulSub( vA, mA, P );
wA -= iA * b2Cross( rA, P );
vB = b2MulAdd( vB, mB, P );
wB += iB * b2Cross( rB, P );
}
// Rolling resistance
{
float deltaLambda = -constraint->rollingMass * ( wB - wA );
float lambda = constraint->rollingImpulse;
float maxLambda = constraint->rollingResistance * totalNormalImpulse;
constraint->rollingImpulse = b2ClampFloat( lambda + deltaLambda, -maxLambda, maxLambda );
deltaLambda = constraint->rollingImpulse - lambda;
wA -= iA * deltaLambda;
wB += iB * deltaLambda;
}
stateA->linearVelocity = vA;
stateA->angularVelocity = wA;
stateB->linearVelocity = vB;
stateB->angularVelocity = wB;
}
b2TracyCZoneEnd( solve_contact );
}
void b2ApplyOverflowRestitution( b2StepContext* context )
{
b2TracyCZoneNC( overflow_resitution, "Overflow Restitution", b2_colorViolet, true );
b2ConstraintGraph* graph = context->graph;
b2GraphColor* color = graph->colors + B2_OVERFLOW_INDEX;
b2ContactConstraint* constraints = color->overflowConstraints;
int contactCount = color->contactSims.count;
b2World* world = context->world;
b2SolverSet* awakeSet = b2SolverSetArray_Get( &world->solverSets, b2_awakeSet );
b2BodyState* states = awakeSet->bodyStates.data;
float threshold = context->world->restitutionThreshold;
// dummy state to represent a static body
b2BodyState dummyState = b2_identityBodyState;
for ( int i = 0; i < contactCount; ++i )
{
b2ContactConstraint* constraint = constraints + i;
float restitution = constraint->restitution;
if ( restitution == 0.0f )
{
continue;
}
float mA = constraint->invMassA;
float iA = constraint->invIA;
float mB = constraint->invMassB;
float iB = constraint->invIB;
b2BodyState* stateA = constraint->indexA == B2_NULL_INDEX ? &dummyState : states + constraint->indexA;
b2Vec2 vA = stateA->linearVelocity;
float wA = stateA->angularVelocity;
b2BodyState* stateB = constraint->indexB == B2_NULL_INDEX ? &dummyState : states + constraint->indexB;
b2Vec2 vB = stateB->linearVelocity;
float wB = stateB->angularVelocity;
b2Vec2 normal = constraint->normal;
int pointCount = constraint->pointCount;
// it is possible to get more accurate restitution by iterating
// this only makes a difference if there are two contact points
// for (int iter = 0; iter < 10; ++iter)
{
for ( int j = 0; j < pointCount; ++j )
{
b2ContactConstraintPoint* cp = constraint->points + j;
// if the normal impulse is zero then there was no collision
// this skips speculative contact points that didn't generate an impulse
// The max normal impulse is used in case there was a collision that moved away within the sub-step process
if ( cp->relativeVelocity > -threshold || cp->totalNormalImpulse == 0.0f )
{
continue;
}
// fixed anchor points
b2Vec2 rA = cp->anchorA;
b2Vec2 rB = cp->anchorB;
// relative normal velocity at contact
b2Vec2 vrB = b2Add( vB, b2CrossSV( wB, rB ) );
b2Vec2 vrA = b2Add( vA, b2CrossSV( wA, rA ) );
float vn = b2Dot( b2Sub( vrB, vrA ), normal );
// compute normal impulse
float impulse = -cp->normalMass * ( vn + restitution * cp->relativeVelocity );
// clamp the accumulated impulse
// todo should this be stored?
float newImpulse = b2MaxFloat( cp->normalImpulse + impulse, 0.0f );
impulse = newImpulse - cp->normalImpulse;
cp->normalImpulse = newImpulse;
// Add the incremental impulse rather than the full impulse because this is not a sub-step
cp->totalNormalImpulse += impulse;
// apply contact impulse
b2Vec2 P = b2MulSV( impulse, normal );
vA = b2MulSub( vA, mA, P );
wA -= iA * b2Cross( rA, P );
vB = b2MulAdd( vB, mB, P );
wB += iB * b2Cross( rB, P );
}
}
stateA->linearVelocity = vA;
stateA->angularVelocity = wA;
stateB->linearVelocity = vB;
stateB->angularVelocity = wB;
}
b2TracyCZoneEnd( overflow_resitution );
}
void b2StoreOverflowImpulses( b2StepContext* context )
{
b2TracyCZoneNC( store_impulses, "Store", b2_colorFireBrick, true );
b2ConstraintGraph* graph = context->graph;
b2GraphColor* color = graph->colors + B2_OVERFLOW_INDEX;
b2ContactConstraint* constraints = color->overflowConstraints;
b2ContactSim* contacts = color->contactSims.data;
int contactCount = color->contactSims.count;
for ( int i = 0; i < contactCount; ++i )
{
const b2ContactConstraint* constraint = constraints + i;
b2ContactSim* contact = contacts + i;
b2Manifold* manifold = &contact->manifold;
int pointCount = manifold->pointCount;
for ( int j = 0; j < pointCount; ++j )
{
manifold->points[j].normalImpulse = constraint->points[j].normalImpulse;
manifold->points[j].tangentImpulse = constraint->points[j].tangentImpulse;
manifold->points[j].totalNormalImpulse = constraint->points[j].totalNormalImpulse;
manifold->points[j].normalVelocity = constraint->points[j].relativeVelocity;
}
manifold->rollingImpulse = constraint->rollingImpulse;
}
b2TracyCZoneEnd( store_impulses );
}
#if defined( B2_SIMD_AVX2 )
#include <immintrin.h>
// wide float holds 8 numbers
typedef __m256 b2FloatW;
#elif defined( B2_SIMD_NEON )
#include <arm_neon.h>
// wide float holds 4 numbers
typedef float32x4_t b2FloatW;
#elif defined( B2_SIMD_SSE2 )
#include <emmintrin.h>
// wide float holds 4 numbers
typedef __m128 b2FloatW;
#else
// scalar math
typedef struct b2FloatW
{
float x, y, z, w;
} b2FloatW;
#endif
// Wide vec2
typedef struct b2Vec2W
{
b2FloatW X, Y;
} b2Vec2W;
// Wide rotation
typedef struct b2RotW
{
b2FloatW C, S;
} b2RotW;
#if defined( B2_SIMD_AVX2 )
static inline b2FloatW b2ZeroW( void )
{
return _mm256_setzero_ps();
}
static inline b2FloatW b2SplatW( float scalar )
{
return _mm256_set1_ps( scalar );
}
static inline b2FloatW b2AddW( b2FloatW a, b2FloatW b )
{
return _mm256_add_ps( a, b );
}
static inline b2FloatW b2SubW( b2FloatW a, b2FloatW b )
{
return _mm256_sub_ps( a, b );
}
static inline b2FloatW b2MulW( b2FloatW a, b2FloatW b )
{
return _mm256_mul_ps( a, b );
}
static inline b2FloatW b2MulAddW( b2FloatW a, b2FloatW b, b2FloatW c )
{
// FMA can be emulated: https://github.com/lattera/glibc/blob/master/sysdeps/ieee754/dbl-64/s_fmaf.c#L34
// return _mm256_fmadd_ps( b, c, a );
return _mm256_add_ps( _mm256_mul_ps( b, c ), a );
}
static inline b2FloatW b2MulSubW( b2FloatW a, b2FloatW b, b2FloatW c )
{
// return _mm256_fnmadd_ps(b, c, a);
return _mm256_sub_ps( a, _mm256_mul_ps( b, c ) );
}
static inline b2FloatW b2MinW( b2FloatW a, b2FloatW b )
{
return _mm256_min_ps( a, b );
}
static inline b2FloatW b2MaxW( b2FloatW a, b2FloatW b )
{
return _mm256_max_ps( a, b );
}
// a = clamp(a, -b, b)
static inline b2FloatW b2SymClampW( b2FloatW a, b2FloatW b )
{
b2FloatW nb = _mm256_sub_ps( _mm256_setzero_ps(), b );
return _mm256_max_ps( nb, _mm256_min_ps( a, b ) );
}
static inline b2FloatW b2OrW( b2FloatW a, b2FloatW b )
{
return _mm256_or_ps( a, b );
}
static inline b2FloatW b2GreaterThanW( b2FloatW a, b2FloatW b )
{
return _mm256_cmp_ps( a, b, _CMP_GT_OQ );
}
static inline b2FloatW b2EqualsW( b2FloatW a, b2FloatW b )
{
return _mm256_cmp_ps( a, b, _CMP_EQ_OQ );
}
static inline bool b2AllZeroW( b2FloatW a )
{
// Compare each element with zero
b2FloatW zero = _mm256_setzero_ps();
b2FloatW cmp = _mm256_cmp_ps( a, zero, _CMP_EQ_OQ );
// Create a mask from the comparison results
int mask = _mm256_movemask_ps( cmp );
// If all elements are zero, the mask will be 0xFF (11111111 in binary)
return mask == 0xFF;
}
// component-wise returns mask ? b : a
static inline b2FloatW b2BlendW( b2FloatW a, b2FloatW b, b2FloatW mask )
{
return _mm256_blendv_ps( a, b, mask );
}
#elif defined( B2_SIMD_NEON )
static inline b2FloatW b2ZeroW( void )
{
return vdupq_n_f32( 0.0f );
}
static inline b2FloatW b2SplatW( float scalar )
{
return vdupq_n_f32( scalar );
}
static inline b2FloatW b2SetW( float a, float b, float c, float d )
{
float32_t array[4] = { a, b, c, d };
return vld1q_f32( array );
}
static inline b2FloatW b2AddW( b2FloatW a, b2FloatW b )
{
return vaddq_f32( a, b );
}
static inline b2FloatW b2SubW( b2FloatW a, b2FloatW b )
{
return vsubq_f32( a, b );
}
static inline b2FloatW b2MulW( b2FloatW a, b2FloatW b )
{
return vmulq_f32( a, b );
}
static inline b2FloatW b2MulAddW( b2FloatW a, b2FloatW b, b2FloatW c )
{
return vmlaq_f32( a, b, c );
}
static inline b2FloatW b2MulSubW( b2FloatW a, b2FloatW b, b2FloatW c )
{
return vmlsq_f32( a, b, c );
}
static inline b2FloatW b2MinW( b2FloatW a, b2FloatW b )
{
return vminq_f32( a, b );
}
static inline b2FloatW b2MaxW( b2FloatW a, b2FloatW b )
{
return vmaxq_f32( a, b );
}
// a = clamp(a, -b, b)
static inline b2FloatW b2SymClampW( b2FloatW a, b2FloatW b )
{
b2FloatW nb = vnegq_f32( b );
return vmaxq_f32( nb, vminq_f32( a, b ) );
}
static inline b2FloatW b2OrW( b2FloatW a, b2FloatW b )
{
return vreinterpretq_f32_u32( vorrq_u32( vreinterpretq_u32_f32( a ), vreinterpretq_u32_f32( b ) ) );
}
static inline b2FloatW b2GreaterThanW( b2FloatW a, b2FloatW b )
{
return vreinterpretq_f32_u32( vcgtq_f32( a, b ) );
}
static inline b2FloatW b2EqualsW( b2FloatW a, b2FloatW b )
{
return vreinterpretq_f32_u32( vceqq_f32( a, b ) );
}
static inline bool b2AllZeroW( b2FloatW a )
{
// Create a zero vector for comparison
b2FloatW zero = vdupq_n_f32( 0.0f );
// Compare the input vector with zero
uint32x4_t cmp_result = vceqq_f32( a, zero );
// Check if all comparison results are non-zero using vminvq
#ifdef __ARM_FEATURE_SVE
// ARM v8.2+ has horizontal minimum instruction
return vminvq_u32( cmp_result ) != 0;
#else
// For older ARM architectures, we need to manually check all lanes
return vgetq_lane_u32( cmp_result, 0 ) != 0 && vgetq_lane_u32( cmp_result, 1 ) != 0 && vgetq_lane_u32( cmp_result, 2 ) != 0 &&
vgetq_lane_u32( cmp_result, 3 ) != 0;
#endif
}
// component-wise returns mask ? b : a
static inline b2FloatW b2BlendW( b2FloatW a, b2FloatW b, b2FloatW mask )
{
uint32x4_t mask32 = vreinterpretq_u32_f32( mask );
return vbslq_f32( mask32, b, a );
}
static inline b2FloatW b2LoadW( const float32_t* data )
{
return vld1q_f32( data );
}
static inline void b2StoreW( float32_t* data, b2FloatW a )
{
vst1q_f32( data, a );
}
static inline b2FloatW b2UnpackLoW( b2FloatW a, b2FloatW b )
{
#if defined( __aarch64__ )
return vzip1q_f32( a, b );
#else
float32x2_t a1 = vget_low_f32( a );
float32x2_t b1 = vget_low_f32( b );
float32x2x2_t result = vzip_f32( a1, b1 );
return vcombine_f32( result.val[0], result.val[1] );
#endif
}
static inline b2FloatW b2UnpackHiW( b2FloatW a, b2FloatW b )
{
#if defined( __aarch64__ )
return vzip2q_f32( a, b );
#else
float32x2_t a1 = vget_high_f32( a );
float32x2_t b1 = vget_high_f32( b );
float32x2x2_t result = vzip_f32( a1, b1 );
return vcombine_f32( result.val[0], result.val[1] );
#endif
}
#elif defined( B2_SIMD_SSE2 )
static inline b2FloatW b2ZeroW( void )
{
return _mm_setzero_ps();
}
static inline b2FloatW b2SplatW( float scalar )
{
return _mm_set1_ps( scalar );
}
static inline b2FloatW b2SetW( float a, float b, float c, float d )
{
return _mm_setr_ps( a, b, c, d );
}
static inline b2FloatW b2AddW( b2FloatW a, b2FloatW b )
{
return _mm_add_ps( a, b );
}
static inline b2FloatW b2SubW( b2FloatW a, b2FloatW b )
{
return _mm_sub_ps( a, b );
}
static inline b2FloatW b2MulW( b2FloatW a, b2FloatW b )
{
return _mm_mul_ps( a, b );
}
static inline b2FloatW b2MulAddW( b2FloatW a, b2FloatW b, b2FloatW c )
{
return _mm_add_ps( a, _mm_mul_ps( b, c ) );
}
static inline b2FloatW b2MulSubW( b2FloatW a, b2FloatW b, b2FloatW c )
{
return _mm_sub_ps( a, _mm_mul_ps( b, c ) );
}
static inline b2FloatW b2MinW( b2FloatW a, b2FloatW b )
{
return _mm_min_ps( a, b );
}
static inline b2FloatW b2MaxW( b2FloatW a, b2FloatW b )
{
return _mm_max_ps( a, b );
}
// a = clamp(a, -b, b)
static inline b2FloatW b2SymClampW( b2FloatW a, b2FloatW b )
{
// Create a mask with the sign bit set for each element
__m128 mask = _mm_set1_ps( -0.0f );
// XOR the input with the mask to negate each element
__m128 nb = _mm_xor_ps( b, mask );
return _mm_max_ps( nb, _mm_min_ps( a, b ) );
}
static inline b2FloatW b2OrW( b2FloatW a, b2FloatW b )
{
return _mm_or_ps( a, b );
}
static inline b2FloatW b2GreaterThanW( b2FloatW a, b2FloatW b )
{
return _mm_cmpgt_ps( a, b );
}
static inline b2FloatW b2EqualsW( b2FloatW a, b2FloatW b )
{
return _mm_cmpeq_ps( a, b );
}
static inline bool b2AllZeroW( b2FloatW a )
{
// Compare each element with zero
b2FloatW zero = _mm_setzero_ps();
b2FloatW cmp = _mm_cmpeq_ps( a, zero );
// Create a mask from the comparison results
int mask = _mm_movemask_ps( cmp );
// If all elements are zero, the mask will be 0xF (1111 in binary)
return mask == 0xF;
}
// component-wise returns mask ? b : a
static inline b2FloatW b2BlendW( b2FloatW a, b2FloatW b, b2FloatW mask )
{
return _mm_or_ps( _mm_and_ps( mask, b ), _mm_andnot_ps( mask, a ) );
}
static inline b2FloatW b2LoadW( const float* data )
{
return _mm_load_ps( data );
}
static inline void b2StoreW( float* data, b2FloatW a )
{
_mm_store_ps( data, a );
}
static inline b2FloatW b2UnpackLoW( b2FloatW a, b2FloatW b )
{
return _mm_unpacklo_ps( a, b );
}
static inline b2FloatW b2UnpackHiW( b2FloatW a, b2FloatW b )
{
return _mm_unpackhi_ps( a, b );
}
#else
static inline b2FloatW b2ZeroW( void )
{
return (b2FloatW){ 0.0f, 0.0f, 0.0f, 0.0f };
}
static inline b2FloatW b2SplatW( float scalar )
{
return (b2FloatW){ scalar, scalar, scalar, scalar };
}
static inline b2FloatW b2AddW( b2FloatW a, b2FloatW b )
{
return (b2FloatW){ a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w };
}
static inline b2FloatW b2SubW( b2FloatW a, b2FloatW b )
{
return (b2FloatW){ a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w };
}
static inline b2FloatW b2MulW( b2FloatW a, b2FloatW b )
{
return (b2FloatW){ a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w };
}
static inline b2FloatW b2MulAddW( b2FloatW a, b2FloatW b, b2FloatW c )
{
return (b2FloatW){ a.x + b.x * c.x, a.y + b.y * c.y, a.z + b.z * c.z, a.w + b.w * c.w };
}
static inline b2FloatW b2MulSubW( b2FloatW a, b2FloatW b, b2FloatW c )
{
return (b2FloatW){ a.x - b.x * c.x, a.y - b.y * c.y, a.z - b.z * c.z, a.w - b.w * c.w };
}
static inline b2FloatW b2MinW( b2FloatW a, b2FloatW b )
{
b2FloatW r;
r.x = a.x <= b.x ? a.x : b.x;
r.y = a.y <= b.y ? a.y : b.y;
r.z = a.z <= b.z ? a.z : b.z;
r.w = a.w <= b.w ? a.w : b.w;
return r;
}
static inline b2FloatW b2MaxW( b2FloatW a, b2FloatW b )
{
b2FloatW r;
r.x = a.x >= b.x ? a.x : b.x;
r.y = a.y >= b.y ? a.y : b.y;
r.z = a.z >= b.z ? a.z : b.z;
r.w = a.w >= b.w ? a.w : b.w;
return r;
}
// a = clamp(a, -b, b)
static inline b2FloatW b2SymClampW( b2FloatW a, b2FloatW b )
{
b2FloatW r;
r.x = b2ClampFloat( a.x, -b.x, b.x );
r.y = b2ClampFloat( a.y, -b.y, b.y );
r.z = b2ClampFloat( a.z, -b.z, b.z );
r.w = b2ClampFloat( a.w, -b.w, b.w );
return r;
}
static inline b2FloatW b2OrW( b2FloatW a, b2FloatW b )
{
b2FloatW r;
r.x = a.x != 0.0f || b.x != 0.0f ? 1.0f : 0.0f;
r.y = a.y != 0.0f || b.y != 0.0f ? 1.0f : 0.0f;
r.z = a.z != 0.0f || b.z != 0.0f ? 1.0f : 0.0f;
r.w = a.w != 0.0f || b.w != 0.0f ? 1.0f : 0.0f;
return r;
}
static inline b2FloatW b2GreaterThanW( b2FloatW a, b2FloatW b )
{
b2FloatW r;
r.x = a.x > b.x ? 1.0f : 0.0f;
r.y = a.y > b.y ? 1.0f : 0.0f;
r.z = a.z > b.z ? 1.0f : 0.0f;
r.w = a.w > b.w ? 1.0f : 0.0f;
return r;
}
static inline b2FloatW b2EqualsW( b2FloatW a, b2FloatW b )
{
b2FloatW r;
r.x = a.x == b.x ? 1.0f : 0.0f;
r.y = a.y == b.y ? 1.0f : 0.0f;
r.z = a.z == b.z ? 1.0f : 0.0f;
r.w = a.w == b.w ? 1.0f : 0.0f;
return r;
}
static inline bool b2AllZeroW( b2FloatW a )
{
return a.x == 0.0f && a.y == 0.0f && a.z == 0.0f && a.w == 0.0f;
}
// component-wise returns mask ? b : a
static inline b2FloatW b2BlendW( b2FloatW a, b2FloatW b, b2FloatW mask )
{
b2FloatW r;
r.x = mask.x != 0.0f ? b.x : a.x;
r.y = mask.y != 0.0f ? b.y : a.y;
r.z = mask.z != 0.0f ? b.z : a.z;
r.w = mask.w != 0.0f ? b.w : a.w;
return r;
}
#endif
static inline b2FloatW b2DotW( b2Vec2W a, b2Vec2W b )
{
return b2AddW( b2MulW( a.X, b.X ), b2MulW( a.Y, b.Y ) );
}
static inline b2FloatW b2CrossW( b2Vec2W a, b2Vec2W b )
{
return b2SubW( b2MulW( a.X, b.Y ), b2MulW( a.Y, b.X ) );
}
static inline b2Vec2W b2RotateVectorW( b2RotW q, b2Vec2W v )
{
return (b2Vec2W){ b2SubW( b2MulW( q.C, v.X ), b2MulW( q.S, v.Y ) ), b2AddW( b2MulW( q.S, v.X ), b2MulW( q.C, v.Y ) ) };
}
// Soft contact constraints with sub-stepping support
// Uses fixed anchors for Jacobians for better behavior on rolling shapes (circles & capsules)
// http://mmacklin.com/smallsteps.pdf
// https://box2d.org/files/ErinCatto_SoftConstraints_GDC2011.pdf
typedef struct b2ContactConstraintSIMD
{
int indexA[B2_SIMD_WIDTH];
int indexB[B2_SIMD_WIDTH];
b2FloatW invMassA, invMassB;
b2FloatW invIA, invIB;
b2Vec2W normal;
b2FloatW friction;
b2FloatW tangentSpeed;
b2FloatW rollingResistance;
b2FloatW rollingMass;
b2FloatW rollingImpulse;
b2FloatW biasRate;
b2FloatW massScale;
b2FloatW impulseScale;
b2Vec2W anchorA1, anchorB1;
b2FloatW normalMass1, tangentMass1;
b2FloatW baseSeparation1;
b2FloatW normalImpulse1;
b2FloatW totalNormalImpulse1;
b2FloatW tangentImpulse1;
b2Vec2W anchorA2, anchorB2;
b2FloatW baseSeparation2;
b2FloatW normalImpulse2;
b2FloatW totalNormalImpulse2;
b2FloatW tangentImpulse2;
b2FloatW normalMass2, tangentMass2;
b2FloatW restitution;
b2FloatW relativeVelocity1, relativeVelocity2;
} b2ContactConstraintSIMD;
int b2GetContactConstraintSIMDByteCount( void )
{
return sizeof( b2ContactConstraintSIMD );
}
// wide version of b2BodyState
typedef struct b2BodyStateW
{
b2Vec2W v;
b2FloatW w;
b2FloatW flags;
b2Vec2W dp;
b2RotW dq;
} b2BodyStateW;
// Custom gather/scatter for each SIMD type
#if defined( B2_SIMD_AVX2 )
// This is a load and 8x8 transpose
static b2BodyStateW b2GatherBodies( const b2BodyState* B2_RESTRICT states, int* B2_RESTRICT indices )
{
_Static_assert( sizeof( b2BodyState ) == 32, "b2BodyState not 32 bytes" );
B2_ASSERT( ( (uintptr_t)states & 0x1F ) == 0 );
// b2BodyState b2_identityBodyState = {{0.0f, 0.0f}, 0.0f, 0, {0.0f, 0.0f}, {1.0f, 0.0f}};
b2FloatW identity = _mm256_setr_ps( 0.0f, 0.0f, 0.0f, 0, 0.0f, 0.0f, 1.0f, 0.0f );
b2FloatW b0 = indices[0] == B2_NULL_INDEX ? identity : _mm256_load_ps( (float*)( states + indices[0] ) );
b2FloatW b1 = indices[1] == B2_NULL_INDEX ? identity : _mm256_load_ps( (float*)( states + indices[1] ) );
b2FloatW b2 = indices[2] == B2_NULL_INDEX ? identity : _mm256_load_ps( (float*)( states + indices[2] ) );
b2FloatW b3 = indices[3] == B2_NULL_INDEX ? identity : _mm256_load_ps( (float*)( states + indices[3] ) );
b2FloatW b4 = indices[4] == B2_NULL_INDEX ? identity : _mm256_load_ps( (float*)( states + indices[4] ) );
b2FloatW b5 = indices[5] == B2_NULL_INDEX ? identity : _mm256_load_ps( (float*)( states + indices[5] ) );
b2FloatW b6 = indices[6] == B2_NULL_INDEX ? identity : _mm256_load_ps( (float*)( states + indices[6] ) );
b2FloatW b7 = indices[7] == B2_NULL_INDEX ? identity : _mm256_load_ps( (float*)( states + indices[7] ) );
b2FloatW t0 = _mm256_unpacklo_ps( b0, b1 );
b2FloatW t1 = _mm256_unpackhi_ps( b0, b1 );
b2FloatW t2 = _mm256_unpacklo_ps( b2, b3 );
b2FloatW t3 = _mm256_unpackhi_ps( b2, b3 );
b2FloatW t4 = _mm256_unpacklo_ps( b4, b5 );
b2FloatW t5 = _mm256_unpackhi_ps( b4, b5 );
b2FloatW t6 = _mm256_unpacklo_ps( b6, b7 );
b2FloatW t7 = _mm256_unpackhi_ps( b6, b7 );
b2FloatW tt0 = _mm256_shuffle_ps( t0, t2, _MM_SHUFFLE( 1, 0, 1, 0 ) );
b2FloatW tt1 = _mm256_shuffle_ps( t0, t2, _MM_SHUFFLE( 3, 2, 3, 2 ) );
b2FloatW tt2 = _mm256_shuffle_ps( t1, t3, _MM_SHUFFLE( 1, 0, 1, 0 ) );
b2FloatW tt3 = _mm256_shuffle_ps( t1, t3, _MM_SHUFFLE( 3, 2, 3, 2 ) );
b2FloatW tt4 = _mm256_shuffle_ps( t4, t6, _MM_SHUFFLE( 1, 0, 1, 0 ) );
b2FloatW tt5 = _mm256_shuffle_ps( t4, t6, _MM_SHUFFLE( 3, 2, 3, 2 ) );
b2FloatW tt6 = _mm256_shuffle_ps( t5, t7, _MM_SHUFFLE( 1, 0, 1, 0 ) );
b2FloatW tt7 = _mm256_shuffle_ps( t5, t7, _MM_SHUFFLE( 3, 2, 3, 2 ) );
b2BodyStateW simdBody;
simdBody.v.X = _mm256_permute2f128_ps( tt0, tt4, 0x20 );
simdBody.v.Y = _mm256_permute2f128_ps( tt1, tt5, 0x20 );
simdBody.w = _mm256_permute2f128_ps( tt2, tt6, 0x20 );
simdBody.flags = _mm256_permute2f128_ps( tt3, tt7, 0x20 );
simdBody.dp.X = _mm256_permute2f128_ps( tt0, tt4, 0x31 );
simdBody.dp.Y = _mm256_permute2f128_ps( tt1, tt5, 0x31 );
simdBody.dq.C = _mm256_permute2f128_ps( tt2, tt6, 0x31 );
simdBody.dq.S = _mm256_permute2f128_ps( tt3, tt7, 0x31 );
return simdBody;
}
// This writes everything back to the solver bodies but only the velocities change
static void b2ScatterBodies( b2BodyState* B2_RESTRICT states, int* B2_RESTRICT indices, const b2BodyStateW* B2_RESTRICT simdBody )
{
_Static_assert( sizeof( b2BodyState ) == 32, "b2BodyState not 32 bytes" );
B2_ASSERT( ( (uintptr_t)states & 0x1F ) == 0 );
b2FloatW t0 = _mm256_unpacklo_ps( simdBody->v.X, simdBody->v.Y );
b2FloatW t1 = _mm256_unpackhi_ps( simdBody->v.X, simdBody->v.Y );
b2FloatW t2 = _mm256_unpacklo_ps( simdBody->w, simdBody->flags );
b2FloatW t3 = _mm256_unpackhi_ps( simdBody->w, simdBody->flags );
b2FloatW t4 = _mm256_unpacklo_ps( simdBody->dp.X, simdBody->dp.Y );
b2FloatW t5 = _mm256_unpackhi_ps( simdBody->dp.X, simdBody->dp.Y );
b2FloatW t6 = _mm256_unpacklo_ps( simdBody->dq.C, simdBody->dq.S );
b2FloatW t7 = _mm256_unpackhi_ps( simdBody->dq.C, simdBody->dq.S );
b2FloatW tt0 = _mm256_shuffle_ps( t0, t2, _MM_SHUFFLE( 1, 0, 1, 0 ) );
b2FloatW tt1 = _mm256_shuffle_ps( t0, t2, _MM_SHUFFLE( 3, 2, 3, 2 ) );
b2FloatW tt2 = _mm256_shuffle_ps( t1, t3, _MM_SHUFFLE( 1, 0, 1, 0 ) );
b2FloatW tt3 = _mm256_shuffle_ps( t1, t3, _MM_SHUFFLE( 3, 2, 3, 2 ) );
b2FloatW tt4 = _mm256_shuffle_ps( t4, t6, _MM_SHUFFLE( 1, 0, 1, 0 ) );
b2FloatW tt5 = _mm256_shuffle_ps( t4, t6, _MM_SHUFFLE( 3, 2, 3, 2 ) );
b2FloatW tt6 = _mm256_shuffle_ps( t5, t7, _MM_SHUFFLE( 1, 0, 1, 0 ) );
b2FloatW tt7 = _mm256_shuffle_ps( t5, t7, _MM_SHUFFLE( 3, 2, 3, 2 ) );
// I don't use any dummy body in the body array because this will lead to multithreaded sharing and the
// associated cache flushing.
if ( indices[0] != B2_NULL_INDEX )
_mm256_store_ps( (float*)( states + indices[0] ), _mm256_permute2f128_ps( tt0, tt4, 0x20 ) );
if ( indices[1] != B2_NULL_INDEX )
_mm256_store_ps( (float*)( states + indices[1] ), _mm256_permute2f128_ps( tt1, tt5, 0x20 ) );
if ( indices[2] != B2_NULL_INDEX )
_mm256_store_ps( (float*)( states + indices[2] ), _mm256_permute2f128_ps( tt2, tt6, 0x20 ) );
if ( indices[3] != B2_NULL_INDEX )
_mm256_store_ps( (float*)( states + indices[3] ), _mm256_permute2f128_ps( tt3, tt7, 0x20 ) );
if ( indices[4] != B2_NULL_INDEX )
_mm256_store_ps( (float*)( states + indices[4] ), _mm256_permute2f128_ps( tt0, tt4, 0x31 ) );
if ( indices[5] != B2_NULL_INDEX )
_mm256_store_ps( (float*)( states + indices[5] ), _mm256_permute2f128_ps( tt1, tt5, 0x31 ) );
if ( indices[6] != B2_NULL_INDEX )
_mm256_store_ps( (float*)( states + indices[6] ), _mm256_permute2f128_ps( tt2, tt6, 0x31 ) );
if ( indices[7] != B2_NULL_INDEX )
_mm256_store_ps( (float*)( states + indices[7] ), _mm256_permute2f128_ps( tt3, tt7, 0x31 ) );
}
#elif defined( B2_SIMD_NEON )
// This is a load and transpose
static b2BodyStateW b2GatherBodies( const b2BodyState* B2_RESTRICT states, int* B2_RESTRICT indices )
{
_Static_assert( sizeof( b2BodyState ) == 32, "b2BodyState not 32 bytes" );
B2_ASSERT( ( (uintptr_t)states & 0x1F ) == 0 );
// [vx vy w flags]
b2FloatW identityA = b2ZeroW();
// [dpx dpy dqc dqs]
b2FloatW identityB = b2SetW( 0.0f, 0.0f, 1.0f, 0.0f );
b2FloatW b1a = indices[0] == B2_NULL_INDEX ? identityA : b2LoadW( (float*)( states + indices[0] ) + 0 );
b2FloatW b1b = indices[0] == B2_NULL_INDEX ? identityB : b2LoadW( (float*)( states + indices[0] ) + 4 );
b2FloatW b2a = indices[1] == B2_NULL_INDEX ? identityA : b2LoadW( (float*)( states + indices[1] ) + 0 );
b2FloatW b2b = indices[1] == B2_NULL_INDEX ? identityB : b2LoadW( (float*)( states + indices[1] ) + 4 );
b2FloatW b3a = indices[2] == B2_NULL_INDEX ? identityA : b2LoadW( (float*)( states + indices[2] ) + 0 );
b2FloatW b3b = indices[2] == B2_NULL_INDEX ? identityB : b2LoadW( (float*)( states + indices[2] ) + 4 );
b2FloatW b4a = indices[3] == B2_NULL_INDEX ? identityA : b2LoadW( (float*)( states + indices[3] ) + 0 );
b2FloatW b4b = indices[3] == B2_NULL_INDEX ? identityB : b2LoadW( (float*)( states + indices[3] ) + 4 );
// [vx1 vx3 vy1 vy3]
b2FloatW t1a = b2UnpackLoW( b1a, b3a );
// [vx2 vx4 vy2 vy4]
b2FloatW t2a = b2UnpackLoW( b2a, b4a );
// [w1 w3 f1 f3]
b2FloatW t3a = b2UnpackHiW( b1a, b3a );
// [w2 w4 f2 f4]
b2FloatW t4a = b2UnpackHiW( b2a, b4a );
b2BodyStateW simdBody;
simdBody.v.X = b2UnpackLoW( t1a, t2a );
simdBody.v.Y = b2UnpackHiW( t1a, t2a );
simdBody.w = b2UnpackLoW( t3a, t4a );
simdBody.flags = b2UnpackHiW( t3a, t4a );
b2FloatW t1b = b2UnpackLoW( b1b, b3b );
b2FloatW t2b = b2UnpackLoW( b2b, b4b );
b2FloatW t3b = b2UnpackHiW( b1b, b3b );
b2FloatW t4b = b2UnpackHiW( b2b, b4b );
simdBody.dp.X = b2UnpackLoW( t1b, t2b );
simdBody.dp.Y = b2UnpackHiW( t1b, t2b );
simdBody.dq.C = b2UnpackLoW( t3b, t4b );
simdBody.dq.S = b2UnpackHiW( t3b, t4b );
return simdBody;
}
// This writes only the velocities back to the solver bodies
// https://developer.arm.com/documentation/102107a/0100/Floating-point-4x4-matrix-transposition
static void b2ScatterBodies( b2BodyState* B2_RESTRICT states, int* B2_RESTRICT indices, const b2BodyStateW* B2_RESTRICT simdBody )
{
_Static_assert( sizeof( b2BodyState ) == 32, "b2BodyState not 32 bytes" );
B2_ASSERT( ( (uintptr_t)states & 0x1F ) == 0 );
// b2FloatW x = b2SetW(0.0f, 1.0f, 2.0f, 3.0f);
// b2FloatW y = b2SetW(4.0f, 5.0f, 6.0f, 7.0f);
// b2FloatW z = b2SetW(8.0f, 9.0f, 10.0f, 11.0f);
// b2FloatW w = b2SetW(12.0f, 13.0f, 14.0f, 15.0f);
//
// float32x4x2_t rr1 = vtrnq_f32( x, y );
// float32x4x2_t rr2 = vtrnq_f32( z, w );
//
// float32x4_t b1 = vcombine_f32(vget_low_f32(rr1.val[0]), vget_low_f32(rr2.val[0]));
// float32x4_t b2 = vcombine_f32(vget_low_f32(rr1.val[1]), vget_low_f32(rr2.val[1]));
// float32x4_t b3 = vcombine_f32(vget_high_f32(rr1.val[0]), vget_high_f32(rr2.val[0]));
// float32x4_t b4 = vcombine_f32(vget_high_f32(rr1.val[1]), vget_high_f32(rr2.val[1]));
// transpose
float32x4x2_t r1 = vtrnq_f32( simdBody->v.X, simdBody->v.Y );
float32x4x2_t r2 = vtrnq_f32( simdBody->w, simdBody->flags );
// I don't use any dummy body in the body array because this will lead to multithreaded sharing and the
// associated cache flushing.
if ( indices[0] != B2_NULL_INDEX )
{
float32x4_t body1 = vcombine_f32( vget_low_f32( r1.val[0] ), vget_low_f32( r2.val[0] ) );
b2StoreW( (float*)( states + indices[0] ), body1 );
}
if ( indices[1] != B2_NULL_INDEX )
{
float32x4_t body2 = vcombine_f32( vget_low_f32( r1.val[1] ), vget_low_f32( r2.val[1] ) );
b2StoreW( (float*)( states + indices[1] ), body2 );
}
if ( indices[2] != B2_NULL_INDEX )
{
float32x4_t body3 = vcombine_f32( vget_high_f32( r1.val[0] ), vget_high_f32( r2.val[0] ) );
b2StoreW( (float*)( states + indices[2] ), body3 );
}
if ( indices[3] != B2_NULL_INDEX )
{
float32x4_t body4 = vcombine_f32( vget_high_f32( r1.val[1] ), vget_high_f32( r2.val[1] ) );
b2StoreW( (float*)( states + indices[3] ), body4 );
}
}
#elif defined( B2_SIMD_SSE2 )
// This is a load and transpose
static b2BodyStateW b2GatherBodies( const b2BodyState* B2_RESTRICT states, int* B2_RESTRICT indices )
{
_Static_assert( sizeof( b2BodyState ) == 32, "b2BodyState not 32 bytes" );
B2_ASSERT( ( (uintptr_t)states & 0x1F ) == 0 );
// [vx vy w flags]
b2FloatW identityA = b2ZeroW();
// [dpx dpy dqc dqs]
b2FloatW identityB = b2SetW( 0.0f, 0.0f, 1.0f, 0.0f );
b2FloatW b1a = indices[0] == B2_NULL_INDEX ? identityA : b2LoadW( (float*)( states + indices[0] ) + 0 );
b2FloatW b1b = indices[0] == B2_NULL_INDEX ? identityB : b2LoadW( (float*)( states + indices[0] ) + 4 );
b2FloatW b2a = indices[1] == B2_NULL_INDEX ? identityA : b2LoadW( (float*)( states + indices[1] ) + 0 );
b2FloatW b2b = indices[1] == B2_NULL_INDEX ? identityB : b2LoadW( (float*)( states + indices[1] ) + 4 );
b2FloatW b3a = indices[2] == B2_NULL_INDEX ? identityA : b2LoadW( (float*)( states + indices[2] ) + 0 );
b2FloatW b3b = indices[2] == B2_NULL_INDEX ? identityB : b2LoadW( (float*)( states + indices[2] ) + 4 );
b2FloatW b4a = indices[3] == B2_NULL_INDEX ? identityA : b2LoadW( (float*)( states + indices[3] ) + 0 );
b2FloatW b4b = indices[3] == B2_NULL_INDEX ? identityB : b2LoadW( (float*)( states + indices[3] ) + 4 );
// [vx1 vx3 vy1 vy3]
b2FloatW t1a = b2UnpackLoW( b1a, b3a );
// [vx2 vx4 vy2 vy4]
b2FloatW t2a = b2UnpackLoW( b2a, b4a );
// [w1 w3 f1 f3]
b2FloatW t3a = b2UnpackHiW( b1a, b3a );
// [w2 w4 f2 f4]
b2FloatW t4a = b2UnpackHiW( b2a, b4a );
b2BodyStateW simdBody;
simdBody.v.X = b2UnpackLoW( t1a, t2a );
simdBody.v.Y = b2UnpackHiW( t1a, t2a );
simdBody.w = b2UnpackLoW( t3a, t4a );
simdBody.flags = b2UnpackHiW( t3a, t4a );
b2FloatW t1b = b2UnpackLoW( b1b, b3b );
b2FloatW t2b = b2UnpackLoW( b2b, b4b );
b2FloatW t3b = b2UnpackHiW( b1b, b3b );
b2FloatW t4b = b2UnpackHiW( b2b, b4b );
simdBody.dp.X = b2UnpackLoW( t1b, t2b );
simdBody.dp.Y = b2UnpackHiW( t1b, t2b );
simdBody.dq.C = b2UnpackLoW( t3b, t4b );
simdBody.dq.S = b2UnpackHiW( t3b, t4b );
return simdBody;
}
// This writes only the velocities back to the solver bodies
static void b2ScatterBodies( b2BodyState* B2_RESTRICT states, int* B2_RESTRICT indices, const b2BodyStateW* B2_RESTRICT simdBody )
{
_Static_assert( sizeof( b2BodyState ) == 32, "b2BodyState not 32 bytes" );
B2_ASSERT( ( (uintptr_t)states & 0x1F ) == 0 );
// [vx1 vy1 vx2 vy2]
b2FloatW t1 = b2UnpackLoW( simdBody->v.X, simdBody->v.Y );
// [vx3 vy3 vx4 vy4]
b2FloatW t2 = b2UnpackHiW( simdBody->v.X, simdBody->v.Y );
// [w1 f1 w2 f2]
b2FloatW t3 = b2UnpackLoW( simdBody->w, simdBody->flags );
// [w3 f3 w4 f4]
b2FloatW t4 = b2UnpackHiW( simdBody->w, simdBody->flags );
// I don't use any dummy body in the body array because this will lead to multithreaded sharing and the
// associated cache flushing.
if ( indices[0] != B2_NULL_INDEX )
{
// [t1.x t1.y t3.x t3.y]
b2StoreW( (float*)( states + indices[0] ), _mm_shuffle_ps( t1, t3, _MM_SHUFFLE( 1, 0, 1, 0 ) ) );
}
if ( indices[1] != B2_NULL_INDEX )
{
// [t1.z t1.w t3.z t3.w]
b2StoreW( (float*)( states + indices[1] ), _mm_shuffle_ps( t1, t3, _MM_SHUFFLE( 3, 2, 3, 2 ) ) );
}
if ( indices[2] != B2_NULL_INDEX )
{
// [t2.x t2.y t4.x t4.y]
b2StoreW( (float*)( states + indices[2] ), _mm_shuffle_ps( t2, t4, _MM_SHUFFLE( 1, 0, 1, 0 ) ) );
}
if ( indices[3] != B2_NULL_INDEX )
{
// [t2.z t2.w t4.z t4.w]
b2StoreW( (float*)( states + indices[3] ), _mm_shuffle_ps( t2, t4, _MM_SHUFFLE( 3, 2, 3, 2 ) ) );
}
}
#else
// This is a load and transpose
static b2BodyStateW b2GatherBodies( const b2BodyState* B2_RESTRICT states, int* B2_RESTRICT indices )
{
b2BodyState identity = b2_identityBodyState;
b2BodyState s1 = indices[0] == B2_NULL_INDEX ? identity : states[indices[0]];
b2BodyState s2 = indices[1] == B2_NULL_INDEX ? identity : states[indices[1]];
b2BodyState s3 = indices[2] == B2_NULL_INDEX ? identity : states[indices[2]];
b2BodyState s4 = indices[3] == B2_NULL_INDEX ? identity : states[indices[3]];
b2BodyStateW simdBody;
simdBody.v.X = (b2FloatW){ s1.linearVelocity.x, s2.linearVelocity.x, s3.linearVelocity.x, s4.linearVelocity.x };
simdBody.v.Y = (b2FloatW){ s1.linearVelocity.y, s2.linearVelocity.y, s3.linearVelocity.y, s4.linearVelocity.y };
simdBody.w = (b2FloatW){ s1.angularVelocity, s2.angularVelocity, s3.angularVelocity, s4.angularVelocity };
simdBody.flags = (b2FloatW){ (float)s1.flags, (float)s2.flags, (float)s3.flags, (float)s4.flags };
simdBody.dp.X = (b2FloatW){ s1.deltaPosition.x, s2.deltaPosition.x, s3.deltaPosition.x, s4.deltaPosition.x };
simdBody.dp.Y = (b2FloatW){ s1.deltaPosition.y, s2.deltaPosition.y, s3.deltaPosition.y, s4.deltaPosition.y };
simdBody.dq.C = (b2FloatW){ s1.deltaRotation.c, s2.deltaRotation.c, s3.deltaRotation.c, s4.deltaRotation.c };
simdBody.dq.S = (b2FloatW){ s1.deltaRotation.s, s2.deltaRotation.s, s3.deltaRotation.s, s4.deltaRotation.s };
return simdBody;
}
// This writes only the velocities back to the solver bodies
static void b2ScatterBodies( b2BodyState* B2_RESTRICT states, int* B2_RESTRICT indices, const b2BodyStateW* B2_RESTRICT simdBody )
{
// todo somehow skip writing to kinematic bodies
if ( indices[0] != B2_NULL_INDEX )
{
b2BodyState* state = states + indices[0];
state->linearVelocity.x = simdBody->v.X.x;
state->linearVelocity.y = simdBody->v.Y.x;
state->angularVelocity = simdBody->w.x;
}
if ( indices[1] != B2_NULL_INDEX )
{
b2BodyState* state = states + indices[1];
state->linearVelocity.x = simdBody->v.X.y;
state->linearVelocity.y = simdBody->v.Y.y;
state->angularVelocity = simdBody->w.y;
}
if ( indices[2] != B2_NULL_INDEX )
{
b2BodyState* state = states + indices[2];
state->linearVelocity.x = simdBody->v.X.z;
state->linearVelocity.y = simdBody->v.Y.z;
state->angularVelocity = simdBody->w.z;
}
if ( indices[3] != B2_NULL_INDEX )
{
b2BodyState* state = states + indices[3];
state->linearVelocity.x = simdBody->v.X.w;
state->linearVelocity.y = simdBody->v.Y.w;
state->angularVelocity = simdBody->w.w;
}
}
#endif
void b2PrepareContactsTask( int startIndex, int endIndex, b2StepContext* context )
{
b2TracyCZoneNC( prepare_contact, "Prepare Contact", b2_colorYellow, true );
b2World* world = context->world;
b2ContactSim** contacts = context->contacts;
b2ContactConstraintSIMD* constraints = context->simdContactConstraints;
b2BodyState* awakeStates = context->states;
#if B2_VALIDATE
b2Body* bodies = world->bodies.data;
#endif
// Stiffer for static contacts to avoid bodies getting pushed through the ground
b2Softness contactSoftness = context->contactSoftness;
b2Softness staticSoftness = context->staticSoftness;
float warmStartScale = world->enableWarmStarting ? 1.0f : 0.0f;
for ( int i = startIndex; i < endIndex; ++i )
{
b2ContactConstraintSIMD* constraint = constraints + i;
for ( int j = 0; j < B2_SIMD_WIDTH; ++j )
{
b2ContactSim* contactSim = contacts[B2_SIMD_WIDTH * i + j];
if ( contactSim != NULL )
{
const b2Manifold* manifold = &contactSim->manifold;
int indexA = contactSim->bodySimIndexA;
int indexB = contactSim->bodySimIndexB;
#if B2_VALIDATE
b2Body* bodyA = bodies + contactSim->bodyIdA;
int validIndexA = bodyA->setIndex == b2_awakeSet ? bodyA->localIndex : B2_NULL_INDEX;
b2Body* bodyB = bodies + contactSim->bodyIdB;
int validIndexB = bodyB->setIndex == b2_awakeSet ? bodyB->localIndex : B2_NULL_INDEX;
B2_ASSERT( indexA == validIndexA );
B2_ASSERT( indexB == validIndexB );
#endif
constraint->indexA[j] = indexA;
constraint->indexB[j] = indexB;
b2Vec2 vA = b2Vec2_zero;
float wA = 0.0f;
float mA = contactSim->invMassA;
float iA = contactSim->invIA;
if ( indexA != B2_NULL_INDEX )
{
b2BodyState* stateA = awakeStates + indexA;
vA = stateA->linearVelocity;
wA = stateA->angularVelocity;
}
b2Vec2 vB = b2Vec2_zero;
float wB = 0.0f;
float mB = contactSim->invMassB;
float iB = contactSim->invIB;
if ( indexB != B2_NULL_INDEX )
{
b2BodyState* stateB = awakeStates + indexB;
vB = stateB->linearVelocity;
wB = stateB->angularVelocity;
}
( (float*)&constraint->invMassA )[j] = mA;
( (float*)&constraint->invMassB )[j] = mB;
( (float*)&constraint->invIA )[j] = iA;
( (float*)&constraint->invIB )[j] = iB;
{
float k = iA + iB;
( (float*)&constraint->rollingMass )[j] = k > 0.0f ? 1.0f / k : 0.0f;
}
b2Softness soft = ( indexA == B2_NULL_INDEX || indexB == B2_NULL_INDEX ) ? staticSoftness : contactSoftness;
b2Vec2 normal = manifold->normal;
( (float*)&constraint->normal.X )[j] = normal.x;
( (float*)&constraint->normal.Y )[j] = normal.y;
( (float*)&constraint->friction )[j] = contactSim->friction;
( (float*)&constraint->tangentSpeed )[j] = contactSim->tangentSpeed;
( (float*)&constraint->restitution )[j] = contactSim->restitution;
( (float*)&constraint->rollingResistance )[j] = contactSim->rollingResistance;
( (float*)&constraint->rollingImpulse )[j] = warmStartScale * manifold->rollingImpulse;
( (float*)&constraint->biasRate )[j] = soft.biasRate;
( (float*)&constraint->massScale )[j] = soft.massScale;
( (float*)&constraint->impulseScale )[j] = soft.impulseScale;
b2Vec2 tangent = b2RightPerp( normal );
{
const b2ManifoldPoint* mp = manifold->points + 0;
b2Vec2 rA = mp->anchorA;
b2Vec2 rB = mp->anchorB;
( (float*)&constraint->anchorA1.X )[j] = rA.x;
( (float*)&constraint->anchorA1.Y )[j] = rA.y;
( (float*)&constraint->anchorB1.X )[j] = rB.x;
( (float*)&constraint->anchorB1.Y )[j] = rB.y;
( (float*)&constraint->baseSeparation1 )[j] = mp->separation - b2Dot( b2Sub( rB, rA ), normal );
( (float*)&constraint->normalImpulse1 )[j] = warmStartScale * mp->normalImpulse;
( (float*)&constraint->tangentImpulse1 )[j] = warmStartScale * mp->tangentImpulse;
( (float*)&constraint->totalNormalImpulse1 )[j] = 0.0f;
float rnA = b2Cross( rA, normal );
float rnB = b2Cross( rB, normal );
float kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
( (float*)&constraint->normalMass1 )[j] = kNormal > 0.0f ? 1.0f / kNormal : 0.0f;
float rtA = b2Cross( rA, tangent );
float rtB = b2Cross( rB, tangent );
float kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB;
( (float*)&constraint->tangentMass1 )[j] = kTangent > 0.0f ? 1.0f / kTangent : 0.0f;
// relative velocity for restitution
b2Vec2 vrA = b2Add( vA, b2CrossSV( wA, rA ) );
b2Vec2 vrB = b2Add( vB, b2CrossSV( wB, rB ) );
( (float*)&constraint->relativeVelocity1 )[j] = b2Dot( normal, b2Sub( vrB, vrA ) );
}
int pointCount = manifold->pointCount;
B2_ASSERT( 0 < pointCount && pointCount <= 2 );
if ( pointCount == 2 )
{
const b2ManifoldPoint* mp = manifold->points + 1;
b2Vec2 rA = mp->anchorA;
b2Vec2 rB = mp->anchorB;
( (float*)&constraint->anchorA2.X )[j] = rA.x;
( (float*)&constraint->anchorA2.Y )[j] = rA.y;
( (float*)&constraint->anchorB2.X )[j] = rB.x;
( (float*)&constraint->anchorB2.Y )[j] = rB.y;
( (float*)&constraint->baseSeparation2 )[j] = mp->separation - b2Dot( b2Sub( rB, rA ), normal );
( (float*)&constraint->normalImpulse2 )[j] = warmStartScale * mp->normalImpulse;
( (float*)&constraint->tangentImpulse2 )[j] = warmStartScale * mp->tangentImpulse;
( (float*)&constraint->totalNormalImpulse2 )[j] = 0.0f;
float rnA = b2Cross( rA, normal );
float rnB = b2Cross( rB, normal );
float kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
( (float*)&constraint->normalMass2 )[j] = kNormal > 0.0f ? 1.0f / kNormal : 0.0f;
float rtA = b2Cross( rA, tangent );
float rtB = b2Cross( rB, tangent );
float kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB;
( (float*)&constraint->tangentMass2 )[j] = kTangent > 0.0f ? 1.0f / kTangent : 0.0f;
// relative velocity for restitution
b2Vec2 vrA = b2Add( vA, b2CrossSV( wA, rA ) );
b2Vec2 vrB = b2Add( vB, b2CrossSV( wB, rB ) );
( (float*)&constraint->relativeVelocity2 )[j] = b2Dot( normal, b2Sub( vrB, vrA ) );
}
else
{
// dummy data that has no effect
( (float*)&constraint->baseSeparation2 )[j] = 0.0f;
( (float*)&constraint->normalImpulse2 )[j] = 0.0f;
( (float*)&constraint->tangentImpulse2 )[j] = 0.0f;
( (float*)&constraint->totalNormalImpulse2 )[j] = 0.0f;
( (float*)&constraint->anchorA2.X )[j] = 0.0f;
( (float*)&constraint->anchorA2.Y )[j] = 0.0f;
( (float*)&constraint->anchorB2.X )[j] = 0.0f;
( (float*)&constraint->anchorB2.Y )[j] = 0.0f;
( (float*)&constraint->normalMass2 )[j] = 0.0f;
( (float*)&constraint->tangentMass2 )[j] = 0.0f;
( (float*)&constraint->relativeVelocity2 )[j] = 0.0f;
}
}
else
{
// SIMD remainder
constraint->indexA[j] = B2_NULL_INDEX;
constraint->indexB[j] = B2_NULL_INDEX;
( (float*)&constraint->invMassA )[j] = 0.0f;
( (float*)&constraint->invMassB )[j] = 0.0f;
( (float*)&constraint->invIA )[j] = 0.0f;
( (float*)&constraint->invIB )[j] = 0.0f;
( (float*)&constraint->normal.X )[j] = 0.0f;
( (float*)&constraint->normal.Y )[j] = 0.0f;
( (float*)&constraint->friction )[j] = 0.0f;
( (float*)&constraint->tangentSpeed )[j] = 0.0f;
( (float*)&constraint->rollingResistance )[j] = 0.0f;
( (float*)&constraint->rollingMass )[j] = 0.0f;
( (float*)&constraint->rollingImpulse )[j] = 0.0f;
( (float*)&constraint->biasRate )[j] = 0.0f;
( (float*)&constraint->massScale )[j] = 0.0f;
( (float*)&constraint->impulseScale )[j] = 0.0f;
( (float*)&constraint->anchorA1.X )[j] = 0.0f;
( (float*)&constraint->anchorA1.Y )[j] = 0.0f;
( (float*)&constraint->anchorB1.X )[j] = 0.0f;
( (float*)&constraint->anchorB1.Y )[j] = 0.0f;
( (float*)&constraint->baseSeparation1 )[j] = 0.0f;
( (float*)&constraint->normalImpulse1 )[j] = 0.0f;
( (float*)&constraint->tangentImpulse1 )[j] = 0.0f;
( (float*)&constraint->totalNormalImpulse1 )[j] = 0.0f;
( (float*)&constraint->normalMass1 )[j] = 0.0f;
( (float*)&constraint->tangentMass1 )[j] = 0.0f;
( (float*)&constraint->anchorA2.X )[j] = 0.0f;
( (float*)&constraint->anchorA2.Y )[j] = 0.0f;
( (float*)&constraint->anchorB2.X )[j] = 0.0f;
( (float*)&constraint->anchorB2.Y )[j] = 0.0f;
( (float*)&constraint->baseSeparation2 )[j] = 0.0f;
( (float*)&constraint->normalImpulse2 )[j] = 0.0f;
( (float*)&constraint->tangentImpulse2 )[j] = 0.0f;
( (float*)&constraint->totalNormalImpulse2 )[j] = 0.0f;
( (float*)&constraint->normalMass2 )[j] = 0.0f;
( (float*)&constraint->tangentMass2 )[j] = 0.0f;
( (float*)&constraint->restitution )[j] = 0.0f;
( (float*)&constraint->relativeVelocity1 )[j] = 0.0f;
( (float*)&constraint->relativeVelocity2 )[j] = 0.0f;
}
}
}
b2TracyCZoneEnd( prepare_contact );
}
void b2WarmStartContactsTask( int startIndex, int endIndex, b2StepContext* context, int colorIndex )
{
b2TracyCZoneNC( warm_start_contact, "Warm Start", b2_colorGreen, true );
b2BodyState* states = context->states;
b2ContactConstraintSIMD* constraints = context->graph->colors[colorIndex].simdConstraints;
for ( int i = startIndex; i < endIndex; ++i )
{
b2ContactConstraintSIMD* c = constraints + i;
b2BodyStateW bA = b2GatherBodies( states, c->indexA );
b2BodyStateW bB = b2GatherBodies( states, c->indexB );
b2FloatW tangentX = c->normal.Y;
b2FloatW tangentY = b2SubW( b2ZeroW(), c->normal.X );
{
// fixed anchors
b2Vec2W rA = c->anchorA1;
b2Vec2W rB = c->anchorB1;
b2Vec2W P;
P.X = b2AddW( b2MulW( c->normalImpulse1, c->normal.X ), b2MulW( c->tangentImpulse1, tangentX ) );
P.Y = b2AddW( b2MulW( c->normalImpulse1, c->normal.Y ), b2MulW( c->tangentImpulse1, tangentY ) );
bA.w = b2MulSubW( bA.w, c->invIA, b2CrossW( rA, P ) );
bA.v.X = b2MulSubW( bA.v.X, c->invMassA, P.X );
bA.v.Y = b2MulSubW( bA.v.Y, c->invMassA, P.Y );
bB.w = b2MulAddW( bB.w, c->invIB, b2CrossW( rB, P ) );
bB.v.X = b2MulAddW( bB.v.X, c->invMassB, P.X );
bB.v.Y = b2MulAddW( bB.v.Y, c->invMassB, P.Y );
}
{
// fixed anchors
b2Vec2W rA = c->anchorA2;
b2Vec2W rB = c->anchorB2;
b2Vec2W P;
P.X = b2AddW( b2MulW( c->normalImpulse2, c->normal.X ), b2MulW( c->tangentImpulse2, tangentX ) );
P.Y = b2AddW( b2MulW( c->normalImpulse2, c->normal.Y ), b2MulW( c->tangentImpulse2, tangentY ) );
bA.w = b2MulSubW( bA.w, c->invIA, b2CrossW( rA, P ) );
bA.v.X = b2MulSubW( bA.v.X, c->invMassA, P.X );
bA.v.Y = b2MulSubW( bA.v.Y, c->invMassA, P.Y );
bB.w = b2MulAddW( bB.w, c->invIB, b2CrossW( rB, P ) );
bB.v.X = b2MulAddW( bB.v.X, c->invMassB, P.X );
bB.v.Y = b2MulAddW( bB.v.Y, c->invMassB, P.Y );
}
bA.w = b2MulSubW( bA.w, c->invIA, c->rollingImpulse );
bB.w = b2MulAddW( bB.w, c->invIB, c->rollingImpulse );
b2ScatterBodies( states, c->indexA, &bA );
b2ScatterBodies( states, c->indexB, &bB );
}
b2TracyCZoneEnd( warm_start_contact );
}
void b2SolveContactsTask( int startIndex, int endIndex, b2StepContext* context, int colorIndex, bool useBias )
{
b2TracyCZoneNC( solve_contact, "Solve Contact", b2_colorAliceBlue, true );
b2BodyState* states = context->states;
b2ContactConstraintSIMD* constraints = context->graph->colors[colorIndex].simdConstraints;
b2FloatW inv_h = b2SplatW( context->inv_h );
b2FloatW minBiasVel = b2SplatW( -context->world->maxContactPushSpeed );
b2FloatW oneW = b2SplatW( 1.0f );
for ( int i = startIndex; i < endIndex; ++i )
{
b2ContactConstraintSIMD* c = constraints + i;
b2BodyStateW bA = b2GatherBodies( states, c->indexA );
b2BodyStateW bB = b2GatherBodies( states, c->indexB );
b2FloatW biasRate, massScale, impulseScale;
if ( useBias )
{
biasRate = c->biasRate;
massScale = c->massScale;
impulseScale = c->impulseScale;
}
else
{
biasRate = b2ZeroW();
massScale = oneW;
impulseScale = b2ZeroW();
}
b2FloatW totalNormalImpulse = b2ZeroW();
b2Vec2W dp = { b2SubW( bB.dp.X, bA.dp.X ), b2SubW( bB.dp.Y, bA.dp.Y ) };
// point1 non-penetration constraint
{
// Fixed anchors for impulses
b2Vec2W rA = c->anchorA1;
b2Vec2W rB = c->anchorB1;
// Moving anchors for current separation
b2Vec2W rsA = b2RotateVectorW( bA.dq, rA );
b2Vec2W rsB = b2RotateVectorW( bB.dq, rB );
// compute current separation
// this is subject to round-off error if the anchor is far from the body center of mass
b2Vec2W ds = { b2AddW( dp.X, b2SubW( rsB.X, rsA.X ) ), b2AddW( dp.Y, b2SubW( rsB.Y, rsA.Y ) ) };
b2FloatW s = b2AddW( b2DotW( c->normal, ds ), c->baseSeparation1 );
// Apply speculative bias if separation is greater than zero, otherwise apply soft constraint bias
// The minBiasVel is meant to limit stiffness, not increase it.
b2FloatW mask = b2GreaterThanW( s, b2ZeroW() );
b2FloatW specBias = b2MulW( s, inv_h );
b2FloatW softBias = b2MaxW( b2MulW( biasRate, s ), minBiasVel );
// todo try b2MaxW(softBias, specBias);
b2FloatW bias = b2BlendW( softBias, specBias, mask );
b2FloatW pointMassScale = b2BlendW( massScale, oneW, mask );
b2FloatW pointImpulseScale = b2BlendW( impulseScale, b2ZeroW(), mask );
// Relative velocity at contact
b2FloatW dvx = b2SubW( b2SubW( bB.v.X, b2MulW( bB.w, rB.Y ) ), b2SubW( bA.v.X, b2MulW( bA.w, rA.Y ) ) );
b2FloatW dvy = b2SubW( b2AddW( bB.v.Y, b2MulW( bB.w, rB.X ) ), b2AddW( bA.v.Y, b2MulW( bA.w, rA.X ) ) );
b2FloatW vn = b2AddW( b2MulW( dvx, c->normal.X ), b2MulW( dvy, c->normal.Y ) );
// Compute normal impulse
b2FloatW negImpulse = b2AddW( b2MulW( c->normalMass1, b2MulW( pointMassScale, b2AddW( vn, bias ) ) ),
b2MulW( pointImpulseScale, c->normalImpulse1 ) );
// Clamp the accumulated impulse
b2FloatW newImpulse = b2MaxW( b2SubW( c->normalImpulse1, negImpulse ), b2ZeroW() );
b2FloatW impulse = b2SubW( newImpulse, c->normalImpulse1 );
c->normalImpulse1 = newImpulse;
c->totalNormalImpulse1 = b2AddW( c->totalNormalImpulse1, newImpulse );
totalNormalImpulse = b2AddW( totalNormalImpulse, newImpulse );
// Apply contact impulse
b2FloatW Px = b2MulW( impulse, c->normal.X );
b2FloatW Py = b2MulW( impulse, c->normal.Y );
bA.v.X = b2MulSubW( bA.v.X, c->invMassA, Px );
bA.v.Y = b2MulSubW( bA.v.Y, c->invMassA, Py );
bA.w = b2MulSubW( bA.w, c->invIA, b2SubW( b2MulW( rA.X, Py ), b2MulW( rA.Y, Px ) ) );
bB.v.X = b2MulAddW( bB.v.X, c->invMassB, Px );
bB.v.Y = b2MulAddW( bB.v.Y, c->invMassB, Py );
bB.w = b2MulAddW( bB.w, c->invIB, b2SubW( b2MulW( rB.X, Py ), b2MulW( rB.Y, Px ) ) );
}
// second point non-penetration constraint
{
// moving anchors for current separation
b2Vec2W rsA = b2RotateVectorW( bA.dq, c->anchorA2 );
b2Vec2W rsB = b2RotateVectorW( bB.dq, c->anchorB2 );
// compute current separation
b2Vec2W ds = { b2AddW( dp.X, b2SubW( rsB.X, rsA.X ) ), b2AddW( dp.Y, b2SubW( rsB.Y, rsA.Y ) ) };
b2FloatW s = b2AddW( b2DotW( c->normal, ds ), c->baseSeparation2 );
b2FloatW mask = b2GreaterThanW( s, b2ZeroW() );
b2FloatW specBias = b2MulW( s, inv_h );
b2FloatW softBias = b2MaxW( b2MulW( biasRate, s ), minBiasVel );
b2FloatW bias = b2BlendW( softBias, specBias, mask );
b2FloatW pointMassScale = b2BlendW( massScale, oneW, mask );
b2FloatW pointImpulseScale = b2BlendW( impulseScale, b2ZeroW(), mask );
// fixed anchors for Jacobians
b2Vec2W rA = c->anchorA2;
b2Vec2W rB = c->anchorB2;
// Relative velocity at contact
b2FloatW dvx = b2SubW( b2SubW( bB.v.X, b2MulW( bB.w, rB.Y ) ), b2SubW( bA.v.X, b2MulW( bA.w, rA.Y ) ) );
b2FloatW dvy = b2SubW( b2AddW( bB.v.Y, b2MulW( bB.w, rB.X ) ), b2AddW( bA.v.Y, b2MulW( bA.w, rA.X ) ) );
b2FloatW vn = b2AddW( b2MulW( dvx, c->normal.X ), b2MulW( dvy, c->normal.Y ) );
// Compute normal impulse
b2FloatW negImpulse = b2AddW( b2MulW( c->normalMass2, b2MulW( pointMassScale, b2AddW( vn, bias ) ) ),
b2MulW( pointImpulseScale, c->normalImpulse2 ) );
// Clamp the accumulated impulse
b2FloatW newImpulse = b2MaxW( b2SubW( c->normalImpulse2, negImpulse ), b2ZeroW() );
b2FloatW impulse = b2SubW( newImpulse, c->normalImpulse2 );
c->normalImpulse2 = newImpulse;
c->totalNormalImpulse2 = b2AddW( c->totalNormalImpulse2, newImpulse );
totalNormalImpulse = b2AddW( totalNormalImpulse, newImpulse );
// Apply contact impulse
b2FloatW Px = b2MulW( impulse, c->normal.X );
b2FloatW Py = b2MulW( impulse, c->normal.Y );
bA.v.X = b2MulSubW( bA.v.X, c->invMassA, Px );
bA.v.Y = b2MulSubW( bA.v.Y, c->invMassA, Py );
bA.w = b2MulSubW( bA.w, c->invIA, b2SubW( b2MulW( rA.X, Py ), b2MulW( rA.Y, Px ) ) );
bB.v.X = b2MulAddW( bB.v.X, c->invMassB, Px );
bB.v.Y = b2MulAddW( bB.v.Y, c->invMassB, Py );
bB.w = b2MulAddW( bB.w, c->invIB, b2SubW( b2MulW( rB.X, Py ), b2MulW( rB.Y, Px ) ) );
}
b2FloatW tangentX = c->normal.Y;
b2FloatW tangentY = b2SubW( b2ZeroW(), c->normal.X );
// point 1 friction constraint
{
// fixed anchors for Jacobians
b2Vec2W rA = c->anchorA1;
b2Vec2W rB = c->anchorB1;
// Relative velocity at contact
b2FloatW dvx = b2SubW( b2SubW( bB.v.X, b2MulW( bB.w, rB.Y ) ), b2SubW( bA.v.X, b2MulW( bA.w, rA.Y ) ) );
b2FloatW dvy = b2SubW( b2AddW( bB.v.Y, b2MulW( bB.w, rB.X ) ), b2AddW( bA.v.Y, b2MulW( bA.w, rA.X ) ) );
b2FloatW vt = b2AddW( b2MulW( dvx, tangentX ), b2MulW( dvy, tangentY ) );
// Tangent speed (conveyor belt)
vt = b2SubW( vt, c->tangentSpeed );
// Compute tangent force
b2FloatW negImpulse = b2MulW( c->tangentMass1, vt );
// Clamp the accumulated force
b2FloatW maxFriction = b2MulW( c->friction, c->normalImpulse1 );
b2FloatW newImpulse = b2SubW( c->tangentImpulse1, negImpulse );
newImpulse = b2MaxW( b2SubW( b2ZeroW(), maxFriction ), b2MinW( newImpulse, maxFriction ) );
b2FloatW impulse = b2SubW( newImpulse, c->tangentImpulse1 );
c->tangentImpulse1 = newImpulse;
// Apply contact impulse
b2FloatW Px = b2MulW( impulse, tangentX );
b2FloatW Py = b2MulW( impulse, tangentY );
bA.v.X = b2MulSubW( bA.v.X, c->invMassA, Px );
bA.v.Y = b2MulSubW( bA.v.Y, c->invMassA, Py );
bA.w = b2MulSubW( bA.w, c->invIA, b2SubW( b2MulW( rA.X, Py ), b2MulW( rA.Y, Px ) ) );
bB.v.X = b2MulAddW( bB.v.X, c->invMassB, Px );
bB.v.Y = b2MulAddW( bB.v.Y, c->invMassB, Py );
bB.w = b2MulAddW( bB.w, c->invIB, b2SubW( b2MulW( rB.X, Py ), b2MulW( rB.Y, Px ) ) );
}
// second point friction constraint
{
// fixed anchors for Jacobians
b2Vec2W rA = c->anchorA2;
b2Vec2W rB = c->anchorB2;
// Relative velocity at contact
b2FloatW dvx = b2SubW( b2SubW( bB.v.X, b2MulW( bB.w, rB.Y ) ), b2SubW( bA.v.X, b2MulW( bA.w, rA.Y ) ) );
b2FloatW dvy = b2SubW( b2AddW( bB.v.Y, b2MulW( bB.w, rB.X ) ), b2AddW( bA.v.Y, b2MulW( bA.w, rA.X ) ) );
b2FloatW vt = b2AddW( b2MulW( dvx, tangentX ), b2MulW( dvy, tangentY ) );
// Tangent speed (conveyor belt)
vt = b2SubW( vt, c->tangentSpeed );
// Compute tangent force
b2FloatW negImpulse = b2MulW( c->tangentMass2, vt );
// Clamp the accumulated force
b2FloatW maxFriction = b2MulW( c->friction, c->normalImpulse2 );
b2FloatW newImpulse = b2SubW( c->tangentImpulse2, negImpulse );
newImpulse = b2MaxW( b2SubW( b2ZeroW(), maxFriction ), b2MinW( newImpulse, maxFriction ) );
b2FloatW impulse = b2SubW( newImpulse, c->tangentImpulse2 );
c->tangentImpulse2 = newImpulse;
// Apply contact impulse
b2FloatW Px = b2MulW( impulse, tangentX );
b2FloatW Py = b2MulW( impulse, tangentY );
bA.v.X = b2MulSubW( bA.v.X, c->invMassA, Px );
bA.v.Y = b2MulSubW( bA.v.Y, c->invMassA, Py );
bA.w = b2MulSubW( bA.w, c->invIA, b2SubW( b2MulW( rA.X, Py ), b2MulW( rA.Y, Px ) ) );
bB.v.X = b2MulAddW( bB.v.X, c->invMassB, Px );
bB.v.Y = b2MulAddW( bB.v.Y, c->invMassB, Py );
bB.w = b2MulAddW( bB.w, c->invIB, b2SubW( b2MulW( rB.X, Py ), b2MulW( rB.Y, Px ) ) );
}
// Rolling resistance
{
b2FloatW deltaLambda = b2MulW( c->rollingMass, b2SubW( bA.w, bB.w ) );
b2FloatW lambda = c->rollingImpulse;
b2FloatW maxLambda = b2MulW( c->rollingResistance, totalNormalImpulse );
c->rollingImpulse = b2SymClampW( b2AddW( lambda, deltaLambda ), maxLambda );
deltaLambda = b2SubW( c->rollingImpulse, lambda );
bA.w = b2MulSubW( bA.w, c->invIA, deltaLambda );
bB.w = b2MulAddW( bB.w, c->invIB, deltaLambda );
}
b2ScatterBodies( states, c->indexA, &bA );
b2ScatterBodies( states, c->indexB, &bB );
}
b2TracyCZoneEnd( solve_contact );
}
void b2ApplyRestitutionTask( int startIndex, int endIndex, b2StepContext* context, int colorIndex )
{
b2TracyCZoneNC( restitution, "Restitution", b2_colorDodgerBlue, true );
b2BodyState* states = context->states;
b2ContactConstraintSIMD* constraints = context->graph->colors[colorIndex].simdConstraints;
b2FloatW threshold = b2SplatW( context->world->restitutionThreshold );
b2FloatW zero = b2ZeroW();
for ( int i = startIndex; i < endIndex; ++i )
{
b2ContactConstraintSIMD* c = constraints + i;
if ( b2AllZeroW( c->restitution ) )
{
// No lanes have restitution. Common case.
continue;
}
// Create a mask based on restitution so that lanes with no restitution are not affected
// by the calculations below.
b2FloatW restitutionMask = b2EqualsW( c->restitution, zero );
b2BodyStateW bA = b2GatherBodies( states, c->indexA );
b2BodyStateW bB = b2GatherBodies( states, c->indexB );
// first point non-penetration constraint
{
// Set effective mass to zero if restitution should not be applied
b2FloatW mask1 = b2GreaterThanW( b2AddW( c->relativeVelocity1, threshold ), zero );
b2FloatW mask2 = b2EqualsW( c->totalNormalImpulse1, zero );
b2FloatW mask = b2OrW( b2OrW( mask1, mask2 ), restitutionMask );
b2FloatW mass = b2BlendW( c->normalMass1, zero, mask );
// fixed anchors for Jacobians
b2Vec2W rA = c->anchorA1;
b2Vec2W rB = c->anchorB1;
// Relative velocity at contact
b2FloatW dvx = b2SubW( b2SubW( bB.v.X, b2MulW( bB.w, rB.Y ) ), b2SubW( bA.v.X, b2MulW( bA.w, rA.Y ) ) );
b2FloatW dvy = b2SubW( b2AddW( bB.v.Y, b2MulW( bB.w, rB.X ) ), b2AddW( bA.v.Y, b2MulW( bA.w, rA.X ) ) );
b2FloatW vn = b2AddW( b2MulW( dvx, c->normal.X ), b2MulW( dvy, c->normal.Y ) );
// Compute normal impulse
b2FloatW negImpulse = b2MulW( mass, b2AddW( vn, b2MulW( c->restitution, c->relativeVelocity1 ) ) );
// Clamp the accumulated impulse
b2FloatW newImpulse = b2MaxW( b2SubW( c->normalImpulse1, negImpulse ), b2ZeroW() );
b2FloatW impulse = b2SubW( newImpulse, c->normalImpulse1 );
c->normalImpulse1 = newImpulse;
// Apply contact impulse
b2FloatW Px = b2MulW( impulse, c->normal.X );
b2FloatW Py = b2MulW( impulse, c->normal.Y );
bA.v.X = b2MulSubW( bA.v.X, c->invMassA, Px );
bA.v.Y = b2MulSubW( bA.v.Y, c->invMassA, Py );
bA.w = b2MulSubW( bA.w, c->invIA, b2SubW( b2MulW( rA.X, Py ), b2MulW( rA.Y, Px ) ) );
bB.v.X = b2MulAddW( bB.v.X, c->invMassB, Px );
bB.v.Y = b2MulAddW( bB.v.Y, c->invMassB, Py );
bB.w = b2MulAddW( bB.w, c->invIB, b2SubW( b2MulW( rB.X, Py ), b2MulW( rB.Y, Px ) ) );
}
// second point non-penetration constraint
{
// Set effective mass to zero if restitution should not be applied
b2FloatW mask1 = b2GreaterThanW( b2AddW( c->relativeVelocity2, threshold ), zero );
b2FloatW mask2 = b2EqualsW( c->totalNormalImpulse2, zero );
b2FloatW mask = b2OrW( b2OrW( mask1, mask2 ), restitutionMask );
b2FloatW mass = b2BlendW( c->normalMass2, zero, mask );
// fixed anchors for Jacobians
b2Vec2W rA = c->anchorA2;
b2Vec2W rB = c->anchorB2;
// Relative velocity at contact
b2FloatW dvx = b2SubW( b2SubW( bB.v.X, b2MulW( bB.w, rB.Y ) ), b2SubW( bA.v.X, b2MulW( bA.w, rA.Y ) ) );
b2FloatW dvy = b2SubW( b2AddW( bB.v.Y, b2MulW( bB.w, rB.X ) ), b2AddW( bA.v.Y, b2MulW( bA.w, rA.X ) ) );
b2FloatW vn = b2AddW( b2MulW( dvx, c->normal.X ), b2MulW( dvy, c->normal.Y ) );
// Compute normal impulse
b2FloatW negImpulse = b2MulW( mass, b2AddW( vn, b2MulW( c->restitution, c->relativeVelocity2 ) ) );
// Clamp the accumulated impulse
b2FloatW newImpulse = b2MaxW( b2SubW( c->normalImpulse2, negImpulse ), b2ZeroW() );
b2FloatW impulse = b2SubW( newImpulse, c->normalImpulse2 );
c->normalImpulse2 = newImpulse;
// Apply contact impulse
b2FloatW Px = b2MulW( impulse, c->normal.X );
b2FloatW Py = b2MulW( impulse, c->normal.Y );
bA.v.X = b2MulSubW( bA.v.X, c->invMassA, Px );
bA.v.Y = b2MulSubW( bA.v.Y, c->invMassA, Py );
bA.w = b2MulSubW( bA.w, c->invIA, b2SubW( b2MulW( rA.X, Py ), b2MulW( rA.Y, Px ) ) );
bB.v.X = b2MulAddW( bB.v.X, c->invMassB, Px );
bB.v.Y = b2MulAddW( bB.v.Y, c->invMassB, Py );
bB.w = b2MulAddW( bB.w, c->invIB, b2SubW( b2MulW( rB.X, Py ), b2MulW( rB.Y, Px ) ) );
}
b2ScatterBodies( states, c->indexA, &bA );
b2ScatterBodies( states, c->indexB, &bB );
}
b2TracyCZoneEnd( restitution );
}
void b2StoreImpulsesTask( int startIndex, int endIndex, b2StepContext* context )
{
b2TracyCZoneNC( store_impulses, "Store", b2_colorFireBrick, true );
b2ContactSim** contacts = context->contacts;
const b2ContactConstraintSIMD* constraints = context->simdContactConstraints;
b2Manifold dummy = { 0 };
for ( int constraintIndex = startIndex; constraintIndex < endIndex; ++constraintIndex )
{
const b2ContactConstraintSIMD* c = constraints + constraintIndex;
const float* rollingImpulse = (float*)&c->rollingImpulse;
const float* normalImpulse1 = (float*)&c->normalImpulse1;
const float* normalImpulse2 = (float*)&c->normalImpulse2;
const float* tangentImpulse1 = (float*)&c->tangentImpulse1;
const float* tangentImpulse2 = (float*)&c->tangentImpulse2;
const float* totalNormalImpulse1 = (float*)&c->totalNormalImpulse1;
const float* totalNormalImpulse2 = (float*)&c->totalNormalImpulse2;
const float* normalVelocity1 = (float*)&c->relativeVelocity1;
const float* normalVelocity2 = (float*)&c->relativeVelocity2;
int baseIndex = B2_SIMD_WIDTH * constraintIndex;
for ( int laneIndex = 0; laneIndex < B2_SIMD_WIDTH; ++laneIndex )
{
b2Manifold* m = contacts[baseIndex + laneIndex] == NULL ? &dummy : &contacts[baseIndex + laneIndex]->manifold;
m->rollingImpulse = rollingImpulse[laneIndex];
m->points[0].normalImpulse = normalImpulse1[laneIndex];
m->points[0].tangentImpulse = tangentImpulse1[laneIndex];
m->points[0].totalNormalImpulse = totalNormalImpulse1[laneIndex];
m->points[0].normalVelocity = normalVelocity1[laneIndex];
m->points[1].normalImpulse = normalImpulse2[laneIndex];
m->points[1].tangentImpulse = tangentImpulse2[laneIndex];
m->points[1].totalNormalImpulse = totalNormalImpulse2[laneIndex];
m->points[1].normalVelocity = normalVelocity2[laneIndex];
}
}
b2TracyCZoneEnd( store_impulses );
}
| 412 | 0.872272 | 1 | 0.872272 | game-dev | MEDIA | 0.71172 | game-dev | 0.97727 | 1 | 0.97727 |
Bam4d/Griddly | 24,809 | bindings/wrapper/GameProcess.cpp | #include <spdlog/spdlog.h>
#include "../../src/Griddly/Core/TurnBasedGameProcess.hpp"
#include "NumpyWrapper.cpp"
#include "Player.cpp"
#include "WrapperCommon.cpp"
namespace griddly {
class ValidActionNode {
public:
std::unordered_map<uint32_t, std::shared_ptr<ValidActionNode>> children;
bool contains(uint32_t value) {
return children.find(value) != children.end();
}
void add(uint32_t value) {
children[value] = std::make_shared<ValidActionNode>(ValidActionNode());
}
static py::dict toPyDict(std::shared_ptr<ValidActionNode> node) {
py::dict py_dict;
for (auto child : node->children) {
py_dict[py::cast(child.first)] = toPyDict(child.second);
}
return py_dict;
}
};
struct InfoAndTruncated {
py::dict info;
bool truncated;
};
class Py_GameProcess {
public:
Py_GameProcess(std::string globalObserverName, std::shared_ptr<GDYFactory> gdyFactory) : gdyFactory_(gdyFactory) {
std::shared_ptr<Grid> grid = std::make_shared<Grid>(Grid());
gameProcess_ = std::make_shared<TurnBasedGameProcess>(TurnBasedGameProcess(globalObserverName, gdyFactory, grid));
spdlog::debug("Created game process wrapper");
}
Py_GameProcess(std::shared_ptr<GDYFactory> gdyFactory, std::shared_ptr<TurnBasedGameProcess> gameProcess)
: gdyFactory_(gdyFactory),
gameProcess_(gameProcess) {
spdlog::debug("Cloned game process wrapper");
}
std::shared_ptr<TurnBasedGameProcess> unwrapped() {
return gameProcess_;
}
std::shared_ptr<Py_Player> registerPlayer(std::string playerName, std::string observerName) {
// auto observerName = Observer::getDefaultObserverName(observerType);
auto nextPlayerId = ++playerCount_;
auto player = std::make_shared<Py_Player>(Py_Player(nextPlayerId, playerName, observerName, gdyFactory_, gameProcess_));
players_.push_back(player);
gameProcess_->addPlayer(player->unwrapped());
return player;
}
const uint32_t getActionTypeId(std::string actionName) const {
auto actionNames = gdyFactory_->getExternalActionNames();
for (int i = 0; i < actionNames.size(); i++) {
if (actionNames[i] == actionName) {
return i;
}
}
throw std::runtime_error("unregistered action");
}
std::vector<py::dict> buildValidActionTrees() const {
std::vector<py::dict> valid_action_trees;
auto externalActionNames = gdyFactory_->getExternalActionNames();
spdlog::debug("Building tree, {0} actions", externalActionNames.size());
for (int playerId = 1; playerId <= playerCount_; playerId++) {
std::shared_ptr<ValidActionNode> node = std::make_shared<ValidActionNode>(ValidActionNode());
for (auto actionNamesAtLocation : gameProcess_->getAvailableActionNames(playerId)) {
auto location = actionNamesAtLocation.first;
auto actionNames = actionNamesAtLocation.second;
for (auto actionName : actionNames) {
spdlog::debug("[{0}] available at location [{1}, {2}]", actionName, location.x, location.y);
std::shared_ptr<ValidActionNode> treePtr = node;
auto actionInputsDefinitions = gdyFactory_->getActionInputsDefinitions();
if (actionInputsDefinitions.find(actionName) != actionInputsDefinitions.end()) {
auto locationVec = glm::ivec2{location[0], location[1]};
auto actionIdsForName = gameProcess_->getAvailableActionIdsAtLocation(locationVec, actionName);
spdlog::debug("{0} action ids available", actionIdsForName.size());
if (actionIdsForName.size() > 0) {
if (gdyFactory_->getAvatarObject().length() == 0) {
auto py_x = locationVec[0];
auto py_y = locationVec[1];
if (!treePtr->contains(py_x)) {
treePtr->add(py_x);
}
treePtr = treePtr->children[py_x];
if (!treePtr->contains(py_y)) {
treePtr->add(py_y);
}
treePtr = treePtr->children[py_y];
}
if (externalActionNames.size() > 1) {
auto actionTypeId = getActionTypeId(actionName);
if (!treePtr->contains(actionTypeId)) {
treePtr->add(actionTypeId);
}
treePtr = treePtr->children[actionTypeId];
}
for (auto id : actionIdsForName) {
treePtr->add(id);
}
treePtr->add(0);
}
}
}
}
valid_action_trees.push_back(ValidActionNode::toPyDict(node));
}
return valid_action_trees;
}
py::dict getAvailableActionNames(int playerId) const {
auto availableActionNames = gameProcess_->getAvailableActionNames(playerId);
py::dict py_availableActionNames;
for (auto availableActionNamesPair : availableActionNames) {
auto location = availableActionNamesPair.first;
auto actionNames = availableActionNamesPair.second;
py::tuple locationKeyTuple = py::cast(std::vector<int32_t>{location.x, location.y});
py_availableActionNames[locationKeyTuple] = actionNames;
}
return py_availableActionNames;
}
py::dict getAvailableActionIds(std::vector<int32_t> location, std::vector<std::string> actionNames) {
spdlog::debug("Getting available action ids for location [{0},{1}]", location[0], location[1]);
py::dict py_availableActionIds;
for (auto actionName : actionNames) {
auto actionInputsDefinitions = gdyFactory_->getActionInputsDefinitions();
if (actionInputsDefinitions.find(actionName) != actionInputsDefinitions.end()) {
auto locationVec = glm::ivec2{location[0], location[1]};
auto actionIdsForName = gameProcess_->getAvailableActionIdsAtLocation(locationVec, actionName);
py_availableActionIds[actionName.c_str()] = py::cast(actionIdsForName);
}
}
return py_availableActionIds;
}
void init(bool isCloned) {
gameProcess_->init(isCloned);
}
void loadLevel(uint32_t levelId) {
gameProcess_->setLevel(levelId);
}
void loadLevelString(std::string levelString) {
gameProcess_->setLevel(levelString);
}
void reset() {
gameProcess_->reset();
}
py::dict getGlobalObservationDescription() const {
return wrapObservationDescription(gameProcess_->getObserver());
}
py::object observe() {
return wrapObservation(gameProcess_->getObserver());
}
py::tuple stepParallel(py::buffer stepArray) {
auto stepArrayInfo = stepArray.request();
if (stepArrayInfo.format != "l" && stepArrayInfo.format != "i") {
auto error = fmt::format("Invalid data type {0}, must be an integer.", stepArrayInfo.format);
spdlog::error(error);
throw std::invalid_argument(error);
}
spdlog::debug("Dims: {0}", stepArrayInfo.ndim);
if (stepArrayInfo.ndim != 3) {
auto error = fmt::format("Invalid number of dimensions {0}, must be 3. [P,N,A] (Num Players, Number of actions, Action Size)", stepArrayInfo.ndim);
spdlog::error(error);
throw std::invalid_argument(error);
}
auto playerStride = stepArrayInfo.strides[0] / sizeof(int32_t);
auto numActionStride = stepArrayInfo.strides[1] / sizeof(int32_t);
auto actionArrayStride = stepArrayInfo.strides[2] / sizeof(int32_t);
spdlog::debug("Strides: {0}, {1}, {2}", playerStride, numActionStride, actionArrayStride);
auto playerSize = stepArrayInfo.shape[0];
auto numActionSize = stepArrayInfo.shape[1];
auto actionSize = stepArrayInfo.shape[2];
spdlog::debug("Shapes: {0}, {1}, {2}", playerSize, numActionSize, actionSize);
if (playerSize != playerCount_) {
auto error = fmt::format("The number of players {0} does not match the first dimension of the parallel action.", playerCount_);
spdlog::error(error);
throw std::invalid_argument(error);
}
auto externalActionNames = gdyFactory_->getExternalActionNames();
std::vector<int32_t> playerRewards{};
bool terminated = false;
bool truncated = false;
py::dict info{};
std::vector<uint32_t> playerIdx;
for (uint32_t p = 0; p < playerSize; p++) {
playerIdx.push_back(p);
}
std::shuffle(playerIdx.begin(), playerIdx.end(), gameProcess_->getGrid()->getRandomGenerator()->getEngine());
for (int i = 0; i < playerSize; i++) {
auto p = playerIdx[i];
auto pStr = p * playerStride;
bool lastPlayer = i == (playerSize - 1);
std::vector<std::shared_ptr<Action>> actions{};
for (int n = 0; n < numActionSize; n++) {
std::string actionName;
std::vector<int32_t> actionArray;
auto nStr = n * numActionStride;
auto offset = (int32_t*)stepArrayInfo.ptr + pStr + nStr;
spdlog::debug("Player {0} action {1} offset {2}", p, n, pStr + nStr);
switch (actionSize) {
case 1:
actionName = externalActionNames.at(0);
actionArray.push_back(*(offset + 0 * actionArrayStride));
break;
case 2:
actionName = externalActionNames.at(*(offset + 0 * actionArrayStride));
actionArray.push_back(*(offset + 1 * actionArrayStride));
break;
case 3:
actionName = externalActionNames.at(0);
actionArray.push_back(*(offset + 0 * actionArrayStride));
actionArray.push_back(*(offset + 1 * actionArrayStride));
actionArray.push_back(*(offset + 2 * actionArrayStride));
break;
case 4:
actionArray.push_back(*(offset + 0 * actionArrayStride));
actionArray.push_back(*(offset + 1 * actionArrayStride));
actionName = externalActionNames.at(*(offset + 2 * actionArrayStride));
actionArray.push_back(*(offset + 3 * actionArrayStride));
break;
default: {
auto error = fmt::format("Invalid action size, {0}", actionSize);
spdlog::error(error);
throw std::invalid_argument(error);
}
}
spdlog::debug("Creating action for player {0} with name {1}", p, actionName);
auto action = buildAction(players_[p]->unwrapped(), actionName, actionArray);
if (action != nullptr) {
actions.push_back(action);
}
}
auto actionResult = players_[p]->performActions(actions, lastPlayer);
terminated = actionResult.terminated;
truncated = actionResult.truncated;
if (lastPlayer) {
spdlog::debug("Last player, updating ticks");
auto info_and_truncated = buildInfo(actionResult);
info = info_and_truncated.info;
truncated = info_and_truncated.truncated;
}
}
for (int p = 0; p < playerSize; p++) {
playerRewards.push_back(gameProcess_->getAccumulatedRewards(p + 1));
}
return py::make_tuple(playerRewards, terminated, truncated, info);
}
std::array<uint32_t, 2> getTileSize() const {
auto vulkanObserver = std::dynamic_pointer_cast<VulkanObserver>(gameProcess_->getObserver());
if (vulkanObserver == nullptr) {
return {0, 0};
} else {
auto tileSize = vulkanObserver->getTileSize();
return {(uint32_t)tileSize[0], (uint32_t)tileSize[1]};
}
}
void enableHistory(bool enable) {
gameProcess_->getGrid()->enableHistory(enable);
}
uint32_t getWidth() const {
return gameProcess_->getGrid()->getWidth();
}
uint32_t getHeight() const {
return gameProcess_->getGrid()->getHeight();
}
// force release of resources for vulkan etc
void release() {
gameProcess_->release();
}
std::shared_ptr<Py_GameProcess> clone() {
auto clonedGameProcess = gameProcess_->clone();
auto clonedPyGameProcessWrapper = std::make_shared<Py_GameProcess>(Py_GameProcess(gdyFactory_, clonedGameProcess));
return clonedPyGameProcessWrapper;
}
std::shared_ptr<Py_GameProcess> loadState(py::dict py_state) {
const auto& stateMapping = gdyFactory_->getObjectGenerator()->getStateMapping();
GameState gameState;
gameState.tickCount = py_state["GameTicks"].cast<int32_t>();
gameState.grid.height = py_state["Grid"]["Height"].cast<uint32_t>();
gameState.grid.width = py_state["Grid"]["Width"].cast<uint32_t>();
gameState.playerCount = py_state["PlayerCount"].cast<uint32_t>();
// convert global variables
py::dict py_globalVariables = py_state["GlobalVariables"].cast<py::dict>();
gameState.globalData.resize(py_globalVariables.size());
for (const auto& py_globalVariable : py_globalVariables) {
const auto variableIndex = stateMapping.globalVariableNameToIdx.at(py_globalVariable.first.cast<std::string>());
gameState.globalData[variableIndex] = py_globalVariable.second.cast<std::vector<int32_t>>();
}
// convert objects
py::list py_objects = py_state["Objects"].cast<py::list>();
gameState.objectData.resize(py_objects.size());
spdlog::debug("Loading {0} objects", py_objects.size());
// TODO: Assuming the order of the objects here is consistent with the indexes in the delayed actions...
// might have to use ids here instead maybe to make it order independent?
for (uint32_t o = 0; o < py_objects.size(); o++) {
const auto& py_objectHandle = py_objects[o];
GameObjectData gameObjectData;
auto py_object = py_objectHandle.cast<py::dict>();
gameObjectData.name = py_object["Name"].cast<std::string>();
spdlog::debug("Loading object and variables for {0}", gameObjectData.name);
auto py_location = py_object["Location"].cast<std::vector<int32_t>>();
const auto py_orientation = DiscreteOrientation::fromString(py_object["Orientation"].cast<std::string>());
const auto variableIndex = stateMapping.objectVariableNameToIdx.at(gameObjectData.name);
spdlog::debug("Loading {0} object variables", variableIndex.size());
gameObjectData.variables.resize(variableIndex.size());
gameObjectData.variables[GameStateMapping::xIdx] = py_location[0];
gameObjectData.variables[GameStateMapping::yIdx] = py_location[1];
gameObjectData.variables[GameStateMapping::dxIdx] = py_orientation[0];
gameObjectData.variables[GameStateMapping::dyIdx] = py_orientation[1];
gameObjectData.variables[GameStateMapping::playerIdIdx] = py_object["PlayerId"].cast<int32_t>();
gameObjectData.variables[GameStateMapping::renderTileIdIdx] = py_object["RenderTileId"].cast<int32_t>();
auto py_variables = py_object["Variables"].cast<py::dict>();
spdlog::debug("Loading {0} custom object variables", py_variables.size());
for (const auto& variable : py_variables) {
gameObjectData.setVariableValue(variableIndex, variable.first.cast<std::string>(), variable.second.cast<int32_t>());
}
gameState.objectData[o] = gameObjectData;
}
// convert delayed actions
py::list py_delayedActions = py_state["DelayedActions"].cast<py::list>();
for (const auto& py_delayedActionData : py_delayedActions) {
DelayedActionData delayedActionData;
delayedActionData.priority = py_delayedActionData["Priority"].cast<uint32_t>();
delayedActionData.playerId = py_delayedActionData["PlayerId"].cast<uint32_t>();
delayedActionData.sourceObjectIdx = py_delayedActionData["SourceObjectIdx"].cast<uint32_t>();
delayedActionData.actionName = py_delayedActionData["ActionName"].cast<std::string>();
delayedActionData.originatingPlayerId = py_delayedActionData["OriginatingPlayerId"].cast<uint32_t>();
auto py_vectorToDest = py_delayedActionData["VectorToDest"].cast<std::vector<int32_t>>();
auto py_originatingVector = py_delayedActionData["Orientation"].cast<std::vector<int32_t>>();
delayedActionData.vectorToDest = glm::ivec2(py_vectorToDest[0], py_vectorToDest[1]);
delayedActionData.orientationVector = glm::ivec2(py_originatingVector[0], py_originatingVector[1]);
gameState.delayedActionData.push_back(delayedActionData);
}
auto loadedGameProcess = gameProcess_->fromGameState(gameState);
return std::make_shared<Py_GameProcess>(Py_GameProcess(gdyFactory_, loadedGameProcess));
}
py::dict getState() const {
py::dict py_state;
const auto& gameState = gameProcess_->getGameState();
const auto& stateMapping = gdyFactory_->getObjectGenerator()->getStateMapping();
py_state["GameTicks"] = gameState.tickCount;
py_state["Hash"] = gameState.hash;
py_state["PlayerCount"] = gameState.playerCount;
py::dict py_grid;
py_grid["Width"] = gameProcess_->getGrid()->getWidth();
py_grid["Height"] = gameProcess_->getGrid()->getHeight();
py_state["Grid"] = py_grid;
py::dict py_globalVariables;
for (auto varIdxIt : stateMapping.globalVariableNameToIdx) {
py_globalVariables[varIdxIt.first.c_str()] = gameState.globalData[varIdxIt.second];
}
py_state["GlobalVariables"] = py_globalVariables;
py::list py_objects;
for (const auto& gameObjectData : gameState.objectData) {
const auto& variableIndexes = gameObjectData.getVariableIndexes(stateMapping);
py::dict py_objectInfo;
py::dict py_objectVariables;
for (const auto& varIdxIt : variableIndexes) {
if (varIdxIt.first[0] != '_') {
py_objectVariables[varIdxIt.first.c_str()] = gameObjectData.variables[varIdxIt.second];
}
}
py_objectInfo["Name"] = gameObjectData.name;
const auto& location = gameObjectData.getLocation(variableIndexes);
py_objectInfo["Location"] = py::cast(std::vector<int32_t>{location.x, location.y});
py_objectInfo["Orientation"] = gameObjectData.getOrientation(variableIndexes).getName();
py_objectInfo["PlayerId"] = gameObjectData.variables[GameStateMapping::playerIdIdx];
py_objectInfo["RenderTileId"] = gameObjectData.variables[GameStateMapping::renderTileIdIdx];
py_objectInfo["Variables"] = py_objectVariables;
py_objects.append(py_objectInfo);
}
py_state["Objects"] = py_objects;
py::list py_delayed_actions;
for (const auto& delayedActionData : gameState.delayedActionData) {
py::dict py_delayedActionInfo;
py_delayedActionInfo["Priority"] = delayedActionData.priority;
py_delayedActionInfo["PlayerId"] = delayedActionData.playerId;
py_delayedActionInfo["SourceObjectIdx"] = delayedActionData.sourceObjectIdx;
py_delayedActionInfo["ActionName"] = delayedActionData.actionName;
py_delayedActionInfo["VectorToDest"] = py::cast(std::vector<int32_t>{delayedActionData.vectorToDest.x, delayedActionData.vectorToDest.y});
py_delayedActionInfo["Orientation"] = py::cast(std::vector<int32_t>{delayedActionData.orientationVector.x, delayedActionData.orientationVector.y});
py_delayedActionInfo["OriginatingPlayerId"] = delayedActionData.originatingPlayerId;
py_delayed_actions.append(py_delayedActionInfo);
}
py_state["DelayedActions"] = py_delayed_actions;
return py_state;
}
std::vector<std::string> getGlobalVariableNames() const {
std::vector<std::string> globalVariableNames;
auto globalVariables = gameProcess_->getGrid()->getGlobalVariables();
for (auto globalVariableIt : globalVariables) {
globalVariableNames.push_back(globalVariableIt.first);
}
return globalVariableNames;
}
py::dict getObjectVariableMap() const {
return py::cast(gameProcess_->getGrid()->getObjectVariableMap());
}
py::dict getGlobalVariables(std::vector<std::string> variables) const {
py::dict py_globalVariables;
auto globalVariables = gameProcess_->getGrid()->getGlobalVariables();
for (auto variableNameIt : variables) {
std::unordered_map<int32_t, int32_t> resolvedGlobalVariableMap;
auto globalVariableMap = globalVariables[variableNameIt];
for (auto playerVariableIt : globalVariableMap) {
resolvedGlobalVariableMap.insert({playerVariableIt.first, *playerVariableIt.second});
}
py_globalVariables[variableNameIt.c_str()] = resolvedGlobalVariableMap;
}
return py_globalVariables;
}
std::vector<py::dict> getHistory(bool purge) const {
auto history = gameProcess_->getGrid()->getHistory();
std::vector<py::dict> py_events;
if (history.size() > 0) {
for (const auto& historyEvent : history) {
py::dict py_event;
py::dict rewards;
for (auto& reward : historyEvent.rewards) {
rewards[py::cast(reward.first)] = reward.second;
}
py_event["PlayerId"] = historyEvent.playerId;
py_event["ActionName"] = historyEvent.actionName;
py_event["Tick"] = historyEvent.tick;
py_event["Rewards"] = rewards;
py_event["Delay"] = historyEvent.delay;
py_event["SourceObjectName"] = historyEvent.sourceObjectName;
py_event["DestinationObjectName"] = historyEvent.destObjectName;
py_event["SourceObjectPlayerId"] = historyEvent.sourceObjectPlayerId;
py_event["DestinationObjectPlayerId"] = historyEvent.destinationObjectPlayerId;
py_event["SourceLocation"] = std::array<uint32_t, 2>{(uint32_t)historyEvent.sourceLocation.x, (uint32_t)historyEvent.sourceLocation.y};
py_event["DestinationLocation"] = std::array<uint32_t, 2>{(uint32_t)historyEvent.destLocation.x, (uint32_t)historyEvent.destLocation.y};
py_events.push_back(py_event);
}
if (purge) {
gameProcess_->getGrid()->purgeHistory();
}
}
return py_events;
}
std::vector<std::string> getObjectNames() {
return gameProcess_->getGrid()->getObjectNames();
}
std::vector<std::string> getObjectVariableNames() {
return gameProcess_->getGrid()->getAllObjectVariableNames();
}
void seedRandomGenerator(uint32_t seed) {
gameProcess_->seedRandomGenerator(seed);
}
private:
std::shared_ptr<TurnBasedGameProcess> gameProcess_;
const std::shared_ptr<GDYFactory> gdyFactory_;
uint32_t playerCount_ = 0;
std::vector<std::shared_ptr<Py_Player>> players_;
InfoAndTruncated buildInfo(ActionResult actionResult) {
py::dict py_info;
bool truncated = false;
if (actionResult.terminated) {
py::dict py_playerResults;
for (auto playerRes : actionResult.playerStates) {
std::string playerStatusString;
switch (playerRes.second) {
case TerminationState::WIN:
playerStatusString = "Win";
break;
case TerminationState::LOSE:
playerStatusString = "Lose";
break;
case TerminationState::NONE:
playerStatusString = "End";
break;
case TerminationState::TRUNCATED:
truncated = true;
playerStatusString = "Truncated";
break;
}
if (playerStatusString.size() > 0) {
py_playerResults[std::to_string(playerRes.first).c_str()] = playerStatusString;
}
}
py_info["PlayerResults"] = py_playerResults;
}
return {py_info, truncated};
}
std::shared_ptr<Action> buildAction(std::shared_ptr<Player> player, std::string actionName, std::vector<int32_t> actionArray) {
const auto& actionInputsDefinition = gdyFactory_->findActionInputsDefinition(actionName);
auto playerAvatar = player->getAvatar();
auto playerId = player->getId();
const auto& inputMappings = actionInputsDefinition.inputMappings;
if (playerAvatar != nullptr) {
auto actionId = actionArray[0];
if (inputMappings.find(actionId) == inputMappings.end()) {
return nullptr;
}
const auto& mapping = inputMappings.at(actionId);
const auto& vectorToDest = mapping.vectorToDest;
const auto& orientationVector = mapping.orientationVector;
const auto& metaData = mapping.metaData;
const auto& action = std::make_shared<Action>(Action(gameProcess_->getGrid(), actionName, playerId, 0, metaData));
action->init(playerAvatar, vectorToDest, orientationVector, actionInputsDefinition.relative);
return action;
} else {
glm::ivec2 sourceLocation = {actionArray[0], actionArray[1]};
auto actionId = actionArray[2];
if (inputMappings.find(actionId) == inputMappings.end()) {
return nullptr;
}
const auto& mapping = inputMappings.at(actionId);
const auto& vector = mapping.vectorToDest;
const auto& orientationVector = mapping.orientationVector;
const auto& metaData = mapping.metaData;
glm::ivec2 destinationLocation = sourceLocation + vector;
auto action = std::make_shared<Action>(Action(gameProcess_->getGrid(), actionName, playerId, 0, metaData));
action->init(sourceLocation, destinationLocation);
return action;
}
}
};
} // namespace griddly | 412 | 0.744851 | 1 | 0.744851 | game-dev | MEDIA | 0.939826 | game-dev | 0.894105 | 1 | 0.894105 |
DanceManiac/Advanced-X-Ray-Public | 5,307 | SourcesAXR/xrGame/ai/monsters/control_path_builder_base.h | #pragma once
#include "ai_monster_defs.h"
#include "control_combase.h"
#include "../../movement_manager_space.h"
class CMotionStats;
class CCoverEvaluatorCloseToEnemy;
class CControlPathBuilderBase : public CControl_ComBase {
typedef CControl_ComBase inherited;
// -----------------------------------------------------------
// external setup
bool m_try_min_time;
bool m_enable;
bool m_use_dest_orient;
Fvector m_dest_dir;
MovementManager::EPathType m_path_type;
bool m_extrapolate;
u32 m_velocity_mask;
u32 m_desirable_mask;
bool m_reset_actuality;
u32 m_game_graph_target_vertex;
// -----------------------------------------------------------
// build path members
// -----------------------------------------------------------
class STarget {
Fvector _position;
u32 _node;
public:
STarget()
{
_position.set( -FLT_MAX, -FLT_MAX, -FLT_MAX );
_node =u32(-1);
}
void init () {
_position.set (0.f,0.f,0.f);
_node = u32(-1);
}
void set (const Fvector &pos, u32 vertex) {
_position.set (pos);
_node = vertex;
}
IC const Fvector &position ()const { return _position; }
//IC Fvector &position () { return _position; }
IC u32 node ()const { return _node; }
IC void set_node ( u32 node_ ) { _node = node_ ; }
IC void set_position( const Fvector &p ){ _position.set(p); }
} m_target_set, m_target_found;
u32 m_time; //
u32 m_last_time_target_set;
float m_distance_to_path_end;
bool m_failed;
u32 m_last_time_dir_set;
bool m_target_actual; //
struct {
bool use_covers;
float min_dist;
float max_dist;
float deviation;
float radius;
} m_cover_info;
enum {
eMoveToTarget,
eRetreatFromTarget,
} m_target_type;
CCoverEvaluatorCloseToEnemy *m_cover_approach;
// -----------------------------------------------------------
enum {
eStatePathValid = u32(1) << 0,
eStateWaitNewPath = u32(1) << 1,
eStatePathEnd = u32(1) << 2,
eStateNoPath = u32(1) << 3,
eStatePathFailed = u32(1) << 4
};
u32 m_state;
bool m_path_end;
// , path_builder
u32 m_time_global_failed_started;
u32 m_time_path_updated_external;
public:
CControlPathBuilderBase ();
virtual ~CControlPathBuilderBase ();
// -------------------------------------------------------------------
// Control Interface
virtual void reinit ();
virtual void update_frame ();
virtual void on_event (ControlCom::EEventType, ControlCom::IEventData*);
virtual void on_start_control (ControlCom::EControlType type);
virtual void on_stop_control (ControlCom::EControlType type);
// -------------------------------------------------------------------
void pre_update ();
// -------------------------------------------------------------------
IC void set_try_min_time (bool new_val) {m_try_min_time = new_val;}
IC void set_use_dest_orient (bool new_val) {m_use_dest_orient = new_val;}
IC void disable_path () {m_enable = false;}
IC void enable_path () {m_enable = true;}
IC void extrapolate_path (bool val) {m_extrapolate = val;}
IC void set_level_path_type () {m_path_type = MovementManager::ePathTypeLevelPath;}
IC void set_game_path_type () {m_path_type = MovementManager::ePathTypeGamePath;}
IC void set_patrol_path_type () {m_path_type = MovementManager::ePathTypePatrolPath;}
IC void set_velocity_mask (u32 mask) {m_velocity_mask = mask;}
IC void set_desirable_mask (u32 mask) {m_desirable_mask = mask;}
void set_dest_direction (const Fvector &dir);
IC bool enabled () {return m_enable;}
// -------------------------------------------------------------------
// Set methods
void set_target_point (const Fvector &position, u32 node = u32(-1));
void set_target_point (u32 node);
void set_retreat_from_point (const Fvector &position);
IC void set_rebuild_time (u32 time);
IC void set_cover_params (float min, float max, float dev, float radius);
IC void set_use_covers (bool val = true);
IC void set_distance_to_end (float dist);
void prepare_builder ();
void detour_graph_points (u32 game_graph_vertex_id = u32(-1));
IC void set_generic_parameters ();
bool is_target_actual () const {return m_target_actual;}
Fvector get_target_found () {return m_target_found.position();}
u32 get_target_found_node () const {return m_target_found.node();}
Fvector get_target_set () {return m_target_set.position();}
// -------------------------------------------------------------------
// Services
void set_target_accessible (STarget &target, const Fvector &position);
private:
// functional
void update_path_builder_state ();
void update_target_point ();
void check_failure ();
bool target_point_need_update ();
void find_target_point_set ();
void find_target_point_failed ();
void select_target (); //
void set_path_builder_params (); // set params to control
void reset ();
void travel_point_changed ();
void on_path_built ();
void on_path_end ();
void on_path_updated ();
// ,
void find_node ();
bool global_failed ();
};
#include "control_path_builder_base_inline.h"
| 412 | 0.93703 | 1 | 0.93703 | game-dev | MEDIA | 0.834213 | game-dev | 0.699295 | 1 | 0.699295 |
libgdx/libgdx | 2,565 | extensions/gdx-bullet/jni/swig-src/collision/com/badlogic/gdx/physics/bullet/collision/btSortedOverlappingPairCache.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.linearmath.*;
public class btSortedOverlappingPairCache extends btOverlappingPairCache {
private long swigCPtr;
protected btSortedOverlappingPairCache (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.btSortedOverlappingPairCache_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btSortedOverlappingPairCache, normally you should not need this constructor it's intended for low-level
* usage. */
public btSortedOverlappingPairCache (long cPtr, boolean cMemoryOwn) {
this("btSortedOverlappingPairCache", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.btSortedOverlappingPairCache_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (btSortedOverlappingPairCache obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btSortedOverlappingPairCache(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public btSortedOverlappingPairCache () {
this(CollisionJNI.new_btSortedOverlappingPairCache(), true);
}
public boolean needsBroadphaseCollision (btBroadphaseProxy proxy0, btBroadphaseProxy proxy1) {
return CollisionJNI.btSortedOverlappingPairCache_needsBroadphaseCollision(swigCPtr, this, btBroadphaseProxy.getCPtr(proxy0),
proxy0, btBroadphaseProxy.getCPtr(proxy1), proxy1);
}
public btBroadphasePairArray getOverlappingPairArrayConst () {
return new btBroadphasePairArray(CollisionJNI.btSortedOverlappingPairCache_getOverlappingPairArrayConst(swigCPtr, this),
false);
}
public btOverlapFilterCallback getOverlapFilterCallback () {
long cPtr = CollisionJNI.btSortedOverlappingPairCache_getOverlapFilterCallback(swigCPtr, this);
return (cPtr == 0) ? null : new btOverlapFilterCallback(cPtr, false);
}
}
| 412 | 0.943992 | 1 | 0.943992 | game-dev | MEDIA | 0.330752 | game-dev | 0.953863 | 1 | 0.953863 |
HellFirePvP/AstralSorcery | 5,350 | src/main/java/hellfirepvp/astralsorcery/datagen/data/recipes/builder/ResultCookingRecipeBuilder.java | /*******************************************************************************
* HellFirePvP / Astral Sorcery 2022
*
* All rights reserved.
* The source code is available on github: https://github.com/HellFirePvP/AstralSorcery
* For further details, see the License file there.
******************************************************************************/
package hellfirepvp.astralsorcery.datagen.data.recipes.builder;
import com.google.gson.JsonObject;
import net.minecraft.data.IFinishedRecipe;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.AbstractCookingRecipe;
import net.minecraft.item.crafting.CookingRecipeSerializer;
import net.minecraft.item.crafting.IRecipeSerializer;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.registries.ForgeRegistries;
import javax.annotation.Nullable;
import java.util.function.Consumer;
/**
* This class is part of the Astral Sorcery Mod
* The complete source code for this mod can be found on github.
* Class: ResultCookingRecipeBuilder
* Created by HellFirePvP
* Date: 07.03.2020 / 08:11
*/
//ItemStack (item + count) result sensitive version...
public class ResultCookingRecipeBuilder {
private final ItemStack result;
private final Ingredient ingredient;
private final float experience;
private final int cookingTime;
private final CookingRecipeSerializer<?> recipeSerializer;
private ResultCookingRecipeBuilder(ItemStack result, Ingredient ingredientIn, float experienceIn, int cookingTimeIn, CookingRecipeSerializer<?> serializer) {
this.result = result.copy();
this.ingredient = ingredientIn;
this.experience = experienceIn;
this.cookingTime = cookingTimeIn;
this.recipeSerializer = serializer;
}
public static ResultCookingRecipeBuilder cookingRecipe(Ingredient ingredientIn, ItemStack result, float experienceIn, int cookingTimeIn, CookingRecipeSerializer<?> serializer) {
return new ResultCookingRecipeBuilder(result, ingredientIn, experienceIn, cookingTimeIn, serializer);
}
public static ResultCookingRecipeBuilder blastingRecipe(Ingredient ingredientIn, ItemStack result, float experienceIn, int cookingTimeIn) {
return cookingRecipe(ingredientIn, result, experienceIn, cookingTimeIn, IRecipeSerializer.BLASTING);
}
public static ResultCookingRecipeBuilder smeltingRecipe(Ingredient ingredientIn, ItemStack result, float experienceIn, int cookingTimeIn) {
return cookingRecipe(ingredientIn, result, experienceIn, cookingTimeIn, IRecipeSerializer.SMELTING);
}
public void build(Consumer<IFinishedRecipe> consumerIn) {
this.build(consumerIn, ForgeRegistries.ITEMS.getKey(this.result.getItem()));
}
public void build(Consumer<IFinishedRecipe> consumerIn, String save) {
ResourceLocation itemKey = ForgeRegistries.ITEMS.getKey(this.result.getItem());
ResourceLocation saveNameKey = new ResourceLocation(save);
if (saveNameKey.equals(itemKey)) {
throw new IllegalStateException("Recipe " + saveNameKey + " should remove its 'save' argument");
} else {
this.build(consumerIn, saveNameKey);
}
}
public void build(Consumer<IFinishedRecipe> consumerIn, ResourceLocation id) {
id = new ResourceLocation(id.getNamespace(), this.recipeSerializer.getRegistryName().getPath() + "/" + id.getPath());
consumerIn.accept(new Result(id, this.ingredient, this.result, this.experience, this.cookingTime, this.recipeSerializer));
}
public static class Result implements IFinishedRecipe {
private final ResourceLocation id;
private final Ingredient ingredient;
private final ItemStack result;
private final float experience;
private final int cookingTime;
private final IRecipeSerializer<? extends AbstractCookingRecipe> serializer;
public Result(ResourceLocation idIn, Ingredient ingredientIn, ItemStack resultIn, float experienceIn, int cookingTimeIn, IRecipeSerializer<? extends AbstractCookingRecipe> serializerIn) {
this.id = idIn;
this.ingredient = ingredientIn;
this.result = resultIn;
this.experience = experienceIn;
this.cookingTime = cookingTimeIn;
this.serializer = serializerIn;
}
public void serialize(JsonObject json) {
JsonObject itemResult = new JsonObject();
itemResult.addProperty("item", this.result.getItem().getRegistryName().toString());
itemResult.addProperty("count", this.result.getCount());
json.add("ingredient", this.ingredient.serialize());
json.add("result", itemResult);
json.addProperty("experience", this.experience);
json.addProperty("cookingtime", this.cookingTime);
}
public IRecipeSerializer<?> getSerializer() {
return this.serializer;
}
public ResourceLocation getID() {
return this.id;
}
@Nullable
public JsonObject getAdvancementJson() {
return null;
}
@Nullable
public ResourceLocation getAdvancementID() {
return new ResourceLocation("");
}
}
}
| 412 | 0.892374 | 1 | 0.892374 | game-dev | MEDIA | 0.965508 | game-dev | 0.854288 | 1 | 0.854288 |
LiteLDev/LeviLamina | 1,027 | src-server/mc/scripting/modules/minecraft/options/ScriptActorApplyDamageOptions.h | #pragma once
#include "mc/_HeaderOutputPredefine.h"
// auto generated forward declare list
// clang-format off
namespace Scripting { struct InterfaceBinding; }
// clang-format on
namespace ScriptModuleMinecraft {
struct ScriptActorApplyDamageOptions {
public:
// member variables
// NOLINTBEGIN
::ll::UntypedStorage<4, 4> mUnk232874;
::ll::UntypedStorage<8, 40> mUnkbfc0ea;
// NOLINTEND
public:
// prevent constructor by default
ScriptActorApplyDamageOptions& operator=(ScriptActorApplyDamageOptions const&);
ScriptActorApplyDamageOptions(ScriptActorApplyDamageOptions const&);
ScriptActorApplyDamageOptions();
public:
// member functions
// NOLINTBEGIN
MCNAPI ~ScriptActorApplyDamageOptions();
// NOLINTEND
public:
// static functions
// NOLINTBEGIN
MCNAPI static ::Scripting::InterfaceBinding bind();
// NOLINTEND
public:
// destructor thunk
// NOLINTBEGIN
MCNAPI void $dtor();
// NOLINTEND
};
} // namespace ScriptModuleMinecraft
| 412 | 0.637094 | 1 | 0.637094 | game-dev | MEDIA | 0.485729 | game-dev | 0.518429 | 1 | 0.518429 |
comet-ml/kangas | 3,848 | backend/kangas/datatypes/base.py | # -*- coding: utf-8 -*-
######################################################
# _____ _____ _ _ #
# (____ \ _ | ___) (_) | | #
# _ \ \ ____| |_ ____| | ___ ___ _ _ | | #
# | | | )/ _ | _)/ _ | |(_ / __) |/ || | #
# | |__/ ( ( | | | ( ( | | |__| | | | ( (_| | #
# |_____/ \_||_|___)\_||_|_____/|_| |_|\____| #
# #
# Copyright (c) 2023-2024 Kangas Development Team #
# All rights reserved #
######################################################
import json
from .utils import generate_guid
class Asset:
"""
The base class for any object that needs to be logged.
"""
ASSET_TYPE = "Asset"
def __init__(self, source=None):
"""
NOTE: each subclass will generate and cache metadata.
"""
self._unserialize = None
self.asset_id = generate_guid()
self.asset_data = None
self.metadata = {"assetId": self.asset_id}
self.source = None
if source is not None:
# FIXME: check to make sure that source should be http, https, or file
self.source = source
self.asset_data = json.dumps({"source": self.source})
self.metadata["source"] = source
@property
def asset_id(self):
self.deserialize()
return self._asset_id
@asset_id.setter
def asset_id(self, asset_id):
self._asset_id = asset_id
@property
def asset_data(self):
self.deserialize()
return self._asset_data
@asset_data.setter
def asset_data(self, asset_data):
self._asset_data = asset_data
def deserialize(self, get_remote_source=True):
"""
Deserialize if needed.
"""
if self._unserialize:
self._unserialize(self, get_remote_source)
self._unserialize = None
return self
def log_and_serialize(self, datagrid, row_id):
"""
Log and serialize an asset.
NOTE: will only log an asset once in each datagrid db.
"""
datagrid._log(
self.asset_id, self.ASSET_TYPE, self.asset_data, self.metadata, row_id
)
return self.asset_id
@classmethod
def get_statistics(cls, datagrid, column_name, field_name):
pass
@classmethod
def unserialize(cls, datagrid, row, column_name):
asset_id = row[column_name]
def _unserialize(obj, get_remote_asset=True):
row = datagrid.conn.execute(
"""SELECT asset_data, asset_metadata,
json_extract(asset_metadata, "$.source") as asset_source
from assets WHERE asset_id = ?""",
[asset_id],
).fetchone()
if row:
asset_data, asset_metadata, asset_source = row
if asset_source:
if get_remote_asset:
obj.asset_data = obj._get_asset_data_from_source(asset_source)
obj.metadata = json.loads(asset_metadata)
obj.source = asset_source
else:
obj.asset_data = asset_data
obj.metadata = json.loads(asset_metadata)
obj = cls(unserialize=_unserialize)
obj.asset_id = asset_id
return obj
def _get_asset_data_from_source(self, asset_source):
# Add this method in asset class
raise NotImplementedError("This asset subclass needs to implement this method")
def _log_metadata(self, **metadata):
"""
Log the metadata.
"""
self.metadata.update(metadata)
def __repr__(self):
return "<%s, asset_id=%r>" % (self.ASSET_TYPE, self.asset_id)
| 412 | 0.691203 | 1 | 0.691203 | game-dev | MEDIA | 0.567318 | game-dev | 0.790191 | 1 | 0.790191 |
mcclure/bitbucket-backup | 4,818 | repos/impression/contents/desktop/static_lib/cpBody.cpp | /* Copyright (c) 2007 Scott Lembcke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdlib.h>
#include <float.h>
#include <stdarg.h>
#include "chipmunk_private.h"
// initialized in cpInitChipmunk()
cpBody cpStaticBodySingleton;
cpBody*
cpBodyAlloc(void)
{
return (cpBody *)cpmalloc(sizeof(cpBody));
}
cpBodyVelocityFunc cpBodyUpdateVelocityDefault = cpBodyUpdateVelocity;
cpBodyPositionFunc cpBodyUpdatePositionDefault = cpBodyUpdatePosition;
cpBody*
cpBodyInit(cpBody *body, cpFloat m, cpFloat i)
{
body->velocity_func = cpBodyUpdateVelocityDefault;
body->position_func = cpBodyUpdatePositionDefault;
cpBodySetMass(body, m);
cpBodySetMoment(body, i);
body->p = cpvzero;
body->v = cpvzero;
body->f = cpvzero;
cpBodySetAngle(body, 0.0f);
body->w = 0.0f;
body->t = 0.0f;
body->v_bias = cpvzero;
body->w_bias = 0.0f;
body->data = NULL;
body->v_limit = (cpFloat)INFINITY;
body->w_limit = (cpFloat)INFINITY;
body->space = NULL;
body->shapesList = NULL;
cpComponentNode node = {NULL, NULL, 0, 0.0f};
body->node = node;
return body;
}
cpBody*
cpBodyNew(cpFloat m, cpFloat i)
{
return cpBodyInit(cpBodyAlloc(), m, i);
}
cpBody *
cpBodyInitStatic(cpBody *body)
{
cpBodyInit(body, (cpFloat)INFINITY, (cpFloat)INFINITY);
body->node.idleTime = (cpFloat)INFINITY;
return body;
}
cpBody *
cpBodyNewStatic()
{
return cpBodyInitStatic(cpBodyAlloc());
}
void cpBodyDestroy(cpBody *body){}
void
cpBodyFree(cpBody *body)
{
if(body){
cpBodyDestroy(body);
cpfree(body);
}
}
void
cpBodySetMass(cpBody *body, cpFloat mass)
{
body->m = mass;
body->m_inv = 1.0f/mass;
}
void
cpBodySetMoment(cpBody *body, cpFloat moment)
{
body->i = moment;
body->i_inv = 1.0f/moment;
}
void
cpBodySetAngle(cpBody *body, cpFloat angle)
{
body->a = angle;//fmod(a, (cpFloat)M_PI*2.0f);
body->rot = cpvforangle(angle);
}
void
cpBodySlew(cpBody *body, cpVect pos, cpFloat dt)
{
cpVect delta = cpvsub(pos, body->p);
body->v = cpvmult(delta, 1.0f/dt);
}
void
cpBodyUpdateVelocity(cpBody *body, cpVect gravity, cpFloat damping, cpFloat dt)
{
body->v = cpvclamp(cpvadd(cpvmult(body->v, damping), cpvmult(cpvadd(gravity, cpvmult(body->f, body->m_inv)), dt)), body->v_limit);
cpFloat w_limit = body->w_limit;
body->w = cpfclamp(body->w*damping + body->t*body->i_inv*dt, -w_limit, w_limit);
}
void
cpBodyUpdatePosition(cpBody *body, cpFloat dt)
{
body->p = cpvadd(body->p, cpvmult(cpvadd(body->v, body->v_bias), dt));
cpBodySetAngle(body, body->a + (body->w + body->w_bias)*dt);
body->v_bias = cpvzero;
body->w_bias = 0.0f;
}
void
cpBodyResetForces(cpBody *body)
{
body->f = cpvzero;
body->t = 0.0f;
}
void
cpBodyApplyForce(cpBody *body, cpVect force, cpVect r)
{
body->f = cpvadd(body->f, force);
body->t += cpvcross(r, force);
}
void
cpApplyDampedSpring(cpBody *a, cpBody *b, cpVect anchr1, cpVect anchr2, cpFloat rlen, cpFloat k, cpFloat dmp, cpFloat dt)
{
// Calculate the world space anchor coordinates.
cpVect r1 = cpvrotate(anchr1, a->rot);
cpVect r2 = cpvrotate(anchr2, b->rot);
cpVect delta = cpvsub(cpvadd(b->p, r2), cpvadd(a->p, r1));
cpFloat dist = cpvlength(delta);
cpVect n = dist ? cpvmult(delta, 1.0f/dist) : cpvzero;
cpFloat f_spring = (dist - rlen)*k;
// Calculate the world relative velocities of the anchor points.
cpVect v1 = cpvadd(a->v, cpvmult(cpvperp(r1), a->w));
cpVect v2 = cpvadd(b->v, cpvmult(cpvperp(r2), b->w));
// Calculate the damping force.
// This really should be in the impulse solver and can produce problems when using large damping values.
cpFloat vrn = cpvdot(cpvsub(v2, v1), n);
cpFloat f_damp = vrn*cpfmin(dmp, 1.0f/(dt*(a->m_inv + b->m_inv)));
// Apply!
cpVect f = cpvmult(n, f_spring + f_damp);
cpBodyApplyForce(a, f, r1);
cpBodyApplyForce(b, cpvneg(f), r2);
}
| 412 | 0.573941 | 1 | 0.573941 | game-dev | MEDIA | 0.805793 | game-dev | 0.503327 | 1 | 0.503327 |
BeyondDimension/SteamTools | 7,572 | src/BD.WTTS.Client.Plugins.Accelerator/Services.Implementation/BackendAcceleratorServiceImpl.XunYou.cs | using System.Threading.Channels;
namespace BD.WTTS.Services.Implementation;
partial class BackendAcceleratorServiceImpl
{
XunYouState lastXunYouState = default;
int XunYouAccelStateCallback(XunYouState status, nint thisptr)
{
lastXunYouState = status;
XunYouAccelStateModel m;
switch (status)
{
case XunYouState.加速中:
case XunYouState.加速已完成:
case XunYouState.停止加速中:
m = GetXunYouAccelStateModel(status);
break;
default:
m = new XunYouAccelStateModel
{
State = status,
};
break;
}
#if DEBUG
static string? EnumToStringDebug<T>(T? value) where T : struct, Enum
{
if (value is null)
return null;
if (Enum.IsDefined(typeof(T), value))
{
return $"{value}({ConvertibleHelper.Convert<int, T>(value.Value)})";
}
return value.ToString();
}
Console.WriteLine($"迅游加速状态变更:{EnumToStringDebug((XunYouState?)m.State)}, {EnumToStringDebug(m.AccelState)}, GameId: {m.GameId}, AreaId: {m.AreaId}, ServerId: {m.ServerId}");
#endif
XunYouAccelStateToFrontendCallback(m);
return 0;
}
/*async*/
void XunYouAccelStateToFrontendCallback(XunYouAccelStateModel m)
{
if (disposedValue)
return;
try
{
// 通知前端
//var ipc = Ioc.Get<IPCSubProcessService>();
//var accelStateToFrontendCallback = ipc.GetService<IXunYouAccelStateToFrontendCallback>();
var accelStateToFrontendCallback = Ioc.Get<IXunYouAccelStateToFrontendCallback>();
accelStateToFrontendCallback.ThrowIsNull(nameof(accelStateToFrontendCallback)).XunYouAccelStateToFrontendCallback(m);
//await Plugin.IpcServer.HubContext.Clients.All.SendAsync(nameof(XunYouAccelStateModel), m);
}
catch (Exception ex)
{
Log.Error(nameof(BackendAcceleratorServiceImpl), ex, "XunYouAccelStateToFrontendCallback fail.");
}
}
static XunYouAccelStateModel GetXunYouAccelStateModel(XunYouState status)
{
var accState = XunYouSDK.GetAccelStateEx(out var gameid, out var areaid, out var serverid);
return new XunYouAccelStateModel
{
State = status,
AccelState = accState,
GameId = gameid,
AreaId = areaid,
ServerId = serverid,
};
}
/// <inheritdoc/>
public async Task<ApiRsp<bool>> XY_IsInstall(CancellationToken cancellationToken = default)
{
if (!XunYouSDK.IsSupported)
{
return ApiRspHelper.Ok(false);
}
var result = XunYouSDK.IsInstall();
await Task.CompletedTask;
return result;
}
/// <inheritdoc/>
public async Task<ApiRsp<XunYouUninstallCode>> XY_Uninstall(CancellationToken cancellationToken = default)
{
if (!XunYouSDK.IsSupported)
{
return ApiRspHelper.Ok(XunYouUninstallCode.卸载成功);
}
var result = XunYouSDK.Uninstall();
await Task.CompletedTask;
return result;
}
/// <inheritdoc/>
public async Task<ApiRsp<int>> XY_StartEx2(
string openid,
string nickname,
int gameid,
int area,
int server,
string? areaPath = default,
string? svrPath = default,
CancellationToken cancellationToken = default)
{
if (!XunYouSDK.IsSupported)
{
return ApiRspHelper.Ok(0);
}
var show = XunYouShowCommands.SW_HIDE;
var result = XunYouSDK.StartEx2(
openid,
nickname,
show,
gameid,
area,
server,
null,
default,
GameAcceleratorSettings.WattAcceleratorDirPath.Value!,
areaPath,
svrPath);
await Task.CompletedTask;
return result;
}
/// <inheritdoc/>
public async Task<ApiRsp<int>> XY_StartAccel(
int gameid,
int area,
int serverid = default,
string? areaName = default,
string? svrName = default,
CancellationToken cancellationToken = default)
{
if (!XunYouSDK.IsSupported)
{
return ApiRspHelper.Ok(0);
}
var result = XunYouSDK.StartAccel(
gameid,
area,
areaName,
serverid,
svrName);
await Task.CompletedTask;
return result == XunYouSendResultCode.发送失败 ? 300 : 101;
}
/// <inheritdoc/>
public async Task<ApiRsp<XunYouAccelStateModel?>> XY_GetAccelStateEx(CancellationToken cancellationToken = default)
{
if (!XunYouSDK.IsSupported)
{
return ApiRspHelper.Ok((XunYouAccelStateModel?)null);
}
var result = GetXunYouAccelStateModel(lastXunYouState);
await Task.CompletedTask;
return result;
}
/// <inheritdoc/>
public async IAsyncEnumerable<ApiRsp<int>> XY_Install(string installPath, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
if (!XunYouSDK.IsSupported)
{
yield break;
}
var channel = Channel.CreateUnbounded<int>();
int XunYouDownLoadCallback(int par, nint thisptr)
{
channel.Writer.TryWrite(par);
if (par > 100)
{
channel.Writer.Complete();
}
return 0;
}
var installPackPath = Plugin.Instance.CacheDirectory;
var result = XunYouSDK.Install(XunYouDownLoadCallback, default, installPath, installPackPath);
if (result == 101) // 成功
{
await foreach (var item in channel.Reader.ReadAllAsync(cancellationToken))
{
yield return item;
}
}
else
{
yield return result;
}
}
/// <inheritdoc/>
public async Task<ApiRsp<XunYouSendResultCode>> XY_StopAccel(CancellationToken cancellationToken = default)
{
if (!XunYouSDK.IsSupported)
{
return ApiRspHelper.Ok(XunYouSendResultCode.发送成功);
}
var result = XunYouSDK.Stop();
await Task.CompletedTask;
return result;
}
/// <inheritdoc/>
public async Task<ApiRsp<XunYouIsRunningCode>> XY_IsRunning(CancellationToken cancellationToken = default)
{
if (!XunYouSDK.IsSupported)
{
return ApiRspHelper.Ok(XunYouIsRunningCode.加速器未启动);
}
var result = XunYouSDK.IsRunning();
await Task.CompletedTask;
return result;
}
/// <inheritdoc/>
public async Task<ApiRsp<XunYouStartGameCode>> XY_StartGame(CancellationToken cancellationToken = default)
{
if (!XunYouSDK.IsSupported)
{
return ApiRspHelper.Ok(XunYouStartGameCode.失败);
}
var result = XunYouSDK.StartGame();
await Task.CompletedTask;
return result;
}
/// <inheritdoc/>
public async Task<ApiRsp<int>> XY_ShowWinodw(bool showHide, CancellationToken cancellationToken = default)
{
if (!XunYouSDK.IsSupported)
{
return ApiRspHelper.Ok(0);
}
XunYouSDK.xunyou_show(Convert.ToInt32(showHide));
await Task.CompletedTask;
return ApiRspHelper.Ok(0);
}
}
| 412 | 0.820478 | 1 | 0.820478 | game-dev | MEDIA | 0.298322 | game-dev | 0.824927 | 1 | 0.824927 |
liugaolian/gordon_cnn | 6,220 | include/armadillo_bits/fn_randg.hpp | // Copyright 2008-2016 Conrad Sanderson (http://conradsanderson.id.au)
// Copyright 2008-2016 National ICT Australia (NICTA)
//
// 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.
// ------------------------------------------------------------------------
//! \addtogroup fn_randg
//! @{
template<typename obj_type>
arma_warn_unused
inline
obj_type
randg(const uword n_rows, const uword n_cols, const distr_param& param = distr_param(), const typename arma_Mat_Col_Row_only<obj_type>::result* junk = 0)
{
arma_extra_debug_sigprint();
arma_ignore(junk);
#if defined(ARMA_USE_CXX11)
{
if(is_Col<obj_type>::value == true)
{
arma_debug_check( (n_cols != 1), "randg(): incompatible size" );
}
else
if(is_Row<obj_type>::value == true)
{
arma_debug_check( (n_rows != 1), "randg(): incompatible size" );
}
obj_type out(n_rows, n_cols);
double a;
double b;
if(param.state == 0)
{
a = double(1);
b = double(1);
}
else
if(param.state == 1)
{
a = double(param.a_int);
b = double(param.b_int);
}
else
{
a = param.a_double;
b = param.b_double;
}
arma_debug_check( ((a <= double(0)) || (b <= double(0))), "randg(): a and b must be greater than zero" );
#if defined(ARMA_USE_EXTERN_CXX11_RNG)
{
arma_rng_cxx11_instance.randg_fill(out.memptr(), out.n_elem, a, b);
}
#else
{
arma_rng_cxx11 local_arma_rng_cxx11_instance;
typedef typename arma_rng_cxx11::seed_type seed_type;
local_arma_rng_cxx11_instance.set_seed( seed_type(arma_rng::randi<seed_type>()) );
local_arma_rng_cxx11_instance.randg_fill(out.memptr(), out.n_elem, a, b);
}
#endif
return out;
}
#else
{
arma_ignore(n_rows);
arma_ignore(n_cols);
arma_ignore(param);
arma_stop_logic_error("randg(): C++11 compiler required");
return obj_type();
}
#endif
}
template<typename obj_type>
arma_warn_unused
inline
obj_type
randg(const SizeMat& s, const distr_param& param = distr_param(), const typename arma_Mat_Col_Row_only<obj_type>::result* junk = 0)
{
arma_extra_debug_sigprint();
arma_ignore(junk);
return randg<obj_type>(s.n_rows, s.n_cols, param);
}
template<typename obj_type>
arma_warn_unused
inline
obj_type
randg(const uword n_elem, const distr_param& param = distr_param(), const arma_empty_class junk1 = arma_empty_class(), const typename arma_Mat_Col_Row_only<obj_type>::result* junk2 = 0)
{
arma_extra_debug_sigprint();
arma_ignore(junk1);
arma_ignore(junk2);
if(is_Row<obj_type>::value == true)
{
return randg<obj_type>(1, n_elem, param);
}
else
{
return randg<obj_type>(n_elem, 1, param);
}
}
arma_warn_unused
inline
mat
randg(const uword n_rows, const uword n_cols, const distr_param& param = distr_param())
{
arma_extra_debug_sigprint();
return randg<mat>(n_rows, n_cols, param);
}
arma_warn_unused
inline
mat
randg(const SizeMat& s, const distr_param& param = distr_param())
{
arma_extra_debug_sigprint();
return randg<mat>(s.n_rows, s.n_cols, param);
}
arma_warn_unused
inline
vec
randg(const uword n_elem, const distr_param& param = distr_param())
{
arma_extra_debug_sigprint();
return randg<vec>(n_elem, param);
}
template<typename cube_type>
arma_warn_unused
inline
cube_type
randg(const uword n_rows, const uword n_cols, const uword n_slices, const distr_param& param = distr_param(), const typename arma_Cube_only<cube_type>::result* junk = 0)
{
arma_extra_debug_sigprint();
arma_ignore(junk);
#if defined(ARMA_USE_CXX11)
{
cube_type out(n_rows, n_cols, n_slices);
double a;
double b;
if(param.state == 0)
{
a = double(1);
b = double(1);
}
else
if(param.state == 1)
{
a = double(param.a_int);
b = double(param.b_int);
}
else
{
a = param.a_double;
b = param.b_double;
}
arma_debug_check( ((a <= double(0)) || (b <= double(0))), "randg(): a and b must be greater than zero" );
#if defined(ARMA_USE_EXTERN_CXX11_RNG)
{
arma_rng_cxx11_instance.randg_fill(out.memptr(), out.n_elem, a, b);
}
#else
{
arma_rng_cxx11 local_arma_rng_cxx11_instance;
typedef typename arma_rng_cxx11::seed_type seed_type;
local_arma_rng_cxx11_instance.set_seed( seed_type(arma_rng::randi<seed_type>()) );
local_arma_rng_cxx11_instance.randg_fill(out.memptr(), out.n_elem, a, b);
}
#endif
return out;
}
#else
{
arma_ignore(n_rows);
arma_ignore(n_cols);
arma_ignore(n_slices);
arma_ignore(param);
arma_stop_logic_error("randg(): C++11 compiler required");
return cube_type();
}
#endif
}
template<typename cube_type>
arma_warn_unused
inline
cube_type
randg(const SizeCube& s, const distr_param& param = distr_param(), const typename arma_Cube_only<cube_type>::result* junk = 0)
{
arma_extra_debug_sigprint();
arma_ignore(junk);
return randg<cube_type>(s.n_rows, s.n_cols, s.n_slices, param);
}
arma_warn_unused
inline
cube
randg(const uword n_rows, const uword n_cols, const uword n_slices, const distr_param& param = distr_param())
{
arma_extra_debug_sigprint();
return randg<cube>(n_rows, n_cols, n_slices, param);
}
arma_warn_unused
inline
cube
randg(const SizeCube& s, const distr_param& param = distr_param())
{
arma_extra_debug_sigprint();
return randg<cube>(s.n_rows, s.n_cols, s.n_slices, param);
}
//! @}
| 412 | 0.82625 | 1 | 0.82625 | game-dev | MEDIA | 0.429231 | game-dev | 0.646869 | 1 | 0.646869 |
hebohang/HEngine | 5,722 | Engine/Source/ThirdParty/bullet3/examples/SharedMemory/plugins/collisionFilterPlugin/collisionFilterPlugin.cpp |
//tinyRendererPlugin implements the TinyRenderer as a plugin
//it is statically linked when using preprocessor #define STATIC_LINK_VR_PLUGIN
//otherwise you can dynamically load it using pybullet.loadPlugin
#include "collisionFilterPlugin.h"
#include "../../SharedMemoryPublic.h"
#include "../b3PluginContext.h"
#include <stdio.h>
#include "Bullet3Common/b3HashMap.h"
#include "../b3PluginCollisionInterface.h"
struct b3CustomCollisionFilter
{
int m_objectUniqueIdA;
int m_linkIndexA;
int m_objectUniqueIdB;
int m_linkIndexB;
bool m_enableCollision;
B3_FORCE_INLINE unsigned int getHash() const
{
int obA = (m_objectUniqueIdA & 0xff);
int obB = ((m_objectUniqueIdB & 0xf) << 8);
int linkA = ((m_linkIndexA & 0xff) << 16);
int linkB = ((m_linkIndexB & 0xff) << 24);
long long int key = obA + obB + linkA + linkB;
// Thomas Wang's hash
key += ~(key << 15);
key ^= (key >> 10);
key += (key << 3);
key ^= (key >> 6);
key += ~(key << 11);
key ^= (key >> 16);
return (int) key;
}
bool equals(const b3CustomCollisionFilter& other) const
{
return m_objectUniqueIdA == other.m_objectUniqueIdA &&
m_objectUniqueIdB == other.m_objectUniqueIdB &&
m_linkIndexA == other.m_linkIndexA &&
m_linkIndexB == other.m_linkIndexB;
}
};
struct DefaultPluginCollisionInterface : public b3PluginCollisionInterface
{
b3HashMap<b3CustomCollisionFilter, b3CustomCollisionFilter> m_customCollisionFilters;
virtual void setBroadphaseCollisionFilter(
int objectUniqueIdA, int objectUniqueIdB,
int linkIndexA, int linkIndexB,
bool enableCollision)
{
b3CustomCollisionFilter keyValue;
keyValue.m_objectUniqueIdA = objectUniqueIdA;
keyValue.m_linkIndexA = linkIndexA;
keyValue.m_objectUniqueIdB = objectUniqueIdB;
keyValue.m_linkIndexB = linkIndexB;
keyValue.m_enableCollision = enableCollision;
if (objectUniqueIdA > objectUniqueIdB)
{
b3Swap(keyValue.m_objectUniqueIdA, keyValue.m_objectUniqueIdB);
b3Swap(keyValue.m_linkIndexA, keyValue.m_linkIndexB);
}
if (objectUniqueIdA == objectUniqueIdB)
{
if (keyValue.m_linkIndexA > keyValue.m_linkIndexB)
{
b3Swap(keyValue.m_linkIndexA, keyValue.m_linkIndexB);
}
}
m_customCollisionFilters.insert(keyValue, keyValue);
}
virtual void removeBroadphaseCollisionFilter(
int objectUniqueIdA, int objectUniqueIdB,
int linkIndexA, int linkIndexB)
{
b3CustomCollisionFilter keyValue;
keyValue.m_objectUniqueIdA = objectUniqueIdA;
keyValue.m_linkIndexA = linkIndexA;
keyValue.m_objectUniqueIdB = objectUniqueIdB;
keyValue.m_linkIndexB = linkIndexB;
if (objectUniqueIdA > objectUniqueIdB)
{
b3Swap(keyValue.m_objectUniqueIdA, keyValue.m_objectUniqueIdB);
b3Swap(keyValue.m_linkIndexA, keyValue.m_linkIndexB);
}
if (objectUniqueIdA == objectUniqueIdB)
{
if (keyValue.m_linkIndexA > keyValue.m_linkIndexB)
{
b3Swap(keyValue.m_linkIndexA, keyValue.m_linkIndexB);
}
}
m_customCollisionFilters.remove(keyValue);
}
virtual int getNumRules() const
{
return m_customCollisionFilters.size();
}
virtual void resetAll()
{
m_customCollisionFilters.clear();
}
virtual int needsBroadphaseCollision(int objectUniqueIdA, int linkIndexA,
int collisionFilterGroupA, int collisionFilterMaskA,
int objectUniqueIdB, int linkIndexB,
int collisionFilterGroupB, int collisionFilterMaskB,
int filterMode)
{
//check and apply any custom rules for those objects/links
b3CustomCollisionFilter keyValue;
keyValue.m_objectUniqueIdA = objectUniqueIdA;
keyValue.m_linkIndexA = linkIndexA;
keyValue.m_objectUniqueIdB = objectUniqueIdB;
keyValue.m_linkIndexB = linkIndexB;
if (objectUniqueIdA > objectUniqueIdB)
{
b3Swap(keyValue.m_objectUniqueIdA, keyValue.m_objectUniqueIdB);
b3Swap(keyValue.m_linkIndexA, keyValue.m_linkIndexB);
}
if (objectUniqueIdA == objectUniqueIdB)
{
if (keyValue.m_linkIndexA > keyValue.m_linkIndexB)
{
b3Swap(keyValue.m_linkIndexA, keyValue.m_linkIndexB);
}
}
b3CustomCollisionFilter* filter = m_customCollisionFilters.find(keyValue);
if (filter)
{
return filter->m_enableCollision;
}
//otherwise use the default fallback
if (filterMode == B3_FILTER_GROUPAMASKB_AND_GROUPBMASKA)
{
bool collides = (collisionFilterGroupA & collisionFilterMaskB) != 0;
collides = collides && (collisionFilterGroupB & collisionFilterMaskA);
return collides;
}
if (filterMode == B3_FILTER_GROUPAMASKB_OR_GROUPBMASKA)
{
bool collides = (collisionFilterGroupA & collisionFilterMaskB) != 0;
collides = collides || (collisionFilterGroupB & collisionFilterMaskA);
return collides;
}
return false;
}
};
struct CollisionFilterMyClass
{
int m_testData;
DefaultPluginCollisionInterface m_collisionFilter;
CollisionFilterMyClass()
: m_testData(42)
{
}
virtual ~CollisionFilterMyClass()
{
}
};
B3_SHARED_API int initPlugin_collisionFilterPlugin(struct b3PluginContext* context)
{
CollisionFilterMyClass* obj = new CollisionFilterMyClass();
context->m_userPointer = obj;
return SHARED_MEMORY_MAGIC_NUMBER;
}
B3_SHARED_API struct b3PluginCollisionInterface* getCollisionInterface_collisionFilterPlugin(struct b3PluginContext* context)
{
CollisionFilterMyClass* obj = (CollisionFilterMyClass*)context->m_userPointer;
return &obj->m_collisionFilter;
}
B3_SHARED_API int executePluginCommand_collisionFilterPlugin(struct b3PluginContext* context, const struct b3PluginArguments* arguments)
{
return 0;
}
B3_SHARED_API void exitPlugin_collisionFilterPlugin(struct b3PluginContext* context)
{
CollisionFilterMyClass* obj = (CollisionFilterMyClass*)context->m_userPointer;
delete obj;
context->m_userPointer = 0;
}
| 412 | 0.854116 | 1 | 0.854116 | game-dev | MEDIA | 0.770983 | game-dev | 0.834576 | 1 | 0.834576 |
randomguy3725/MoonLight | 2,973 | src/main/java/net/minecraft/item/crafting/RecipesMapCloning.java | package net.minecraft.item.crafting;
import net.minecraft.init.Items;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
public class RecipesMapCloning implements IRecipe
{
public boolean matches(InventoryCrafting inv, World worldIn)
{
int i = 0;
ItemStack itemstack = null;
for (int j = 0; j < inv.getSizeInventory(); ++j)
{
ItemStack itemstack1 = inv.getStackInSlot(j);
if (itemstack1 != null)
{
if (itemstack1.getItem() == Items.filled_map)
{
if (itemstack != null)
{
return false;
}
itemstack = itemstack1;
}
else
{
if (itemstack1.getItem() != Items.map)
{
return false;
}
++i;
}
}
}
return itemstack != null && i > 0;
}
public ItemStack getCraftingResult(InventoryCrafting inv)
{
int i = 0;
ItemStack itemstack = null;
for (int j = 0; j < inv.getSizeInventory(); ++j)
{
ItemStack itemstack1 = inv.getStackInSlot(j);
if (itemstack1 != null)
{
if (itemstack1.getItem() == Items.filled_map)
{
if (itemstack != null)
{
return null;
}
itemstack = itemstack1;
}
else
{
if (itemstack1.getItem() != Items.map)
{
return null;
}
++i;
}
}
}
if (itemstack != null && i >= 1)
{
ItemStack itemstack2 = new ItemStack(Items.filled_map, i + 1, itemstack.getMetadata());
if (itemstack.hasDisplayName())
{
itemstack2.setStackDisplayName(itemstack.getDisplayName());
}
return itemstack2;
}
else
{
return null;
}
}
public int getRecipeSize()
{
return 9;
}
public ItemStack getRecipeOutput()
{
return null;
}
public ItemStack[] getRemainingItems(InventoryCrafting inv)
{
ItemStack[] aitemstack = new ItemStack[inv.getSizeInventory()];
for (int i = 0; i < aitemstack.length; ++i)
{
ItemStack itemstack = inv.getStackInSlot(i);
if (itemstack != null && itemstack.getItem().hasContainerItem())
{
aitemstack[i] = new ItemStack(itemstack.getItem().getContainerItem());
}
}
return aitemstack;
}
}
| 412 | 0.754392 | 1 | 0.754392 | game-dev | MEDIA | 0.996252 | game-dev | 0.899926 | 1 | 0.899926 |
Madalaski/ObraDinnTutorial | 10,791 | Library/PackageCache/com.unity.timeline@1.4.6/Editor/Window/TimelineWindow_HeaderGui.cs | using System.Linq;
using UnityEngine;
using UnityEngine.Timeline;
namespace UnityEditor.Timeline
{
partial class TimelineWindow
{
static readonly GUIContent[] k_TimeReferenceGUIContents =
{
EditorGUIUtility.TrTextContent("Local", "Display time based on the current timeline."),
EditorGUIUtility.TrTextContent("Global", "Display time based on the master timeline.")
};
TimelineMarkerHeaderGUI m_MarkerHeaderGUI;
void MarkerHeaderGUI()
{
var timelineAsset = state.editSequence.asset;
if (timelineAsset == null)
return;
if (m_MarkerHeaderGUI == null)
m_MarkerHeaderGUI = new TimelineMarkerHeaderGUI(timelineAsset, state);
m_MarkerHeaderGUI.Draw(markerHeaderRect, markerContentRect, state);
}
void DrawTransportToolbar()
{
using (new EditorGUI.DisabledScope(currentMode.PreviewState(state) == TimelineModeGUIState.Disabled))
{
PreviewModeButtonGUI();
}
using (new EditorGUI.DisabledScope(currentMode.ToolbarState(state) == TimelineModeGUIState.Disabled))
{
GotoBeginingSequenceGUI();
PreviousEventButtonGUI();
PlayButtonGUI();
NextEventButtonGUI();
GotoEndSequenceGUI();
PlayRangeButtonGUI();
TimeCodeGUI();
ReferenceTimeGUI();
}
}
void PreviewModeButtonGUI()
{
if (state.ignorePreview && !Application.isPlaying)
{
GUILayout.Label(DirectorStyles.previewDisabledContent, DirectorStyles.Instance.previewButtonDisabled);
return;
}
EditorGUI.BeginChangeCheck();
var enabled = state.previewMode;
enabled = GUILayout.Toggle(enabled, DirectorStyles.previewContent, EditorStyles.toolbarButton);
if (EditorGUI.EndChangeCheck())
{
// turn off auto play as well, so it doesn't auto reenable
if (!enabled)
{
state.SetPlaying(false);
state.recording = false;
}
state.previewMode = enabled;
// if we are successfully enabled, rebuild the graph so initial states work correctly
// Note: testing both values because previewMode setter can "fail"
if (enabled && state.previewMode)
state.rebuildGraph = true;
}
}
void GotoBeginingSequenceGUI()
{
if (GUILayout.Button(DirectorStyles.gotoBeginingContent, EditorStyles.toolbarButton))
{
state.editSequence.time = 0;
state.EnsurePlayHeadIsVisible();
}
}
// in the editor the play button starts/stops simulation
void PlayButtonGUIEditor()
{
EditorGUI.BeginChangeCheck();
var isPlaying = GUILayout.Toggle(state.playing, DirectorStyles.playContent, EditorStyles.toolbarButton);
if (EditorGUI.EndChangeCheck())
{
state.SetPlaying(isPlaying);
}
}
// in playmode the button reflects the playing state.
// needs to disabled if playing is not possible
void PlayButtonGUIPlayMode()
{
bool buttonEnabled = state.masterSequence.director != null &&
state.masterSequence.director.isActiveAndEnabled;
using (new EditorGUI.DisabledScope(!buttonEnabled))
{
PlayButtonGUIEditor();
}
}
void PlayButtonGUI()
{
if (!Application.isPlaying)
PlayButtonGUIEditor();
else
PlayButtonGUIPlayMode();
}
void NextEventButtonGUI()
{
if (GUILayout.Button(DirectorStyles.nextFrameContent, EditorStyles.toolbarButton))
{
state.referenceSequence.frame += 1;
}
}
void PreviousEventButtonGUI()
{
if (GUILayout.Button(DirectorStyles.previousFrameContent, EditorStyles.toolbarButton))
{
state.referenceSequence.frame -= 1;
}
}
void GotoEndSequenceGUI()
{
if (GUILayout.Button(DirectorStyles.gotoEndContent, EditorStyles.toolbarButton))
{
state.editSequence.time = state.editSequence.asset.duration;
state.EnsurePlayHeadIsVisible();
}
}
void PlayRangeButtonGUI()
{
using (new EditorGUI.DisabledScope(state.ignorePreview || state.IsEditingASubTimeline()))
{
state.playRangeEnabled = GUILayout.Toggle(state.playRangeEnabled, DirectorStyles.Instance.playrangeContent, EditorStyles.toolbarButton);
}
}
void AddButtonGUI()
{
if (currentMode.trackOptionsState.newButton == TimelineModeGUIState.Hidden)
return;
using (new EditorGUI.DisabledScope(currentMode.trackOptionsState.newButton == TimelineModeGUIState.Disabled))
{
if (EditorGUILayout.DropdownButton(DirectorStyles.newContent, FocusType.Passive, EditorStyles.toolbarPopup))
{
// if there is 1 and only 1 track selected, AND it's a group, add to that group
var groupTracks = SelectionManager.SelectedTracks().ToList();
if (groupTracks.Any(x => x.GetType() != typeof(GroupTrack) || x.lockedInHierarchy))
groupTracks = null;
SequencerContextMenu.ShowNewTracksContextMenu(groupTracks, state, EditorGUILayout.s_LastRect);
}
}
}
void ShowMarkersButton()
{
var asset = state.editSequence.asset;
if (asset == null)
return;
var content = state.showMarkerHeader ? DirectorStyles.showMarkersOn : DirectorStyles.showMarkersOff;
SetShowMarkerHeader(GUILayout.Toggle(state.showMarkerHeader, content, DirectorStyles.Instance.showMarkersBtn));
}
internal void SetShowMarkerHeader(bool newValue)
{
if (state.showMarkerHeader == newValue)
return;
TimelineUndo.PushUndo(state.editSequence.viewModel, "Toggle Show Markers");
state.editSequence.viewModel.showMarkerHeader = newValue;
if (!newValue)
{
var asset = state.editSequence.asset;
if (asset != null && asset.markerTrack != null)
{
SelectionManager.Remove(asset.markerTrack);
foreach (var marker in asset.markerTrack.GetMarkers())
{
SelectionManager.Remove(marker);
}
}
}
}
static void EditModeToolbarGUI(TimelineMode mode)
{
using (new EditorGUI.DisabledScope(mode.EditModeButtonsState(instance.state) == TimelineModeGUIState.Disabled))
{
var editType = EditMode.editType;
EditorGUI.BeginChangeCheck();
var mixIcon = editType == EditMode.EditType.Mix ? DirectorStyles.mixOn : DirectorStyles.mixOff;
GUILayout.Toggle(editType == EditMode.EditType.Mix, mixIcon, DirectorStyles.Instance.editModeBtn);
if (EditorGUI.EndChangeCheck())
EditMode.editType = EditMode.EditType.Mix;
EditorGUI.BeginChangeCheck();
var rippleIcon = editType == EditMode.EditType.Ripple ? DirectorStyles.rippleOn : DirectorStyles.rippleOff;
GUILayout.Toggle(editType == EditMode.EditType.Ripple, rippleIcon, DirectorStyles.Instance.editModeBtn);
if (EditorGUI.EndChangeCheck())
EditMode.editType = EditMode.EditType.Ripple;
EditorGUI.BeginChangeCheck();
var replaceIcon = editType == EditMode.EditType.Replace ? DirectorStyles.replaceOn : DirectorStyles.replaceOff;
GUILayout.Toggle(editType == EditMode.EditType.Replace, replaceIcon, DirectorStyles.Instance.editModeBtn);
if (EditorGUI.EndChangeCheck())
EditMode.editType = EditMode.EditType.Replace;
}
}
// Draws the box to enter the time field
void TimeCodeGUI()
{
EditorGUI.BeginChangeCheck();
var currentTime = state.editSequence.asset != null ? TimeReferenceUtility.ToTimeString(state.editSequence.time, "F1") : "0";
var r = EditorGUILayout.GetControlRect(false, EditorGUI.kSingleLineHeight, EditorStyles.toolbarTextField, GUILayout.Width(WindowConstants.timeCodeWidth));
var id = GUIUtility.GetControlID("RenameFieldTextField".GetHashCode(), FocusType.Passive, r);
var newCurrentTime = EditorGUI.DelayedTextFieldInternal(r, id, GUIContent.none, currentTime, null, EditorStyles.toolbarTextField);
if (EditorGUI.EndChangeCheck())
state.editSequence.time = TimeReferenceUtility.FromTimeString(newCurrentTime);
}
void ReferenceTimeGUI()
{
if (!state.IsEditingASubTimeline())
return;
EditorGUI.BeginChangeCheck();
state.timeReferenceMode = (TimeReferenceMode)EditorGUILayout.CycleButton((int)state.timeReferenceMode, k_TimeReferenceGUIContents, DirectorStyles.Instance.timeReferenceButton);
if (EditorGUI.EndChangeCheck())
OnTimeReferenceModeChanged();
}
void OnTimeReferenceModeChanged()
{
m_TimeAreaDirty = true;
InitTimeAreaFrameRate();
SyncTimeAreaShownRange();
foreach (var inspector in InspectorWindow.GetAllInspectorWindows())
{
inspector.Repaint();
}
}
void DrawHeaderEditButtons()
{
if (state.editSequence.asset == null)
return;
using (new GUILayout.HorizontalScope(EditorStyles.toolbar, GUILayout.Width(sequenceHeaderRect.width)))
{
GUILayout.Space(DirectorStyles.kBaseIndent);
AddButtonGUI();
GUILayout.FlexibleSpace();
EditModeToolbarGUI(currentMode);
ShowMarkersButton();
EditorGUILayout.Space();
}
}
}
}
| 412 | 0.93809 | 1 | 0.93809 | game-dev | MEDIA | 0.932819 | game-dev | 0.990496 | 1 | 0.990496 |
Electroblob77/Wizardry | 1,844 | src/main/java/electroblob/wizardry/packet/PacketSyncDonationPerks.java | package electroblob.wizardry.packet;
import electroblob.wizardry.constants.Element;
import electroblob.wizardry.misc.DonationPerksHandler;
import io.netty.buffer.ByteBuf;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import java.util.ArrayList;
import java.util.List;
/**
* <b>[Server -> Client]</b> This packet is sent to update the donation perks map for each player that logs in, and for
* all players whenever the map changes.
*/
public class PacketSyncDonationPerks implements IMessageHandler<PacketSyncDonationPerks.Message, IMessage> {
@Override
public IMessage onMessage(Message message, MessageContext ctx){
// Just to make sure that the side is correct
if(ctx.side.isClient()){
// Using a fully qualified name is a good course of action here; we don't really want to clutter the proxy
// methods any more than necessary.
net.minecraft.client.Minecraft.getMinecraft().addScheduledTask(() -> DonationPerksHandler.setElements(message.elements));
}
return null;
}
public static class Message implements IMessage {
public List<Element> elements;
// This constructor is required otherwise you'll get errors (used somewhere in fml through reflection)
public Message(){}
public Message(List<Element> elements){
this.elements = elements;
}
@Override
public void fromBytes(ByteBuf buf){
// The order is important
this.elements = new ArrayList<>();
while(buf.isReadable()){
int i = buf.readShort();
elements.add(i == -1 ? null : Element.values()[i]);
}
}
@Override
public void toBytes(ByteBuf buf){
for(Element element : elements) buf.writeShort(element == null ? -1 : element.ordinal());
}
}
}
| 412 | 0.831314 | 1 | 0.831314 | game-dev | MEDIA | 0.957916 | game-dev | 0.960534 | 1 | 0.960534 |
stacklok/toolhive | 2,432 | cmd/thv/app/runtime.go | package app
import (
"context"
"fmt"
"time"
"github.com/spf13/cobra"
"github.com/stacklok/toolhive/pkg/container"
"github.com/stacklok/toolhive/pkg/container/runtime"
)
// Define the `runtime` parent command
var runtimeCmd = &cobra.Command{
Use: "runtime",
Short: "Commands related to the container runtime",
}
// Define the `runtime check` subcommand
var runtimeCheckCmd = &cobra.Command{
Use: "check",
Short: "Ping the container runtime",
Long: "Ensure the container runtime is responsive.",
Args: cobra.NoArgs, // no args allowed
RunE: runtimeCheckCmdFunc,
}
var runtimeCheckTimeout int
func init() {
rootCmd.AddCommand(runtimeCmd)
runtimeCmd.AddCommand(runtimeCheckCmd)
runtimeCheckCmd.Flags().IntVar(&runtimeCheckTimeout, "timeout", 30,
"Timeout in seconds for runtime checks (default: 30 seconds)")
}
func runtimeCheckCmdFunc(cmd *cobra.Command, _ []string) error {
ctx := cmd.Context()
// Create runtime with timeout
createCtx, cancelCreate := context.WithTimeout(ctx, time.Duration(runtimeCheckTimeout)*time.Second)
defer cancelCreate()
rt, err := createWithTimeout(createCtx)
if err != nil {
if createCtx.Err() == context.DeadlineExceeded {
return fmt.Errorf("creating container runtime timed out after %d seconds", runtimeCheckTimeout)
}
return fmt.Errorf("failed to create container runtime: %w", err)
}
// Ping with separate timeout
pingCtx, cancelPing := context.WithTimeout(ctx, time.Duration(runtimeCheckTimeout)*time.Second)
defer cancelPing()
if err := pingRuntime(pingCtx, rt); err != nil {
if pingCtx.Err() == context.DeadlineExceeded {
return fmt.Errorf("runtime ping timed out after %d seconds", runtimeCheckTimeout)
}
return fmt.Errorf("runtime ping failed: %w", err)
}
fmt.Println("Container runtime is responsive")
return nil
}
func createWithTimeout(ctx context.Context) (runtime.Runtime, error) {
done := make(chan struct {
rt runtime.Runtime
err error
}, 1)
go func() {
rt, err := container.NewFactory().Create(ctx)
done <- struct {
rt runtime.Runtime
err error
}{rt, err}
}()
select {
case <-ctx.Done():
return nil, ctx.Err()
case res := <-done:
return res.rt, res.err
}
}
func pingRuntime(ctx context.Context, rt runtime.Runtime) error {
done := make(chan error, 1)
go func() {
done <- rt.IsRunning(ctx)
}()
select {
case <-ctx.Done():
return ctx.Err()
case err := <-done:
return err
}
}
| 412 | 0.693018 | 1 | 0.693018 | game-dev | MEDIA | 0.21061 | game-dev | 0.648261 | 1 | 0.648261 |
pWn3d1337/Techguns2 | 33,888 | src/main/java/techguns/events/TGEventHandler.java | package techguns.events;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import com.mojang.realmsclient.gui.ChatFormatting;
import elucent.albedo.event.GatherLightsEvent;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.audio.ISound;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelBiped.ArmPose;
import net.minecraft.client.model.ModelPlayer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.ItemRenderer;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.GlStateManager.DestFactor;
import net.minecraft.client.renderer.GlStateManager.SourceFactor;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.attributes.IAttributeInstance;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.EnumHandSide;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.RayTraceResult.Type;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.WorldServer;
import net.minecraft.world.storage.loot.LootContext;
import net.minecraft.world.storage.loot.LootTable;
import net.minecraftforge.client.event.DrawBlockHighlightEvent;
import net.minecraftforge.client.event.FOVUpdateEvent;
import net.minecraftforge.client.event.ModelBakeEvent;
import net.minecraftforge.client.event.MouseEvent;
import net.minecraftforge.client.event.RenderHandEvent;
import net.minecraftforge.client.event.RenderLivingEvent;
import net.minecraftforge.client.event.RenderWorldLastEvent;
import net.minecraftforge.client.event.TextureStitchEvent;
import net.minecraftforge.client.event.sound.SoundEvent.SoundSourceEvent;
import net.minecraftforge.event.entity.EntityEvent.EntityConstructing;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
import net.minecraftforge.event.entity.living.LivingAttackEvent;
import net.minecraftforge.event.entity.living.LivingDeathEvent;
import net.minecraftforge.event.entity.living.LivingEquipmentChangeEvent;
import net.minecraftforge.event.entity.living.LivingEvent.LivingJumpEvent;
import net.minecraftforge.event.entity.living.LivingEvent.LivingUpdateEvent;
import net.minecraftforge.event.entity.living.LivingFallEvent;
import net.minecraftforge.event.entity.living.LivingHurtEvent;
import net.minecraftforge.event.entity.player.EntityItemPickupEvent;
import net.minecraftforge.event.entity.player.ItemTooltipEvent;
import net.minecraftforge.event.entity.player.PlayerDropsEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.event.entity.player.PlayerEvent.BreakSpeed;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.event.world.BlockEvent;
import net.minecraftforge.event.world.BlockEvent.HarvestDropsEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Optional;
import net.minecraftforge.fml.common.eventhandler.Event.Result;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.PlayerEvent.ItemCraftedEvent;
import net.minecraftforge.fml.relauncher.ReflectionHelper;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import techguns.TGBlocks;
import techguns.TGConfig;
import techguns.TGPackets;
import techguns.TGRadiationSystem;
import techguns.Techguns;
import techguns.api.guns.GunHandType;
import techguns.api.guns.GunManager;
import techguns.api.guns.IGenericGun;
import techguns.api.npc.INpcTGDamageSystem;
import techguns.api.radiation.TGRadiation;
import techguns.api.tginventory.ITGSpecialSlot;
import techguns.api.tginventory.TGSlotType;
import techguns.capabilities.TGExtendedPlayer;
import techguns.client.ClientProxy;
import techguns.client.ShooterValues;
import techguns.client.audio.TGSound;
import techguns.client.render.GLStateSnapshot;
import techguns.client.render.entities.npcs.RenderAttackHelicopter;
import techguns.client.render.entities.projectiles.DeathEffectEntityRenderer;
import techguns.client.render.entities.projectiles.RenderGrenade40mmProjectile;
import techguns.client.render.tileentities.RenderDoor3x3Fast;
import techguns.damagesystem.DamageSystem;
import techguns.damagesystem.TGDamageSource;
import techguns.deatheffects.EntityDeathUtils;
import techguns.deatheffects.EntityDeathUtils.DeathType;
import techguns.entities.npcs.TGDummySpawn;
import techguns.entities.spawn.TGSpawnManager;
import techguns.gui.player.TGPlayerInventory;
import techguns.gui.widgets.SlotFabricator;
import techguns.gui.widgets.SlotTG;
import techguns.items.armors.GenericArmor;
import techguns.items.armors.TGArmorBonus;
import techguns.items.guns.GenericGrenade;
import techguns.items.guns.GenericGun;
import techguns.items.guns.GenericGunCharge;
import techguns.items.guns.GenericGunMeleeCharge;
import techguns.items.guns.MiningDrill;
import techguns.packets.PacketEntityDeathType;
import techguns.packets.PacketNotifyAmbientEffectChange;
import techguns.packets.PacketRequestTGPlayerSync;
import techguns.packets.PacketTGExtendedPlayerSync;
import techguns.radiation.ItemRadiationData;
import techguns.radiation.ItemRadiationRegistry;
import techguns.util.BlockUtils;
import techguns.util.InventoryUtil;
import techguns.util.TextUtil;
@Mod.EventBusSubscriber(modid = Techguns.MODID)
public class TGEventHandler {
@SideOnly(Side.CLIENT)
@SubscribeEvent(priority = EventPriority.HIGH)
public static void onMouseEvent(MouseEvent event) {
if (event.getButton()!=-1){
EntityPlayerSP ply = Minecraft.getMinecraft().player;
if (Minecraft.getMinecraft().inGameHasFocus) {
// System.out.println("MOUSE EVENT LMB");
if (event.getButton() == 0 && !ply.getHeldItemMainhand().isEmpty() && ply.getHeldItemMainhand().getItem() instanceof IGenericGun) {
ClientProxy cp = ClientProxy.get();
if (((IGenericGun) ply.getHeldItemMainhand().getItem()).isShootWithLeftClick()) {
cp.keyFirePressedMainhand = event.isButtonstate();
event.setCanceled(true);
// can't mine/attack while reloading
} else if (ShooterValues.getReloadtime(ClientProxy.get().getPlayerClient(), false) > 0) {
long diff = ShooterValues.getReloadtime(ClientProxy.get().getPlayerClient(), false) - System.currentTimeMillis();
if (diff > 0) {
if (event.isButtonstate()) {
event.setCanceled(true);
}
}
}
} /*else if (event.getButton() == 1 && !GunManager.canUseOffhand(ply)) {
if(!ply.getHeldItemMainhand().isEmpty()&&ply.getHeldItemMainhand().getItem() instanceof GenericGunCharge) {
//Charging gun is allowed
} else if (!ply.getHeldItemMainhand().isEmpty() && ply.getHeldItemMainhand().getItem() instanceof GenericGun){
GenericGun g = (GenericGun) ply.getHeldItemMainhand().getItem();
//Cancel and call secondary action
if (!ply.isSneaking() && event.isButtonstate()) {
boolean use = g.gunSecondaryAction(ply, ply.getHeldItemMainhand());
event.setCanceled(use);
}
}
} */ else if (event.getButton() == 1 && !ply.isSneaking() && !ply.getHeldItemOffhand().isEmpty() && ply.getHeldItemOffhand().getItem() instanceof IGenericGun && GunManager.canUseOffhand(ply)) {
ClientProxy cp = ClientProxy.get();
if (((IGenericGun) ply.getHeldItemOffhand().getItem()).isShootWithLeftClick()) {
cp.keyFirePressedOffhand = event.isButtonstate();
event.setCanceled(true);
// can't mine/attack while reloading
} else if (ShooterValues.getReloadtime(ClientProxy.get().getPlayerClient(), true) > 0) {
long diff = ShooterValues.getReloadtime(ClientProxy.get().getPlayerClient(), true) - System.currentTimeMillis();
if (diff > 0) {
if (event.isButtonstate()) {
event.setCanceled(true);
}
}
}
//Lock On Weapon
}else if (event.getButton() == 1 && ply.getHeldItemMainhand().getItem() instanceof GenericGunCharge && ((GenericGunCharge)ply.getHeldItemMainhand().getItem()).getLockOnTicks() > 0) {
//System.out.println("Start/Stop LockOn: RMB = "+event.isButtonstate());
ClientProxy cp = ClientProxy.get();
//cp.keyFirePressedOffhand = event.isButtonstate();
TGExtendedPlayer props = TGExtendedPlayer.get(ply);
props.lockOnEntity = null;
props.lockOnTicks = -1;
//System.out.println("reset lock.");
}
//System.out.println("EVENT CANCELLED: "+event.isCanceled());
}
}
}
protected static boolean allowOffhandUse(EntityPlayer player, EnumHand hand) {
if (hand == EnumHand.MAIN_HAND) return true;
if(!player.getHeldItemMainhand().isEmpty() && player.getHeldItemMainhand().getItem() instanceof IGenericGun) {
IGenericGun g = (IGenericGun) player.getHeldItemMainhand().getItem();
if(g.getGunHandType()==GunHandType.TWO_HANDED) {
return false;
}
}
if(!player.getHeldItemOffhand().isEmpty() && player.getHeldItemOffhand().getItem() instanceof IGenericGun) {
IGenericGun g = (IGenericGun) player.getHeldItemOffhand().getItem();
if(g.getGunHandType()==GunHandType.TWO_HANDED) {
return false;
}
}
return true;
}
@SubscribeEvent(priority=EventPriority.HIGH, receiveCanceled=false)
public static void rightClickEvent(PlayerInteractEvent.RightClickItem event) {
boolean cancel = !allowOffhandUse(event.getEntityPlayer(), event.getHand());
if (cancel) {
event.setCanceled(cancel);
event.setCancellationResult(EnumActionResult.PASS);
}
//System.out.println("Right Click Item:"+event.getEntityPlayer()+" "+event.getHand());
}
@SubscribeEvent(priority=EventPriority.HIGH, receiveCanceled=false)
public static void rightClickEvent(PlayerInteractEvent.RightClickBlock event) {
boolean cancel = !allowOffhandUse(event.getEntityPlayer(), event.getHand());
if (cancel) {
event.setCanceled(cancel);
event.setUseBlock(Result.ALLOW);
event.setUseItem(Result.DENY);
event.setCancellationResult(EnumActionResult.PASS);
} else if (event.getHand() == EnumHand.MAIN_HAND){
EntityPlayer ply = event.getEntityPlayer();
if(ply.isSneaking() && !ply.getHeldItemOffhand().isEmpty() && (ply.getHeldItemOffhand().getItem() instanceof GenericGun) && (!event.getItemStack().isEmpty() && !(event.getItemStack().getItem() instanceof GenericGun)) ) {
event.setUseBlock(Result.ALLOW);
}
}
}
@SubscribeEvent(priority=EventPriority.HIGH, receiveCanceled=false)
public static void rightClickEvent(PlayerInteractEvent.EntityInteract event) {
boolean cancel = !allowOffhandUse(event.getEntityPlayer(), event.getHand());
if (cancel) {
event.setCanceled(cancel);
event.setCancellationResult(EnumActionResult.PASS);
}
//System.out.println("EntityInteract:"+event.getEntityPlayer()+" "+event.getHand());
}
@SideOnly(Side.CLIENT)
@SubscribeEvent(priority=EventPriority.LOW) //set to low so other mods don't accidentally destroy it easily
public static void handleFovEvent(FOVUpdateEvent event){
float f = 1.0f;
if ( TGConfig.cl_lockSpeedFov){
IAttributeInstance iattributeinstance = event.getEntity().getEntityAttribute(SharedMonsterAttributes.MOVEMENT_SPEED);
f = 1/ ((float)(((iattributeinstance.getAttributeValue() / (double)event.getEntity().capabilities.getWalkSpeed() + 1.0D) / 2.0D)));
if(ClientProxy.get().getPlayerClient().isSprinting()){
f*=TGConfig.cl_fixedSprintFov;
}
}
event.setNewfov(event.getNewfov()*ClientProxy.get().player_zoom*f);//*speedFOV;
}
@SideOnly(Side.CLIENT)
@SubscribeEvent(priority=EventPriority.NORMAL, receiveCanceled=false)
public static void onRenderLivingEventPre(RenderLivingEvent.Pre event){
if (event.getEntity() instanceof EntityPlayer) {
EntityPlayer ply = (EntityPlayer) event.getEntity();
ItemStack stack =ply.getHeldItemMainhand();
if(!stack.isEmpty() && stack.getItem() instanceof GenericGun && ((GenericGun) stack.getItem()).hasBowAnim()){
ModelBase mdl = event.getRenderer().getMainModel();
if (mdl instanceof ModelPlayer) {
ModelPlayer model = (ModelPlayer) mdl;
if (ply.getPrimaryHand()==EnumHandSide.RIGHT) {
model.rightArmPose = ArmPose.BOW_AND_ARROW;
} else {
model.leftArmPose = ArmPose.BOW_AND_ARROW;
}
}
} else {
ItemStack stack2 =ply.getHeldItemOffhand();
if(!stack2.isEmpty() && stack2.getItem() instanceof GenericGun && ((GenericGun) stack2.getItem()).hasBowAnim()){
ModelBase mdl = event.getRenderer().getMainModel();
if (mdl instanceof ModelPlayer) {
ModelPlayer model = (ModelPlayer) mdl;
if (ShooterValues.getIsCurrentlyUsingGun(ply,true)){
if (ply.getPrimaryHand()==EnumHandSide.RIGHT) {
model.leftArmPose = ArmPose.BOW_AND_ARROW;
} else {
model.rightArmPose = ArmPose.BOW_AND_ARROW;
}
}
}
}
}
}
/*
* ENTITY DEATH EFFECTS
*/
ClientProxy cp = ClientProxy.get();
DeathType dt = cp.getEntityDeathType(event.getEntity());
switch (dt) {
case GORE:
event.setCanceled(true);
break;
case DISMEMBER:
case BIO:
case LASER:
//TODO
event.setCanceled(true);
DeathEffectEntityRenderer.doRender(event.getRenderer(), event.getEntity(), event.getX(), event.getY(), event.getZ(), 0f, dt);
break;
case DEFAULT:
default:
break;
}
}
@SubscribeEvent(priority=EventPriority.HIGH, receiveCanceled=false)
public static void OnLivingAttack(LivingAttackEvent event){
if (event.getSource() instanceof TGDamageSource) {
event.setCanceled(true);
try {
DamageSystem.attackEntityFrom(event.getEntityLiving(), event.getSource(), event.getAmount());
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
} else if ( (event.getSource() == DamageSource.LAVA || event.getSource()==DamageSource.ON_FIRE || event.getSource()==DamageSource.IN_FIRE) && event.getEntityLiving() instanceof EntityPlayer) {
float bonus = GenericArmor.getArmorBonusForPlayer((EntityPlayer) event.getEntityLiving(), TGArmorBonus.COOLING_SYSTEM,event.getEntityLiving().world.getTotalWorldTime()%5==0);
if (bonus >=1.0f) {
event.setCanceled(true);
}
}
}
@SubscribeEvent(priority=EventPriority.HIGH, receiveCanceled=false)
public static void onLivingHurt(LivingHurtEvent event) {
if(event.getEntity() instanceof INpcTGDamageSystem) {
event.setCanceled(true);
try {
DamageSystem.livingHurt(event.getEntityLiving(), event.getSource(), event.getAmount());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
@SubscribeEvent(priority=EventPriority.NORMAL, receiveCanceled=false)
public static void onLivingJumpEvent(LivingJumpEvent event)
{
if (event.getEntity() instanceof EntityPlayer)
{
EntityPlayer ply = (EntityPlayer) event.getEntity();
float jumpbonus = GenericArmor.getArmorBonusForPlayer(ply, TGArmorBonus.JUMP,true);
/*if (ply.onGround && ply.isSneaking()){
jumpbonus*=5;
}*/
ply.motionY+=jumpbonus;
}
}
@SubscribeEvent(priority=EventPriority.NORMAL, receiveCanceled=false)
public static void onLivingFallEvent(LivingFallEvent event)
{
if (event.getEntity() instanceof EntityPlayer)
{
boolean consume= event.getDistance()>3.0f;
EntityPlayer ply = (EntityPlayer) event.getEntity();
float fallbonus = GenericArmor.getArmorBonusForPlayer(ply, TGArmorBonus.FALLDMG,consume);
float reduction = (fallbonus <1 ? 1-fallbonus : 0.0f);
float freeheight = GenericArmor.getArmorBonusForPlayer(ply, TGArmorBonus.FREEHEIGHT,false);
if(freeheight<event.getDistance()){
event.setDistance(event.getDistance() - freeheight);
} else {
event.setDistance(0.0f);
}
event.setDistance(event.getDistance() * reduction);
}
}
@SubscribeEvent(priority=EventPriority.HIGH, receiveCanceled=false)
public static void onBreakEventHigh(BreakSpeed event){
EntityPlayer ply = event.getEntityPlayer();
ItemStack item = ply.getHeldItemMainhand();
if(!item.isEmpty() && item.getItem() instanceof GenericGunMeleeCharge) {
GenericGunMeleeCharge g = (GenericGunMeleeCharge) item.getItem();
if(g.getMiningRadius(item)>0) {
EnumFacing sidehit = g.getSideHitMining(ply.world, ply);
if (sidehit!=null) {
IBlockState state = event.getState();
float mainHardness = state.getBlockHardness(ply.world, event.getPos());
List<BlockPos> blocks = BlockUtils.getBlockPlaneAroundAxisForMining(ply.world,ply, event.getPos(), sidehit.getAxis(), g.getMiningRadius(item), false, g, item);
float maxHardness = 0f;
for (BlockPos p: blocks) {
IBlockState s = ply.world.getBlockState(p);
float h = s.getBlockHardness(ply.world, p);
if(h>maxHardness) {
maxHardness=h;
}
}
if (maxHardness>mainHardness) {
event.setNewSpeed(event.getNewSpeed()*mainHardness/maxHardness);
}
}
}
}
}
@SubscribeEvent(priority=EventPriority.NORMAL, receiveCanceled=false)
public static void onBreakEvent(BreakSpeed event){
EntityPlayer ply = event.getEntityPlayer();
float bonus = 1.0f+GenericArmor.getArmorBonusForPlayer(ply, TGArmorBonus.BREAKSPEED,true);
float waterbonus=1.0f;
if(ply.isInsideOfMaterial(Material.WATER) || ply.isInsideOfMaterial(Material.LAVA)){
waterbonus += GenericArmor.getArmorBonusForPlayer(ply, TGArmorBonus.BREAKSPEED_WATER,true);
}
event.setNewSpeed(event.getNewSpeed()*bonus*waterbonus);
}
@SubscribeEvent(priority=EventPriority.NORMAL, receiveCanceled=false)
public static void onLivingDeathEvent(LivingDeathEvent event){
EntityLivingBase entity = event.getEntityLiving();
if(!entity.world.isRemote){
if(entity instanceof EntityPlayer){
TGExtendedPlayer tgplayer = TGExtendedPlayer.get((EntityPlayer) event.getEntityLiving());
tgplayer.foodleft=0;
tgplayer.lastSaturation=0;
tgplayer.addRadiation(-TGRadiationSystem.RADLOST_ON_DEATH);
}
if (event.getSource() instanceof TGDamageSource) {
TGDamageSource tgs = (TGDamageSource)event.getSource();
if (tgs.deathType != DeathType.DEFAULT) {
if(Math.random()<tgs.goreChance) {
if (EntityDeathUtils.hasSpecialDeathAnim(entity, tgs.deathType)) {
//System.out.println("Send packet!");
TGPackets.network.sendToAllAround(new PacketEntityDeathType(entity, tgs.deathType), TGPackets.targetPointAroundEnt(entity, 100.0f));
}
}
}
}
}
}
@SubscribeEvent(priority=EventPriority.NORMAL, receiveCanceled=false)
public static void onEntityJoinWorld(EntityJoinWorldEvent event){
if (!event.getEntity().world.isRemote){
if(event.getEntity() instanceof EntityPlayer){
EntityPlayer ply = (EntityPlayer) event.getEntity();
TGExtendedPlayer props = TGExtendedPlayer.get(ply);
if (props!=null){
//System.out.println("SENT EXTENDED PLAYER SYNC");
//TGPackets.network.sendToDimension(new PacketTGExtendedPlayerSync(props, false), event.entity.dimension);
TGPackets.network.sendTo(new PacketTGExtendedPlayerSync(ply,props, true), (EntityPlayerMP) ply);
ply.getDataManager().set(TGExtendedPlayer.DATA_FACE_SLOT, props.tg_inventory.getStackInSlot(TGPlayerInventory.SLOT_FACE));
ply.getDataManager().set(TGExtendedPlayer.DATA_BACK_SLOT, props.tg_inventory.getStackInSlot(TGPlayerInventory.SLOT_BACK));
ply.getDataManager().set(TGExtendedPlayer.DATA_HAND_SLOT, props.tg_inventory.getStackInSlot(TGPlayerInventory.SLOT_HAND));
//ply.getDataWatcher().updateObject(TechgunsExtendedPlayerProperties.DATA_WATCHER_ID_FACESLOT, props.TG_inventory.inventory[TGPlayerInventory.SLOT_FACE]);
//ply.getDataWatcher().updateObject(TechgunsExtendedPlayerProperties.DATA_WATCHER_ID_BACKSLOT, props.TG_inventory.inventory[TGPlayerInventory.SLOT_BACK]);
}
} else if (event.getEntity() instanceof TGDummySpawn){
//
TGSpawnManager.handleSpawn(event.getWorld(), event.getEntity());
event.setCanceled(true);
}
}
}
@SubscribeEvent(priority=EventPriority.NORMAL)
public static void onStartTracking(PlayerEvent.StartTracking event){
if(event.getEntityPlayer().world.isRemote){
TGPackets.network.sendToServer(new PacketRequestTGPlayerSync(event.getEntityPlayer()));
}
}
@SubscribeEvent(priority=EventPriority.NORMAL)
public static void onStopTracking(PlayerEvent.StopTracking event){
if(event.getEntityPlayer().world.isRemote){
TGExtendedPlayer props = TGExtendedPlayer.get(event.getEntityPlayer());
if(props!=null){
props.setJumpkeyPressed(false);
props.isGliding=false;
}
}
}
@SideOnly(Side.CLIENT)
@SubscribeEvent
public static void onTextureStitch(TextureStitchEvent event) {
event.getMap().registerSprite(SlotTG.BACKSLOT_TEX);
event.getMap().registerSprite(SlotTG.FACESLOT_TEX);
event.getMap().registerSprite(SlotTG.HANDSLOT_TEX);
event.getMap().registerSprite(SlotTG.FOODSLOT_TEX);
event.getMap().registerSprite(SlotTG.HEALSLOT_TEX);
event.getMap().registerSprite(SlotTG.AMMOSLOT_TEX);
event.getMap().registerSprite(SlotTG.AMMOEMPTYSLOT_TEX);
event.getMap().registerSprite(SlotTG.BOTTLESLOT_TEX);
event.getMap().registerSprite(SlotTG.TURRETGUNSLOT_TEX);
event.getMap().registerSprite(SlotTG.TURTETARMORSLOT_TEX);
event.getMap().registerSprite(SlotFabricator.FABRICATOR_SLOTTEX_WIRES);
event.getMap().registerSprite(SlotFabricator.FABRICATOR_SLOTTEX_POWDER);
event.getMap().registerSprite(SlotFabricator.FABRICATOR_SLOTTEX_PLATE);
event.getMap().registerSprite(SlotTG.INGOTSLOT_TEX);
event.getMap().registerSprite(SlotTG.INGOTDARKSLOT_TEX);
RenderDoor3x3Fast.stitchTextures(event.getMap());
}
@SideOnly(Side.CLIENT)
@SubscribeEvent
public static void onModelBake(ModelBakeEvent event) {
RenderGrenade40mmProjectile.initModel();
RenderAttackHelicopter.initModels();
RenderDoor3x3Fast.initModels();
}
@SideOnly(Side.CLIENT)
@SubscribeEvent
public static void onRenderHand(RenderHandEvent event) {
float t = 1.0f;
EntityPlayer ply = ClientProxy.get().getPlayerClient();
ItemStack stack = ply.getActiveItemStack();
if(!stack.isEmpty() && ((stack.getItem() instanceof GenericGunCharge && ((GenericGunCharge)stack.getItem()).hasRightClickAction()) || stack.getItem() instanceof GenericGrenade)) {
EnumHand hand = ply.getActiveHand();
ItemRenderer itemrenderer = Minecraft.getMinecraft().getItemRenderer();
try {
ClientProxy cp = ClientProxy.get();
if(hand==EnumHand.MAIN_HAND) {
if(cp.Field_ItemRenderer_equippedProgressMainhand.getFloat(itemrenderer)<t) {
cp.Field_ItemRenderer_equippedProgressMainhand.setFloat(itemrenderer, t);
cp.Field_ItemRenderer_prevEquippedProgressMainhand.setFloat(itemrenderer, t);
}
} else {
if(cp.Field_ItemRenderer_equippedProgressOffhand.getFloat(itemrenderer)<t) {
cp.Field_ItemRenderer_equippedProgressOffhand.setFloat(itemrenderer, t);
cp.Field_ItemRenderer_prevEquippedProgressOffhand.setFloat(itemrenderer, t);
}
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} /*else {
if(!ply.getHeldItemMainhand().isEmpty() && ply.getHeldItemMainhand().getItem() instanceof IGenericGunMelee) {
ItemRenderer itemrenderer = Minecraft.getMinecraft().getItemRenderer();
float f = ply.getCooledAttackStrength(1.0f);
System.out.println("f:"+f);
if (f<1f) {
try {
System.out.println("Set to 1");
Field_ItemRenderer_equippedProgressMainhand.setFloat(itemrenderer, 1.0f);
Field_ItemRenderer_prevEquippedProgressMainhand.setFloat(itemrenderer, 1.0f);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}*/
}
@SideOnly(Side.CLIENT)
@SubscribeEvent
public static void onRenderWorldLast(RenderWorldLastEvent event) {
// GLStateSnapshot states = new GLStateSnapshot();
//System.out.println("***********BEFORE**********");
//states.printDebug();
ClientProxy.get().particleManager.renderParticles(Minecraft.getMinecraft().getRenderViewEntity(), event.getPartialTicks());
// states.restore();
//System.out.println("<<<<<<<<<<<AFTER>>>>>>>>>>>>");
//new GLStateSnapshot().printDebug();
GlStateManager.disableBlend();
GlStateManager.blendFunc(SourceFactor.ONE, DestFactor.ZERO);
GlStateManager.enableDepth();
GlStateManager.depthMask(true);
GlStateManager.enableCull();
GlStateManager.disableLighting();
OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, 0, 240f);
}
@SubscribeEvent
public static void onCraftEvent(ItemCraftedEvent event) {
if(event.crafting.getItem() instanceof GenericGun) {
boolean hasGun=false;
boolean hasAmmo=false;
boolean hasInvalid=false;
ItemStack gun=ItemStack.EMPTY;
for(int i=0; i<event.craftMatrix.getSizeInventory();i++) {
ItemStack stack = event.craftMatrix.getStackInSlot(i);
if(!stack.isEmpty()) {
if( stack.getItem() instanceof GenericGun) {
if(!hasGun) {
hasGun=true;
gun=stack;
} else {
hasInvalid=true;
break;
}
} else if (stack.getItem() instanceof ITGSpecialSlot && ((ITGSpecialSlot)stack.getItem()).getSlot(stack)==TGSlotType.AMMOSLOT){
if(!hasAmmo) {
hasAmmo=true;
} else {
hasInvalid=true;
break;
}
} else {
hasInvalid=true;
break;
}
}
}
if(!hasInvalid && hasGun && hasAmmo) {
//Was an Ammo change recipe!
GenericGun g = (GenericGun) gun.getItem();
List<ItemStack> items = g.getAmmoOnUnload(gun);
items.forEach(i -> {
int amount = InventoryUtil.addAmmoToPlayerInventory(event.player, i);
if(amount>0 && !event.player.world.isRemote) {
ItemStack it = i.copy();
it.setCount(amount);
event.player.world.spawnEntity(new EntityItem(event.player.world, event.player.posX, event.player.posY, event.player.posZ, it));
}
});
}
}
}
@SubscribeEvent(priority=EventPriority.NORMAL, receiveCanceled=false)
public static void onPlayerDrops(PlayerDropsEvent event){
EntityPlayer ply = event.getEntityPlayer();
TGExtendedPlayer props = TGExtendedPlayer.get(ply);
if(props!=null){
props.dropInventory(ply);
}
}
public static Method Block_getSilkTouchDrop = ReflectionHelper.findMethod(Block.class, "getSilkTouchDrop", "func_180643_i", IBlockState.class);
@SubscribeEvent
public static void onBlockDrops(HarvestDropsEvent event) {
EntityPlayer ply = event.getHarvester();
if(ply!=null) {
ItemStack stack = ply.getHeldItemMainhand();
if(!stack.isEmpty() && stack.getItem() instanceof MiningDrill && ply.isSneaking()) {
IBlockState state = event.getState();
if (state.getBlock().canSilkHarvest(ply.world, event.getPos(), state, ply)){
MiningDrill md = (MiningDrill) stack.getItem();
if (md.getAmmoLeft(stack)>0) {
List drops = event.getDrops();
drops.clear();
try {
drops.add(Block_getSilkTouchDrop.invoke(state.getBlock(), state));
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
event.setDropChance(1.0f);
}
}
}
}
}
//stop XP drop on silk harvesting with mining drill
@SubscribeEvent(priority=EventPriority.HIGH)
public static void onBlockBreakEvent(BlockEvent.BreakEvent event) {
EntityPlayer ply = event.getPlayer();
if(ply!=null) {
ItemStack stack = ply.getHeldItemMainhand();
if(!stack.isEmpty() && stack.getItem() instanceof MiningDrill && ply.isSneaking()) {
event.setExpToDrop(0);
}
}
}
@SubscribeEvent(priority=EventPriority.HIGH) //run before regular drop events
public static void MilitaryCrateDrops(HarvestDropsEvent event) {
IBlockState state = event.getState();
if(state.getBlock()==TGBlocks.MILITARY_CRATE && !event.isSilkTouching() && !event.getWorld().isRemote) {
BlockPos pos = event.getPos();
EntityPlayer ply = event.getHarvester();
if (ply!=null) {
int fortune = event.getFortuneLevel();
LootTable loottable = ply.world.getLootTableManager().getLootTableFromLocation(TGBlocks.MILITARY_CRATE.getLootableForState(state));
LootContext lootcontext = new LootContext.Builder((WorldServer) ply.world).withLuck(fortune).withPlayer(ply).build();
event.getDrops().clear();
for (ItemStack itemstack : loottable.generateLootForPools(ply.world.rand, lootcontext))
{
event.getDrops().add(itemstack);
}
}
}
}
/*@SubscribeEvent
public static void damageTest(LivingHurtEvent event) {
if (event.getEntityLiving() instanceof EntityPlayer) {
System.out.println("Attacking"+event.getEntityLiving()+" for "+event.getAmount() +" with "+event.getSource());
}
}*/
@SideOnly(Side.CLIENT)
@SubscribeEvent
public static void onBlockHighlight(DrawBlockHighlightEvent event) {
EntityPlayer ply = event.getPlayer();
ItemStack item = ply.getHeldItemMainhand();
if(!ply.isSneaking() && !item.isEmpty() && item.getItem() instanceof GenericGunMeleeCharge) {
GenericGunMeleeCharge g = (GenericGunMeleeCharge) item.getItem();
if (g.getMiningRadius(item)>0 && g.getAmmoLeft(item)>0) {
RayTraceResult target = event.getTarget();
if(target!=null && target.typeOfHit == Type.BLOCK) {
BlockPos p = target.getBlockPos();
List<BlockPos> otherblocks = BlockUtils.getBlockPlaneAroundAxisForMining(ply.world, ply, p, target.sideHit.getAxis(), g.getMiningRadius(item), false, g, item);
otherblocks.forEach(b -> {
RayTraceResult result = new RayTraceResult(new Vec3d(b.getX()+0.5d, b.getY()+0.5d, b.getZ()+0.5d),target.sideHit,b);
event.getContext().drawSelectionBox(ply, result, 0, event.getPartialTicks());
});
}
}
}
}
@SubscribeEvent
public static void onItemSwitch(LivingEquipmentChangeEvent event) {
if (event.getSlot()==EntityEquipmentSlot.MAINHAND || event.getSlot()==EntityEquipmentSlot.OFFHAND) {
boolean fromEffect=false;
boolean toEffect =false;
if (!event.getTo().isEmpty() && event.getTo().getItem() instanceof GenericGun) {
if(((GenericGun)event.getTo().getItem()).hasAmbientEffect()){
toEffect=true;
}
}
if (!event.getFrom().isEmpty() && event.getFrom().getItem() instanceof GenericGun) {
if(((GenericGun)event.getFrom().getItem()).hasAmbientEffect()){
fromEffect=true;
}
}
if(fromEffect||toEffect){
EnumHand hand = EnumHand.MAIN_HAND;
if (event.getSlot()==EntityEquipmentSlot.OFFHAND) {
hand=EnumHand.OFF_HAND;
}
TGPackets.network.sendToDimension(new PacketNotifyAmbientEffectChange(event.getEntityLiving(), hand), event.getEntityLiving().world.provider.getDimension());
}
}
}
@Optional.Method(modid="albedo")
@SideOnly(Side.CLIENT)
@SubscribeEvent
public static void onGatherLightsEvent(GatherLightsEvent event) {
ClientProxy cp = ClientProxy.get();
for (int i=0;i<cp.activeLightPulses.size();i++) {
event.add(cp.activeLightPulses.get(i).provideLight());
}
//ClientProxy.get().activeLightPulses.forEach(l -> event.getLightList().add(l.provideLight()));
}
/*@SubscribeEvent
public static void itemPickupRadiation(EntityItemPickupEvent event) {
ItemStack stack = event.getItem().getItem();
if(!stack.isEmpty()) {
ItemRadiationData data = ItemRadiationRegistry.getRadiationDataFor(stack);
if(data!=null) {
event.getEntityPlayer().addPotionEffect(new PotionEffect(TGRadiationSystem.radiation_effect, data.radduration, data.radamount-1, false,false));
}
}
}*/
@SubscribeEvent
@SideOnly(Side.CLIENT)
public static void ItemRadiationTooltip(ItemTooltipEvent event) {
ItemStack stack = event.getItemStack();
if(!stack.isEmpty()) {
ItemRadiationData data = ItemRadiationRegistry.getRadiationDataFor(stack);
if(data!=null && data.radamount>0) {
event.getToolTip().add(ChatFormatting.GREEN+TextUtil.trans("techguns.radiation")+" "+TextUtil.trans("potion.potency."+(data.radamount-1)));
}
}
}
@SubscribeEvent
public static void onEntityConstruction(EntityConstructing event) {
if(event.getEntity() instanceof EntityLivingBase) {
EntityLivingBase elb = (EntityLivingBase) event.getEntity();
elb.getAttributeMap().registerAttribute(TGRadiation.RADIATION_RESISTANCE).setBaseValue(0);
}
}
}
| 412 | 0.924644 | 1 | 0.924644 | game-dev | MEDIA | 0.977743 | game-dev | 0.91559 | 1 | 0.91559 |
Mindwerks/XLEngine | 16,989 | fileformats/Location_Daggerfall.cpp | #include "Location_Daggerfall.h"
#include "../EngineSettings.h"
#include "../fileformats/ArchiveTypes.h"
#include "../fileformats/ArchiveManager.h"
#include "../memory/ScratchPad.h"
#include <cstdio>
#include <cstdlib>
#include <memory.h>
#include <cstring>
#include <cassert>
namespace
{
#pragma pack(push)
#pragma pack(1)
struct LocationRec
{
int32_t oneValue;
int16_t NullValue1;
int8_t NullValue2;
int32_t XPosition;
int32_t NullValue3;
int32_t YPosition;
int32_t LocType;
int32_t Unknown2;
int32_t Unknown3;
int16_t oneValue2;
uint16_t LocationID;
int32_t NullValue4;
int16_t Unknown4;
int32_t Unknown5;
char NullValue[26];
char LocationName[32];
char Unknowns[9];
int16_t PostRecCount;
};
#pragma pack(pop)
const char _aszRMBHead[][5]=
{
"TVRN",
"GENR",
"RESI",
"WEAP",
"ARMR",
"ALCH",
"BANK",
"BOOK",
"CLOT",
"FURN",
"GEMS",
"LIBR",
"PAWN",
"TEMP",
"TEMP",
"PALA",
"FARM",
"DUNG",
"CAST",
"MANR",
"SHRI",
"RUIN",
"SHCK",
"GRVE",
"FILL",
"KRAV",
"KDRA",
"KOWL",
"KMOO",
"KCAN",
"KFLA",
"KHOR",
"KROS",
"KWHE",
"KSCA",
"KHAW",
"MAGE",
"THIE",
"DARK",
"FIGH",
"CUST",
"WALL",
"MARK",
"SHIP",
"WITC"
};
const char _aszRMBTemple[][3]=
{
"A0",
"B0",
"C0",
"D0",
"E0",
"F0",
"G0",
"H0",
};
#if 0 /* unneeded? */
const char _aszRMBChar[][3]=
{
"AA",
"AA",
"AA",
"AA",
/*
"DA",
"DA",
"DA",
"DA",
"DA",
*/
"AA",
"AA",
"AA",
"AA",
"AA",
//
"AL",
"DL",
"AM",
"DM",
"AS",
"DS",
"AA",
"DA",
};
#endif
const char _aszRMBCharQ[][3]=
{
"AA",
"BA",
"AL",
"BL",
"AM",
"BM",
"AS",
"BS",
"GA",
"GL",
"GM",
"GS"
};
} // namespace
uint32_t WorldMap::m_uRegionCount;
std::unique_ptr<Region_Daggerfall[]> WorldMap::m_pRegions;
LocationMap WorldMap::m_MapLoc;
std::map<uint64_t, WorldCell *> WorldMap::m_MapCell;
NameLocationMap WorldMap::m_MapNames;
bool WorldMap::m_bMapLoaded = false;
///////////////////////////////////////////////////////
// Location
///////////////////////////////////////////////////////
Location_Daggerfall::Location_Daggerfall()
{
m_bLoaded = false;
m_dungeonBlockCnt = 0;
m_startDungeonBlock = 0;
}
Location_Daggerfall::~Location_Daggerfall()
{
}
void Location_Daggerfall::LoadLoc(const char *pData, int index, const int RegIdx, LocationMap &mapLoc, NameLocationMap &mapNames)
{
int nPreRecCount = *((const int*)&pData[index]);
index += 4;
const uint8_t *PreRecords = nullptr;
if(nPreRecCount > 0)
{
PreRecords = (const uint8_t*)&pData[index];
index += nPreRecCount*6;
}
const LocationRec *pLocation = (const LocationRec*)&pData[index];
index += sizeof(LocationRec);
m_LocationID = pLocation->LocationID;
m_OrigX = pLocation->XPosition;
m_OrigY = pLocation->YPosition;
m_x = (float)pLocation->XPosition / 4096.0f;
m_y = (float)pLocation->YPosition / 4096.0f;
strcpy(m_szName, pLocation->LocationName);
uint64_t uKey = (uint64_t)((int32_t)m_y>>3)<<32ULL |
((uint64_t)((int32_t)m_x>>3)&0xffffffff);
mapLoc[uKey] = this;
m_BlockWidth = 0;
m_BlockHeight = 0;
m_pBlockNames = nullptr;
if ( pLocation->LocType == 0x00008000 )
{
//town or exterior location.
index += 5; //unknown...
index += 26*pLocation->PostRecCount; //post records.
index += 32; //"Another name"
/*int locID2 = *((const int*)&pData[index]);*/ index += 4;
index += 4; //unknowns
char BlockWidth = pData[index]; index++;
char BlockHeight = pData[index]; index++;
index += 7; //unknowns
const char *BlockFileIndex = &pData[index]; index += 64;
const char *BlockFileNumber = &pData[index]; index += 64;
const uint8_t *BlockFileChar = (const uint8_t*)&pData[index]; index += 64;
m_BlockWidth = BlockWidth;
m_BlockHeight = BlockHeight;
m_pBlockNames.reset(new LocName[BlockWidth*BlockHeight]);
char szName[64];
for (int by=0; by<BlockHeight; by++)
{
for (int bx=0; bx<BlockWidth; bx++)
{
int bidx = by*BlockWidth + bx;
int bfileidx = BlockFileIndex[bidx];
if ( BlockFileIndex[bidx] == 13 || BlockFileIndex[bidx] == 14 )
{
if ( BlockFileChar[bidx] > 0x07 )
{
sprintf(szName, "%s%s%s.RMB", _aszRMBHead[bfileidx], "GA", _aszRMBTemple[BlockFileNumber[bidx]&0x07]);
}
else
{
sprintf(szName, "%s%s%s.RMB", _aszRMBHead[bfileidx], "AA", _aszRMBTemple[BlockFileNumber[bidx]&0x07]);
}
if ( !ArchiveManager::GameFile_Open(ARCHIVETYPE_BSA, "BLOCKS.BSA", szName) )
{
char szNameTmp[32];
sprintf(szNameTmp, "%s??%s.RMB", _aszRMBHead[bfileidx], _aszRMBTemple[BlockFileNumber[bidx]&0x07]);
ArchiveManager::GameFile_SearchForFile(ARCHIVETYPE_BSA, "BLOCKS.BSA", szNameTmp, szName);
}
ArchiveManager::GameFile_Close();
}
else
{
int Q = BlockFileChar[bidx]/16;
if ( BlockFileIndex[bidx] == 40 ) //"CUST"
{
if ( RegIdx == 20 ) //Sentinel logic
{
Q = 8;
}
else
{
Q = 0;
}
}
else if ( RegIdx == 23 )
{
if (Q>0) Q--;
}
sprintf(szName, "%s%s%02d.RMB", _aszRMBHead[bfileidx], _aszRMBCharQ[Q], BlockFileNumber[bidx]);
assert(Q < 12);
//does this file exist?
if ( !ArchiveManager::GameFile_Open(ARCHIVETYPE_BSA, "BLOCKS.BSA", szName) )
{
char szNameTmp[32];
sprintf(szNameTmp, "%s??%02d.RMB", _aszRMBHead[bfileidx], BlockFileNumber[bidx]);
ArchiveManager::GameFile_SearchForFile(ARCHIVETYPE_BSA, "BLOCKS.BSA", szNameTmp, szName);
}
ArchiveManager::GameFile_Close();
}
strcpy(m_pBlockNames[bidx].szName, szName);
}
}
}
//Add to map.
mapNames[m_szName] = this;
}
///////////////////////////////////////////////////////
// Region
///////////////////////////////////////////////////////
Region_Daggerfall::Region_Daggerfall()
{
}
Region_Daggerfall::~Region_Daggerfall()
{
}
///////////////////////////////////////////////////////
// World Map
///////////////////////////////////////////////////////
void WorldMap::Init()
{
}
void WorldMap::Destroy()
{
m_bMapLoaded = false;
m_uRegionCount = 0;
m_pRegions = nullptr;
}
//load cached data from disk if present.
bool WorldMap::Load()
{
bool bSuccess = true;
if(!m_bMapLoaded)
{
bSuccess = Cache();
m_bMapLoaded = true;
}
return bSuccess;
}
//generate the cached data.
bool WorldMap::Cache()
{
//step 1: compute the total number of locations for the entire world...
char szFileName[64];
uint32_t TotalLocCount=0;
ScratchPad::FreeFrame();
char *pData = (char *)ScratchPad::AllocMem( 1024*1024 );
//Load global data.
m_uRegionCount = 62;
m_pRegions.reset(new Region_Daggerfall[m_uRegionCount]);
for (int r=0; r<62; r++)
{
sprintf(szFileName, "MAPNAMES.0%02d", r);
if ( ArchiveManager::GameFile_Open(ARCHIVETYPE_BSA, "MAPS.BSA", szFileName) )
{
m_pRegions[r].m_uLocationCount = 0;
m_pRegions[r].m_pLocations = nullptr;
uint32_t uLength = ArchiveManager::GameFile_GetLength();
if ( uLength == 0 )
{
ArchiveManager::GameFile_Close();
continue;
}
ArchiveManager::GameFile_Read(pData, uLength);
ArchiveManager::GameFile_Close();
m_pRegions[r].m_uLocationCount = *((unsigned int *)pData);
m_pRegions[r].m_pLocations.reset(
new Location_Daggerfall[m_pRegions[r].m_uLocationCount]);
TotalLocCount += m_pRegions[r].m_uLocationCount;
}
}
ScratchPad::FreeFrame();
for (int r=0; r<(int)m_uRegionCount; r++)
{
sprintf(szFileName, "MAPTABLE.0%02d", r);
if ( ArchiveManager::GameFile_Open(ARCHIVETYPE_BSA, "MAPS.BSA", szFileName) )
{
uint32_t uLength = ArchiveManager::GameFile_GetLength();
if ( uLength == 0 )
{
ArchiveManager::GameFile_Close();
continue;
}
char *pData = (char *)ScratchPad::AllocMem(uLength);
if ( pData )
{
ArchiveManager::GameFile_Read(pData, uLength);
ArchiveManager::GameFile_Close();
int index = 0;
for (uint32_t i=0; i<m_pRegions[r].m_uLocationCount; i++)
{
int mapID = *((int *)&pData[index]); index += 4;
uint8_t U1 = *((uint8_t *)&pData[index]); index++;
uint32_t longType = *((uint32_t *)&pData[index]); index += 4;
m_pRegions[r].m_pLocations[i].m_Lat = ( *((short *)&pData[index]) )&0xFFFF; index += 2;
m_pRegions[r].m_pLocations[i].m_Long = longType&0xFFFF;
uint16_t U2 = *((uint16_t *)&pData[index]); index += 2; //unknown
uint32_t U3 = *((uint32_t *)&pData[index]); index += 4; //unknown
m_pRegions[r].m_pLocations[i].m_locType = longType >> 17;
}
}
ScratchPad::FreeFrame();
}
sprintf(szFileName, "MAPPITEM.0%02d", r);
if ( ArchiveManager::GameFile_Open(ARCHIVETYPE_BSA, "MAPS.BSA", szFileName) )
{
uint32_t uLength = ArchiveManager::GameFile_GetLength();
if ( uLength == 0 )
{
ArchiveManager::GameFile_Close();
continue;
}
char *pData = (char *)ScratchPad::AllocMem(uLength);
if ( pData )
{
ArchiveManager::GameFile_Read(pData, uLength);
ArchiveManager::GameFile_Close();
//pData = region data.
uint32_t *offsets = (uint32_t *)pData;
int nLocationCount = (int)m_pRegions[r].m_uLocationCount;
int base_index = 4*nLocationCount;
int index;
for (int i=0; i<nLocationCount; i++)
{
index = base_index + offsets[i];
m_pRegions[r].m_pLocations[i].LoadLoc(pData, index, r, m_MapLoc, m_MapNames);
}
}
}
ScratchPad::FreeFrame();
sprintf(szFileName, "MAPDITEM.0%02d", r);
if ( ArchiveManager::GameFile_Open(ARCHIVETYPE_BSA, "MAPS.BSA", szFileName) )
{
uint32_t uLength = ArchiveManager::GameFile_GetLength();
if ( uLength == 0 )
{
ArchiveManager::GameFile_Close();
continue;
}
char *pData = (char *)ScratchPad::AllocMem(uLength);
if ( pData )
{
ArchiveManager::GameFile_Read(pData, uLength);
ArchiveManager::GameFile_Close();
//pData = region data.
int index = 0;
uint32_t count = *((uint32_t*)&pData[index]); index += 4;
struct DungeonOffset
{
uint32_t Offset;
uint16_t IsDungeon;
uint16_t ExteriorLocID;
};
DungeonOffset *pOffsets = (DungeonOffset *)&pData[index]; index += 8*count;
int base_index = index;
for (int i=0; i<(int)count; i++)
{
index = base_index + pOffsets[i].Offset;
//find matching exterior record...
Location_Daggerfall *pCurLoc = nullptr;
for (int e=0; e<(int)m_pRegions[r].m_uLocationCount; e++)
{
if ( m_pRegions[r].m_pLocations[e].m_LocationID == pOffsets[i].ExteriorLocID )
{
pCurLoc = &m_pRegions[r].m_pLocations[e];
break;
}
}
assert(pCurLoc);
int nPreRecCount = *((int *)&pData[index]); index += 4;
uint8_t *PreRecords = nullptr;
if ( nPreRecCount > 0 )
{
PreRecords = (uint8_t *)&pData[index]; index += nPreRecCount*6;
}
LocationRec *pLocation = (LocationRec *)&pData[index];
index += sizeof(LocationRec);
assert( pLocation->LocType == 0 );
if ( pLocation->LocType == 0 )
{
pCurLoc->m_waterHeight = (short)pLocation->Unknown5;
if ( pLocation->Unknown3&1 )
{
pCurLoc->m_waterHeight = -256000;
}
index += 8;//unknowns...
uint16_t blockCnt = *((uint16_t *)&pData[index]); index += 2;
index += 5; //unknown
pCurLoc->m_dungeonBlockCnt = blockCnt;
pCurLoc->m_startDungeonBlock = 0;
pCurLoc->m_pDungeonBlocks.reset(
new Location_Daggerfall::DungeonBlock[blockCnt]);
bool bStartFound = false;
for (uint32_t b=0; b<blockCnt; b++)
{
char X = *((uint8_t *)&pData[index]); index++;
char Y = *((uint8_t *)&pData[index]); index++;
uint16_t BlockNumStartIndex = *((uint16_t *)&pData[index]); index+=2;
int blockNum = BlockNumStartIndex&1023;
bool IsStartBlock = (BlockNumStartIndex&1024) ? true : false;
uint32_t blockIndex = (BlockNumStartIndex>>11)&0xff;
//now decode the string name...
char bIdxTable[] = { 'N', 'W', 'L', 'S', 'B', 'M' };
char szName[32];
sprintf(szName, "%c%07d.RDB", bIdxTable[blockIndex], blockNum);
if ( IsStartBlock )
{
pCurLoc->m_startDungeonBlock = b;
bStartFound = true;
}
strcpy( pCurLoc->m_pDungeonBlocks[b].szName, szName );
pCurLoc->m_pDungeonBlocks[b].x = X;
pCurLoc->m_pDungeonBlocks[b].y = Y;
}
assert( bStartFound );
}
}
}
ScratchPad::FreeFrame();
}
}
//just to make sure...
ScratchPad::FreeFrame();
m_bMapLoaded = true;
return true;
}
Location_Daggerfall *WorldMap::GetLocation(int32_t x, int32_t y)
{
uint64_t uKey = ((uint64_t)y<<32ULL) | ((uint64_t)x&0xffffffff);
auto iLoc = m_MapLoc.find(uKey);
if(iLoc != m_MapLoc.end())
return iLoc->second;
return nullptr;
}
Location_Daggerfall *WorldMap::GetLocation(const char *pszName)
{
auto iLoc = m_MapNames.find(pszName);
if(iLoc != m_MapNames.end())
return iLoc->second;
return nullptr;
}
void WorldMap::SetWorldCell(int32_t x, int32_t y, WorldCell *pCell)
{
uint64_t uKey = ((uint64_t)y<<32ULL) | ((uint64_t)x&0xffffffff);
m_MapCell[uKey] = pCell;
}
WorldCell *WorldMap::GetWorldCell(int32_t x, int32_t y)
{
uint64_t uKey = ((uint64_t)y<<32ULL) | ((uint64_t)x&0xffffffff);
auto iLoc = m_MapCell.find(uKey);
if(iLoc != m_MapCell.end())
return iLoc->second;
return nullptr;
}
| 412 | 0.920258 | 1 | 0.920258 | game-dev | MEDIA | 0.946759 | game-dev | 0.885773 | 1 | 0.885773 |
jswigart/omni-bot | 8,148 | Installer/Files/rtcw/scripts/goals/goal_deliversupplies.gm | // This script contains functionality to allow medic bots to deliver ammo to people that request it.
// These parameters are required
this.Name = "DeliverSupplies"; // The name of the goal.
this.Parent = "HighLevel"; // The name of the parent. This setting determines where in the state tree the goal will reside in.
this.KillAndRevive = true;
this.AlwaysRecieveEvents = true;
// possible options
this.LimitToClass(CLASS.LIEUTENANT, CLASS.MEDIC);
this.DeliverPriority = 1.1;
this.RangeLimit = 1500;
// states
this.DELIVER_PACKS = 1;
this.KILL_TARGET = 2;
this.SWITCH_TO_SYRINGE = 3;
this.REVIVE_TARGET = 4;
this.Initialize = function()
{
this.Respond = false;
Util.ScriptDebugPrint(this.Name, "initialized");
};
this.GetPriority = function()
{
block( this.Bot.Name + "_deliversupplies" );
sleep(0.5);
if ( this.Bot.RevivedTargetEnt ) {
this.TargetEntity = this.Bot.RevivedTargetEnt;
this.Bot.RevivedTargetEnt = null;
this.Supply = WEAPON.MEDKIT;
//this.Bot.Say("delivering to " + GetEntName(this.TargetEntity));
// cs: if we've activated from a revive goal, lets give it a higher priority than normal.
this.Priority = this.DeliverPriority + 0.2;
}
};
this.Enter = function()
{
this.FriendlyFire = GetCvar("g_friendlyfire");
this.PacksThrown = 0;
this.TargetPosition = GetEntPosition(this.TargetEntity);
this.StartPosition = this.TargetPosition; // don't chase them across the entire map
this.OnTarget = false;
if ( this.Respond )
{
targetName = GetEntName(this.TargetEntity);
if(this.Supply == WEAPON.AMMO_PACK)
{
this.Bot.SayTeam("Coming with Ammo, ^7", targetName, "^5!^2");
}
else if(this.Supply == WEAPON.MEDKIT)
{
this.Bot.SayTeam("Coming with Health, ^7", targetName, "^5!^2");
}
}
// Set up some finish criteria
this.AddFinishCriteria(this.TargetEntity,"deleted");
this.AddFinishCriteria(this.Bot.GetGameEntity(),"not weaponcharged", this.Supply);
this.AddFinishCriteria(this.TargetEntity,"hasentflag",ENTFLAG.LIMBO);
this.KillTarget = false;
if ( this.Supply == WEAPON.MEDKIT && this.FriendlyFire == 1 && this.KillAndRevive == true
&& this.Bot.HasAmmo(WEAPON.SYRINGE) && this.TargetEntity && !GetEntFlags(this.TargetEntity, ENTFLAG.CARRYINGGOAL) )
{
this.KillTarget = true;
this.AddFinishCriteria(this.TargetEntity,"health greaterthan",75);
}
if ( !this.KillTarget )
{
this.AddFinishCriteria(this.TargetEntity,"health lessthan",1);
}
this.DynamicGotoThread = this.ForkThread(this.DynamicGoto);
};
this.Exit = function()
{
if ( this.DynamicGotoThread )
{ this.KillThread(this.DynamicGotoThread); }
this.TargetEntity = null;
this.TargetPosition = null;
this.OnTarget = false;
this.Bot.KillingForRevive = false; // allow appropriate voice chats again
};
this.DynamicGoto = function()
{
if(this.Goto(this.TargetPosition, 128.f) == EVENT.PATH_SUCCESS)
{
this.OnTarget = true;
}
else
{
this.Finished();
}
};
this.Update = function()
{
while(1)
{
entPos = GetEntPosition(this.TargetEntity);
if ( entPos.IsZero() )
{ this.Finished(); }
// reset if they chose a closer target
if ( this.ChangedTarget ) {
this.TargetPosition = entPos;
this.ChangedTarget = false;
if ( this.DynamicGotoThread )
{ this.KillThread(this.DynamicGotoThread); }
this.DynamicGotoThread = this.ForkThread(this.DynamicGoto);
}
dStart = DistanceBetween(entPos,this.StartPosition);
if ( dStart > 1500 )
{
//stop chasing
//this.Bot.SayTeam("stop moving if you want packs " + GetEntName(this.TargetEntity));
this.Finished();
}
d = DistanceBetween(entPos,this.TargetPosition);
if( d > 128 )
{
if ( this.DynamicGotoThread )
{ this.KillThread(this.DynamicGotoThread); }
this.TargetPosition = entPos;
this.DynamicGotoThread = this.ForkThread(this.DynamicGoto);
}
if ( this.OnTarget )
{
this.Priority = 2.0;
// aim at target while waiting for weapon change
pos = GetEntEyePosition(this.TargetEntity);
this.AddAimRequest(Priority.High, "position",pos);
if ( !this.KillTarget ) {
this.State = this.DELIVER_PACKS;
this.AddWeaponRequest(Priority.High, this.Supply);
this.BlockForWeaponChange(this.Supply);
}
else {
hlth = Util.GetEntHealth(this.TargetEntity);
// cs: there is no finish criteria set when KillAndRevive is enabled
// so we need to make sure that they are still alive.
// a lack of finish criteria for health isn't critical because the medic will
// have needed to be here to revive anyway.
if (hlth < 1) {
this.Finished();
}
else if (hlth < 37) {
this.Bot.KillingForRevive = true; // for voice chats
this.State = this.KILL_TARGET;
}
else {
this.State = this.DELIVER_PACKS;
}
}
while(this.PacksThrown < 2 && this.Bot.IsWeaponCharged(this.Supply))
{
switch(this.State)
{
case this.DELIVER_PACKS:
{
this.UpdateDeliverPacks();
}
case this.KILL_TARGET:
{
this.UpdateKillTarget();
}
case this.SWITCH_TO_SYRINGE:
{
this.UpdateSwitchToSyringe();
}
case this.REVIVE_TARGET:
{
this.UpdateReviveTarget();
}
}
yield();
}
this.Finished();
}
yield();
}
};
this.UpdateDeliverPacks = function()
{
if ( this.Bot.GetCurrentWeapon() != this.Supply ) {
this.AddWeaponRequest(Priority.High, this.Supply);
this.BlockForWeaponChange(this.Supply);
}
pos = GetEntEyePosition(this.TargetEntity);
if (pos)
{
//move towards them while giving packs
this.AddAimRequest(Priority.High, "position",pos);
this.Bot.MoveTowards(pos);
this.Bot.HoldButton(BTN.ATTACK1, 0.25);
}
else
{
this.Finished();
}
sleep(0.25);
};
this.UpdateKillTarget = function()
{
hlth = Util.GetEntHealth(this.TargetEntity);
if ( hlth < 1 ) {
this.Bot.KilledForRevive = true; // for voice chats
this.State = this.SWITCH_TO_SYRINGE;
return;
}
pos = GetEntEyePosition(this.TargetEntity);
if (pos)
{
// shoot at their head
this.AddAimRequest(Priority.High, "position",pos);
this.Bot.MoveTowards(pos);
this.Bot.HoldButton(BTN.ATTACK1, 0.25);
}
else
{
this.Finished();
}
yield();
};
this.UpdateSwitchToSyringe = function()
{
this.AddWeaponRequest(Priority.High, WEAPON.SYRINGE);
this.BlockForWeaponChange(WEAPON.SYRINGE);
this.State = this.REVIVE_TARGET;
};
this.UpdateReviveTarget = function()
{
hlth = Util.GetEntHealth(this.TargetEntity);
if ( hlth > 0 ) {
this.State = this.DELIVER_PACKS;
// move off them
pos = GetEntEyePosition(this.TargetEntity) + Vector3(48,48,0);
if ( pos )
{
this.Goto(pos);
}
else
{
this.Finished();
}
return;
}
pos = GetEntEyePosition(this.TargetEntity);
if (pos)
{
this.AddAimRequest(Priority.High, "position",pos);
this.Bot.MoveTowards(pos);
this.Bot.HoldButton(BTN.ATTACK1, 0.25);
}
else
{
this.Finished();
}
yield();
};
this.Events[EVENT.TEAM_VOICE] = function(whoSaidIt, macroId)
{
packType = null;
if(macroId == VOICE.NEED_AMMO && this.Bot.GetClass() == CLASS.LIEUTENANT) {
packType = WEAPON.AMMO_PACK;
}
else if(macroId == VOICE.NEED_MEDIC && this.Bot.GetClass() == CLASS.MEDIC) {
packType = WEAPON.MEDKIT;
}
else
{
return;
}
dist = this.Bot.DistanceTo(whoSaidIt);
if ( GetEntFlags(whoSaidIt, ENTFLAG.DEAD) || dist > this.RangeLimit )
{
return;
}
if ( this.TargetEntity && this.TargetEntity == whoSaidIt ) {
return;
}
else if ( this.TargetEntity ) {
// store previous ents and collect targets to deliver to?
if ( dist < this.Bot.DistanceTo(this.TargetEntity) ) {
this.ChangedTarget = true;
}
}
if (this.Bot.IsWeaponCharged(packType))
{
this.TargetEntity = whoSaidIt;
this.Supply = packType;
this.Priority = this.DeliverPriority;
this.DelayNextResponse = true;
sleep(10);
if(this.DelayNextResponse) // can be null if bot disconnected
{
this.DelayNextResponse = false;
// if we haven't activated by now, don't bother
if(!this.IsActive()) {
this.Priority = 0;
}
}
}
};
this.Events[EVENT.WEAPON_FIRE] = function(weaponId, projectileEntity)
{
if(weaponId == this.Supply)
{
this.PacksThrown += 1;
}
};
| 412 | 0.93413 | 1 | 0.93413 | game-dev | MEDIA | 0.810253 | game-dev | 0.936859 | 1 | 0.936859 |
mikelma/craftium | 9,335 | src/environment.cpp | // Luanti
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
#include <fstream>
#include "environment.h"
#include "collision.h"
#include "raycast.h"
#include "scripting_server.h"
#include "server.h"
#include "daynightratio.h"
#include "emerge.h"
Environment::Environment(IGameDef *gamedef):
m_time_of_day_speed(0.0f),
m_day_count(0),
m_gamedef(gamedef)
{
m_time_of_day = g_settings->getU32("world_start_time");
m_time_of_day_f = (float)m_time_of_day / 24000.0f;
}
u32 Environment::getDayNightRatio()
{
MutexAutoLock lock(m_time_lock);
if (m_enable_day_night_ratio_override)
return m_day_night_ratio_override;
return time_to_daynight_ratio(m_time_of_day_f * 24000, true);
}
void Environment::setTimeOfDaySpeed(float speed)
{
m_time_of_day_speed = speed;
}
void Environment::setDayNightRatioOverride(bool enable, u32 value)
{
MutexAutoLock lock(m_time_lock);
m_enable_day_night_ratio_override = enable;
m_day_night_ratio_override = value;
}
void Environment::setTimeOfDay(u32 time)
{
MutexAutoLock lock(m_time_lock);
if (m_time_of_day > time)
++m_day_count;
m_time_of_day = time;
m_time_of_day_f = (float)time / 24000.0;
}
u32 Environment::getTimeOfDay()
{
MutexAutoLock lock(m_time_lock);
return m_time_of_day;
}
float Environment::getTimeOfDayF()
{
MutexAutoLock lock(m_time_lock);
return m_time_of_day_f;
}
bool Environment::line_of_sight(v3f pos1, v3f pos2, v3s16 *p)
{
// Iterate trough nodes on the line
voxalgo::VoxelLineIterator iterator(pos1 / BS, (pos2 - pos1) / BS);
do {
MapNode n = getMap().getNode(iterator.m_current_node_pos);
// Return non-air
if (n.param0 != CONTENT_AIR) {
if (p)
*p = iterator.m_current_node_pos;
return false;
}
iterator.next();
} while (iterator.m_current_index <= iterator.m_last_index);
return true;
}
/*
Check how a node can be pointed at
*/
inline static PointabilityType isPointableNode(const MapNode &n,
const NodeDefManager *nodedef, bool liquids_pointable,
const std::optional<Pointabilities> &pointabilities)
{
const ContentFeatures &features = nodedef->get(n);
if (pointabilities) {
std::optional<PointabilityType> match =
pointabilities->matchNode(features.name, features.groups);
if (match)
return match.value();
}
if (features.isLiquid() && liquids_pointable)
return PointabilityType::POINTABLE;
return features.pointable;
}
void Environment::continueRaycast(RaycastState *state, PointedThing *result_p)
{
const NodeDefManager *nodedef = getMap().getNodeDefManager();
if (state->m_initialization_needed) {
// Add objects
if (state->m_objects_pointable) {
std::vector<PointedThing> found;
getSelectedActiveObjects(state->m_shootline, found, state->m_pointabilities);
for (auto &pointed : found)
state->m_found.push(std::move(pointed));
}
// Set search range
core::aabbox3d<s16> maximal_exceed = nodedef->getSelectionBoxIntUnion();
state->m_search_range.MinEdge = -maximal_exceed.MaxEdge;
state->m_search_range.MaxEdge = -maximal_exceed.MinEdge;
// Setting is done
state->m_initialization_needed = false;
}
// The index of the first pointed thing that was not returned
// before. The last index which needs to be tested.
s16 lastIndex = state->m_iterator.m_last_index;
if (!state->m_found.empty()) {
lastIndex = state->m_iterator.getIndex(
floatToInt(state->m_found.top().intersection_point, BS));
}
Map &map = getMap();
std::vector<aabb3f> boxes;
while (state->m_iterator.m_current_index <= lastIndex) {
// Test the nodes around the current node in search_range.
core::aabbox3d<s16> new_nodes = state->m_search_range;
new_nodes.MinEdge += state->m_iterator.m_current_node_pos;
new_nodes.MaxEdge += state->m_iterator.m_current_node_pos;
// Only check new nodes
v3s16 delta = state->m_iterator.m_current_node_pos
- state->m_previous_node;
if (delta.X > 0) {
new_nodes.MinEdge.X = new_nodes.MaxEdge.X;
} else if (delta.X < 0) {
new_nodes.MaxEdge.X = new_nodes.MinEdge.X;
} else if (delta.Y > 0) {
new_nodes.MinEdge.Y = new_nodes.MaxEdge.Y;
} else if (delta.Y < 0) {
new_nodes.MaxEdge.Y = new_nodes.MinEdge.Y;
} else if (delta.Z > 0) {
new_nodes.MinEdge.Z = new_nodes.MaxEdge.Z;
} else if (delta.Z < 0) {
new_nodes.MaxEdge.Z = new_nodes.MinEdge.Z;
}
if (new_nodes.MaxEdge.X == S16_MAX ||
new_nodes.MaxEdge.Y == S16_MAX ||
new_nodes.MaxEdge.Z == S16_MAX) {
break; // About to go out of bounds
}
// For each untested node
for (s16 z = new_nodes.MinEdge.Z; z <= new_nodes.MaxEdge.Z; z++)
for (s16 y = new_nodes.MinEdge.Y; y <= new_nodes.MaxEdge.Y; y++)
for (s16 x = new_nodes.MinEdge.X; x <= new_nodes.MaxEdge.X; x++) {
MapNode n;
v3s16 np(x, y, z);
bool is_valid_position;
n = map.getNode(np, &is_valid_position);
if (!is_valid_position)
continue;
PointabilityType pointable = isPointableNode(n, nodedef,
state->m_liquids_pointable,
state->m_pointabilities);
// If it can be pointed through skip
if (pointable == PointabilityType::POINTABLE_NOT)
continue;
PointedThing result;
boxes.clear();
n.getSelectionBoxes(nodedef, &boxes,
n.getNeighbors(np, &map));
// Is there a collision with a selection box?
bool is_colliding = false;
// Minimal distance of all collisions
float min_distance_sq = 10000000;
// ID of the current box (loop counter)
u16 id = 0;
// If a node is found, this is the center of the
// first nodebox the shootline meets.
v3f found_boxcenter(0, 0, 0);
// Do calculations relative to the node center
// to translate the ray rather than the boxes
v3f npf = intToFloat(np, BS);
v3f rel_start = state->m_shootline.start - npf;
for (aabb3f &box : boxes) {
v3f intersection_point;
v3f intersection_normal;
if (!boxLineCollision(box, rel_start,
state->m_shootline.getVector(), &intersection_point,
&intersection_normal)) {
++id;
continue;
}
intersection_point += npf; // translate back to world coords
f32 distanceSq = (intersection_point
- state->m_shootline.start).getLengthSQ();
// If this is the nearest collision, save it
if (min_distance_sq > distanceSq) {
min_distance_sq = distanceSq;
result.intersection_point = intersection_point;
result.intersection_normal = intersection_normal;
result.box_id = id;
found_boxcenter = box.getCenter();
is_colliding = true;
}
++id;
}
// If there wasn't a collision, stop
if (!is_colliding) {
continue;
}
result.pointability = pointable;
result.type = POINTEDTHING_NODE;
result.node_undersurface = np;
result.distanceSq = min_distance_sq;
// Set undersurface and abovesurface nodes
const f32 d = 0.002 * BS;
v3f fake_intersection = result.intersection_point;
found_boxcenter += npf; // translate back to world coords
// Move intersection towards its source block.
if (fake_intersection.X < found_boxcenter.X) {
fake_intersection.X += d;
} else {
fake_intersection.X -= d;
}
if (fake_intersection.Y < found_boxcenter.Y) {
fake_intersection.Y += d;
} else {
fake_intersection.Y -= d;
}
if (fake_intersection.Z < found_boxcenter.Z) {
fake_intersection.Z += d;
} else {
fake_intersection.Z -= d;
}
result.node_real_undersurface = floatToInt(
fake_intersection, BS);
result.node_abovesurface = result.node_real_undersurface
+ floatToInt(result.intersection_normal, 1.0f);
// Push found PointedThing
state->m_found.push(std::move(result));
// If this is nearer than the old nearest object,
// the search can be shorter
s16 newIndex = state->m_iterator.getIndex(
result.node_real_undersurface);
if (newIndex < lastIndex) {
lastIndex = newIndex;
}
}
// Next node
state->m_previous_node = state->m_iterator.m_current_node_pos;
state->m_iterator.next();
}
// Return empty PointedThing if nothing left on the ray or it is blocking pointable
if (state->m_found.empty()) {
result_p->type = POINTEDTHING_NOTHING;
} else {
*result_p = state->m_found.top();
state->m_found.pop();
if (result_p->pointability == PointabilityType::POINTABLE_BLOCKING)
result_p->type = POINTEDTHING_NOTHING;
}
}
void Environment::stepTimeOfDay(float dtime)
{
MutexAutoLock lock(this->m_time_lock);
// Cached in order to prevent the two reads we do to give
// different results (can be written by code not under the lock)
f32 cached_time_of_day_speed = m_time_of_day_speed;
f32 speed = cached_time_of_day_speed * 24000. / (24. * 3600);
m_time_conversion_skew += dtime;
u32 units = (u32)(m_time_conversion_skew * speed);
bool sync_f = false;
if (units > 0) {
// Sync at overflow
if (m_time_of_day + units >= 24000) {
sync_f = true;
++m_day_count;
}
m_time_of_day = (m_time_of_day + units) % 24000;
if (sync_f)
m_time_of_day_f = (float)m_time_of_day / 24000.0;
}
if (speed > 0) {
m_time_conversion_skew -= (f32)units / speed;
}
if (!sync_f) {
m_time_of_day_f += cached_time_of_day_speed / 24 / 3600 * dtime;
if (m_time_of_day_f > 1.0)
m_time_of_day_f -= 1.0;
if (m_time_of_day_f < 0.0)
m_time_of_day_f += 1.0;
}
}
u32 Environment::getDayCount()
{
// Atomic<u32> counter
return m_day_count;
}
| 412 | 0.926611 | 1 | 0.926611 | game-dev | MEDIA | 0.606652 | game-dev | 0.965566 | 1 | 0.965566 |
Fluorohydride/ygopro-scripts | 4,596 | c22125101.lua | --軌跡の魔術師
function c22125101.initial_effect(c)
--link summon
aux.AddLinkProcedure(c,aux.FilterBoolFunction(Card.IsLinkType,TYPE_EFFECT),2,2,c22125101.lcheck)
c:EnableReviveLimit()
--to hand
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(22125101,0))
e1:SetCategory(CATEGORY_SEARCH+CATEGORY_TOHAND)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetProperty(EFFECT_FLAG_DELAY)
e1:SetCondition(c22125101.thcon)
e1:SetCost(c22125101.thcost)
e1:SetTarget(c22125101.thtg)
e1:SetOperation(c22125101.thop)
c:RegisterEffect(e1)
--destroy
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(22125101,1))
e2:SetCategory(CATEGORY_DESTROY)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
e2:SetRange(LOCATION_MZONE)
e2:SetProperty(EFFECT_FLAG_DELAY+EFFECT_FLAG_CARD_TARGET)
e2:SetCountLimit(1,22125101)
e2:SetCondition(c22125101.descon)
e2:SetTarget(c22125101.destg)
e2:SetOperation(c22125101.desop)
c:RegisterEffect(e2)
if not c22125101.global_check then
c22125101.global_check=true
local ge1=Effect.CreateEffect(c)
ge1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
ge1:SetCode(EVENT_SPSUMMON_SUCCESS_G_P)
ge1:SetOperation(c22125101.checkop)
Duel.RegisterEffect(ge1,0)
end
end
function c22125101.checkop(e,tp,eg,ep,ev,re,r,rp)
Duel.RegisterFlagEffect(rp,22125101,RESET_PHASE+PHASE_END,0,1)
end
function c22125101.lcheck(g)
return g:IsExists(Card.IsLinkType,1,nil,TYPE_PENDULUM)
end
function c22125101.thcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:IsSummonType(SUMMON_TYPE_LINK) and c:GetSequence()>4
end
function c22125101.thcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckLPCost(tp,1200) end
Duel.PayLPCost(tp,1200)
end
function c22125101.thfilter(c)
return c:IsType(TYPE_PENDULUM) and c:IsAbleToHand()
end
function c22125101.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c22125101.thfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c22125101.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c22125101.thfilter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
Duel.ResetFlagEffect(tp,22125101)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetTargetRange(1,0)
e1:SetCondition(c22125101.discon)
e1:SetValue(c22125101.actlimit)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
local e2=Effect.CreateEffect(e:GetHandler())
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_DISABLE)
e2:SetTargetRange(LOCATION_PZONE,0)
e2:SetCondition(c22125101.discon)
e2:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e2,tp)
local e3=Effect.CreateEffect(e:GetHandler())
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e3:SetCode(EVENT_CHAIN_SOLVING)
e3:SetCondition(c22125101.discon)
e3:SetOperation(c22125101.disop)
e3:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e3,tp)
end
function c22125101.actlimit(e,re,tp)
return re:IsActiveType(TYPE_MONSTER)
end
function c22125101.discon(e)
local tp=e:GetHandlerPlayer()
return Duel.GetFlagEffect(tp,22125101)==0
end
function c22125101.disop(e,tp,eg,ep,ev,re,r,rp)
local p,loc=Duel.GetChainInfo(ev,CHAININFO_TRIGGERING_CONTROLER,CHAININFO_TRIGGERING_LOCATION)
if re:GetActiveType()==TYPE_PENDULUM+TYPE_SPELL and p==tp and bit.band(loc,LOCATION_PZONE)~=0 then
Duel.NegateEffect(ev)
end
end
function c22125101.cfilter(c,eg)
return c:IsFaceup() and c:IsSummonType(SUMMON_TYPE_PENDULUM) and c:GetOriginalLevel()>0 and eg:IsContains(c)
end
function c22125101.descon(e,tp,eg,ep,ev,re,r,rp)
local g=e:GetHandler():GetLinkedGroup():Filter(c22125101.cfilter,nil,eg)
return #g==2 and g:GetClassCount(Card.GetOriginalLevel)==2
end
function c22125101.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsOnField() end
if chk==0 then return Duel.IsExistingTarget(aux.TRUE,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,2,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,aux.TRUE,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,2,2,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,2,0,0)
end
function c22125101.desop(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS):Filter(Card.IsRelateToEffect,nil,e)
Duel.Destroy(g,REASON_EFFECT)
end
| 412 | 0.803815 | 1 | 0.803815 | game-dev | MEDIA | 0.955117 | game-dev | 0.944727 | 1 | 0.944727 |
Interrupt/delverengine | 4,720 | core/src/main/java/com/interrupt/dungeoneer/entities/Torch.java | package com.interrupt.dungeoneer.entities;
import com.badlogic.gdx.graphics.Color;
import com.interrupt.dungeoneer.Audio;
import com.interrupt.dungeoneer.annotations.EditorProperty;
import com.interrupt.dungeoneer.game.Game;
import com.interrupt.dungeoneer.game.Level;
import com.interrupt.dungeoneer.game.Level.Source;
import com.interrupt.dungeoneer.gfx.animation.SpriteAnimation;
import com.interrupt.managers.EntityManager;
public class Torch extends Light {
float ticks = 0;
float switchtime = 10;
/** Starting animation frame sprite index. */
@EditorProperty
public int texAnimStart = 4;
/** Ending animation frame sprite index. */
@EditorProperty
public int texAnimEnd = 5;
public enum TorchAnimateModes { RANDOM, LOOP }
/** Torch animation mode. */
@EditorProperty
public TorchAnimateModes torchAnimateMode = TorchAnimateModes.RANDOM;
/** Animation speed. */
@EditorProperty
public float animSpeed = 30f;
protected SpriteAnimation animation = null;
public ParticleEmitter emitter = null;
public Torch() { spriteAtlas = "sprite"; hidden = false; collision.set(0.05f,0.05f,0.2f); fullbrite = true; haloMode = HaloMode.BOTH; haloOffset = 0.8f; }
/** Looping ambient sound. */
@EditorProperty
public String audio = "torch.mp3";
/** Make flies? */
@EditorProperty
public boolean makeFlies = false;
/** Make ParticleEmitter? */
@EditorProperty
public boolean makeEmitter = true;
public Torch(float x, float y, int tex, Color lightColor) {
super(x, y, lightColor, 3.2f);
artType = ArtType.sprite;
collision.set(0.05f,0.05f,0.2f);
this.tex = texAnimStart;
}
@Override
public void tick(Level level, float delta)
{
if(torchAnimateMode == TorchAnimateModes.RANDOM) {
ticks += delta;
if (switchtime < ticks) {
switchtime = ticks + 5;
if (Game.rand.nextInt(10) < 5)
tex = texAnimEnd;
else {
tex = texAnimStart;
}
}
}
else {
if(animation != null && animation.playing) {
animation.animate(delta, this);
if(animation.done) isActive = false; // die when done playing an animation
}
}
if(emitter != null) {
emitter.tick(level, delta);
}
color = lightColor;
}
@Override
public void init(Level level, Source source) {
this.tex = texAnimStart;
super.init(level, source);
collision.set(0.05f,0.05f,0.2f);
if(source != Source.EDITOR) {
if(emitter != null && makeEmitter) {
if(source == Source.LEVEL_START) {
emitter.x += x;
emitter.y += y;
emitter.z += z + 0.7f;
}
emitter.persists = false;
emitter.detailLevel = DetailLevel.HIGH;
emitter.init(level, source);
level.non_collidable_entities.add(emitter);
}
if(makeFlies) {
Entity flies = EntityManager.instance.getEntity("Groups", "Flies");
if (flies != null) {
flies.detailLevel = DetailLevel.HIGH;
if(source == Source.LEVEL_START) {
flies.x = (int) x + 0.5f;
flies.y = (int) y + 0.5f;
flies.z = z + 0.225f;
}
flies.persists = false;
level.non_collidable_entities.add(flies);
}
}
if(audio != null) {
AmbientSound sound = new AmbientSound(x, y, z, audio, 1f, 1f, 3.5f);
sound.persists = false;
level.non_collidable_entities.add(sound);
}
}
if(torchAnimateMode == TorchAnimateModes.LOOP && animation == null) {
this.playAnimation(new SpriteAnimation(texAnimStart, texAnimEnd, animSpeed, null), true, true);
}
}
public void editorTick(Level level, float delta) {
super.editorTick(level, delta);
if(animation != null) animation.animate(delta, this);
}
public void editorStartPreview(Level level) { if(torchAnimateMode == TorchAnimateModes.LOOP) this.playAnimation(new SpriteAnimation(texAnimStart, texAnimEnd, animSpeed, null), true, true); }
public void editorStopPreview(Level level) {
if(animation != null) {
tex = animation.start;
stopAnimation();
animation = null;
}
}
// Start an animation on this sprite
public void playAnimation(SpriteAnimation animation, boolean looping) {
this.animation = animation;
if(looping) this.animation.loop();
else this.animation.play();
}
public void playAnimation(SpriteAnimation animation, boolean looping, boolean randomize) {
playAnimation(animation, looping);
if(randomize && this.animation != null) {
animation.randomizeTime();
}
}
public void stopAnimation() {
animation = null;
}
@Override
public void preloadSounds() {
super.preloadSounds();
Audio.preload(audio);
}
}
| 412 | 0.68666 | 1 | 0.68666 | game-dev | MEDIA | 0.971449 | game-dev | 0.884752 | 1 | 0.884752 |
RuneStar/cs2-scripts | 2,094 | scripts/[proc,hp_hud_pos].cs2 | // 2101
[proc,hp_hud_pos](int $int0, component $component1, component $component2, component $component3, component $component4, component $component5, component $component6, component $component7, component $component8, component $component9, component $component10, component $component11, component $component12, int $int13, component $component14, component $component15, component $component16)
def_int $width17 = if_getwidth($component1);
def_boolean $boolean18 = false;
def_int $int19 = 150;
def_int $setposh20 = ^setpos_abs_left;
if (%varbit12401 = 1 & ~on_mobile = false) {
$int19 = scale(1, 4, $width17);
$int19 = ~max($int19, 200);
$int19 = ~min($int19, 600);
$setposh20 = ^setpos_abs_centre;
}
if ($int0 = $int19) {
return;
}
if ($int19 ! if_getwidth($component2)) {
if_setsize($int19, if_getheight($component2), ^setsize_abs, ^setsize_abs, $component2);
$boolean18 = true;
}
if ($int13 ! %varbit12401) {
if (%varbit12401 = 1 & ~on_mobile = false) {
~script4729($component14, $component2, setbit(setbit(clearbit(clearbit(52968, 5), 6), 12), 17), ^setpos_abs_centre, ^setpos_abs_top, false);
} else if (%varbit12401 = 0 & ~on_mobile = false) {
~script4729($component14, $component2, setbit(clearbit(clearbit(52968, 5), 6), 17), ^setpos_abs_left, ^setpos_abs_top, true);
} else {
~script4729($component14, $component2, setbit(clearbit(clearbit(setbit(setbit(52968, 13), 12), 6), 5), 17), ^setpos_abs_left, ^setpos_abs_top, true);
}
}
if_setposition(0, 0, $setposh20, ^setpos_abs_top, $component2);
if_setposition(0, 0, ^setpos_abs_centre, ^setpos_abs_top, $component3);
if_setposition(0, 0, ^setpos_abs_left, ^setpos_abs_top, $component15);
if_setontimer("hp_hud_pos($int19, $component1, $component2, $component3, $component4, $component5, $component6, $component7, $component8, $component9, $component10, $component11, $component12, %varbit12401, $component14, $component15, $component16)", $component1);
~hp_hud_update($component2, $component6, $component7, $component8, $component3, $component5, $component9, $component10, $component11, $component12, $boolean18);
| 412 | 0.859082 | 1 | 0.859082 | game-dev | MEDIA | 0.84264 | game-dev | 0.656812 | 1 | 0.656812 |
ProjectIgnis/CardScripts | 2,520 | official/c8617563.lua | --RR-ブレイブ・ストリクス
--Raidraptor - Brave Strix
--scripted by Naim
local s,id=GetID()
function s.initial_effect(c)
c:EnableReviveLimit()
--Xyz Summon Procedure
Xyz.AddProcedure(c,nil,5,2)
--Set 1 "Raidraptor" Spell/Trap directly from your Deck
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1,id)
e1:SetCost(Cost.DetachFromSelf(1,1,nil))
e1:SetTarget(s.settg)
e1:SetOperation(s.setop)
c:RegisterEffect(e1)
--Search 1 "Rank-Up-Magic" Spell if it has a Winged Beast monster attached
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,1))
e2:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1,id)
e2:SetCondition(function(e) return e:GetHandler():GetOverlayGroup():IsExists(Card.IsRace,1,nil,RACE_WINGEDBEAST) end)
e2:SetCost(Cost.DetachFromSelf(1,1,nil))
e2:SetTarget(s.thtg)
e2:SetOperation(s.thop)
c:RegisterEffect(e2)
--A "Raidraptor" Xyz Monster that has this card as material gains ATK
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_XMATERIAL)
e3:SetCode(EFFECT_UPDATE_ATTACK)
e3:SetCondition(function(e) return e:GetHandler():IsSetCard(SET_RAIDRAPTOR) end)
e3:SetValue(function(e,c) return c:GetRank()*100 end)
c:RegisterEffect(e3)
end
s.listed_series={SET_RAIDRAPTOR,SET_RANK_UP_MAGIC}
function s.setfilter(c)
return c:IsSetCard(SET_RAIDRAPTOR) and c:IsSpellTrap() and c:IsSSetable()
end
function s.settg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(s.setfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription())
end
function s.setop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SET)
local g=Duel.SelectMatchingCard(tp,s.setfilter,tp,LOCATION_DECK,0,1,1,nil)
if #g>0 then
Duel.SSet(tp,g)
end
end
function s.thfilter(c)
return c:IsSetCard(SET_RANK_UP_MAGIC) and c:IsSpell() 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.Hint(HINT_OPSELECTED,1-tp,e:GetDescription())
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function s.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,s.thfilter,tp,LOCATION_DECK,0,1,1,nil)
if #g>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
| 412 | 0.915014 | 1 | 0.915014 | game-dev | MEDIA | 0.978915 | game-dev | 0.954333 | 1 | 0.954333 |
MongusOrg/LiquidBouncePlusPlus | 1,458 | src/main/java/net/ccbluex/liquidbounce/features/module/modules/movement/speeds/ncp/NCPYPort.java | /*
* LiquidBounce++ Hacked Client
* A free open source mixin-based injection hacked client for Minecraft using Minecraft Forge.
* https://github.com/PlusPlusMC/LiquidBouncePlusPlus/
*/
package net.ccbluex.liquidbounce.features.module.modules.movement.speeds.ncp;
import net.ccbluex.liquidbounce.event.MoveEvent;
import net.ccbluex.liquidbounce.features.module.modules.movement.speeds.SpeedMode;
import net.ccbluex.liquidbounce.utils.MovementUtils;
import net.minecraft.util.MathHelper;
public class NCPYPort extends SpeedMode {
private int jumps;
public NCPYPort() {
super("NCPYPort");
}
@Override
public void onMotion() {
if(mc.thePlayer.isOnLadder() || mc.thePlayer.isInWater() || mc.thePlayer.isInLava() || mc.thePlayer.isInWeb || !MovementUtils.isMoving() || mc.thePlayer.isInWater())
return;
if(jumps >= 4 && mc.thePlayer.onGround)
jumps = 0;
if(mc.thePlayer.onGround) {
mc.thePlayer.motionY = jumps <= 1 ? 0.42F : 0.4F;
float f = mc.thePlayer.rotationYaw * 0.017453292F;
mc.thePlayer.motionX -= MathHelper.sin(f) * 0.2F;
mc.thePlayer.motionZ += MathHelper.cos(f) * 0.2F;
jumps++;
}else if(jumps <= 1)
mc.thePlayer.motionY = -5D;
MovementUtils.strafe();
}
@Override
public void onUpdate() {
}
@Override
public void onMove(MoveEvent event) {
}
}
| 412 | 0.692572 | 1 | 0.692572 | game-dev | MEDIA | 0.609912 | game-dev | 0.760911 | 1 | 0.760911 |
opentibia/yatc | 5,629 | gamecontent/creature.cpp | //////////////////////////////////////////////////////////////////////
// Yet Another Tibia Client
//////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////
// 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.
//////////////////////////////////////////////////////////////////////
#include "creature.h"
#include "globalvars.h"
extern uint32_t g_frameTime;
Creatures* Creatures::m_instance = NULL;
//*********** Creature **************
Creature::Creature()
{
m_id = 0;
m_health = 0;
m_lookdir = DIRECTION_NORTH;
m_outfit.m_looktype = 0;
m_outfit.m_lookhead = 0;
m_outfit.m_lookbody = 0;
m_outfit.m_looklegs = 0;
m_outfit.m_lookfeet = 0;
m_outfit.m_addons = 0;
m_lightLevel = 0;
m_lightColor = 0;
m_speed = 0;
m_skull = 0;
m_shield = 0;
m_emblem = 0;
m_impassable = true;
m_squareColor = 0;
m_squareStartTime = 0;
m_moveStartTime = 0;
}
void Creature::setSquare(uint32_t color)
{
m_squareColor = color;
m_squareStartTime = g_frameTime;
}
void Creature::setMoving(const Position& oldPos, const Position& newPos)
{
m_moveStartTime = g_frameTime;
m_moveOldPos = oldPos;
m_currentPos = newPos;
}
//*********** Creatures *************
// 133 outfit colors on this table
uint32_t Creatures::OutfitLookupTable[] = {
0xFFFFFF, 0xFFD4BF, 0xFFE9BF, 0xFFFFBF, 0xE9FFBF, 0xD4FFBF,
0xBFFFBF, 0xBFFFD4, 0xBFFFE9, 0xBFFFFF, 0xBFE9FF, 0xBFD4FF,
0xBFBFFF, 0xD4BFFF, 0xE9BFFF, 0xFFBFFF, 0xFFBFE9, 0xFFBFD4,
0xFFBFBF, 0xDADADA, 0xBF9F8F, 0xBFAF8F, 0xBFBF8F, 0xAFBF8F,
0x9FBF8F, 0x8FBF8F, 0x8FBF9F, 0x8FBFAF, 0x8FBFBF, 0x8FAFBF,
0x8F9FBF, 0x8F8FBF, 0x9F8FBF, 0xAF8FBF, 0xBF8FBF, 0xBF8FAF,
0xBF8F9F, 0xBF8F8F, 0xB6B6B6, 0xBF7F5F, 0xBFAF8F, 0xBFBF5F,
0x9FBF5F, 0x7FBF5F, 0x5FBF5F, 0x5FBF7F, 0x5FBF9F, 0x5FBFBF,
0x5F9FBF, 0x5F7FBF, 0x5F5FBF, 0x7F5FBF, 0x9F5FBF, 0xBF5FBF,
0xBF5F9F, 0xBF5F7F, 0xBF5F5F, 0x919191, 0xBF6A3F, 0xBF943F,
0xBFBF3F, 0x94BF3F, 0x6ABF3F, 0x3FBF3F, 0x3FBF6A, 0x3FBF94,
0x3FBFBF, 0x3F94BF, 0x3F6ABF, 0x3F3FBF, 0x6A3FBF, 0x943FBF,
0xBF3FBF, 0xBF3F94, 0xBF3F6A, 0xBF3F3F, 0x6D6D6D, 0xFF5500,
0xFFAA00, 0xFFFF00, 0xAAFF00, 0x54FF00, 0x00FF00, 0x00FF54,
0x00FFAA, 0x00FFFF, 0x00A9FF, 0x0055FF, 0x0000FF, 0x5500FF,
0xA900FF, 0xFE00FF, 0xFF00AA, 0xFF0055, 0xFF0000, 0x484848,
0xBF3F00, 0xBF7F00, 0xBFBF00, 0x7FBF00, 0x3FBF00, 0x00BF00,
0x00BF3F, 0x00BF7F, 0x00BFBF, 0x007FBF, 0x003FBF, 0x0000BF,
0x3F00BF, 0x7F00BF, 0xBF00BF, 0xBF007F, 0xBF003F, 0xBF0000,
0x242424, 0x7F2A00, 0x7F5500, 0x7F7F00, 0x557F00, 0x2A7F00,
0x007F00, 0x007F2A, 0x007F55, 0x007F7F, 0x00547F, 0x002A7F,
0x00007F, 0x2A007F, 0x54007F, 0x7F007F, 0x7F0055, 0x7F002A,
0x7F0000,
};
Creature Creatures::m_creaturesArray[CREATURES_ARRAY];
int16_t Creatures::reserveCreature(uint32_t id)
{
for(uint32_t i = 0; i < CREATURES_ARRAY; ++i){
if(m_creaturesArray[i].m_id == 0){
m_creaturesArray[i].m_id = id;
return i;
}
}
// TODO (mips_act#3#): Handle error, trying to create a creature but there isnt any free slot for it!
return -1;
}
Creature* Creatures::getPlayer()
{
uint32_t ourId = GlobalVariables::getPlayerID();
return getCreature(ourId);
}
Creature* Creatures::getCreature(uint32_t id)
{
CreatureMap::iterator it = m_creaturesId.find(id);
//ASSERT(id)// NOTE (nfries88): this assertion seems to fail sometimes. it doesn't seem necessary anyway.
if(it != m_creaturesId.end()){
return &m_creaturesArray[it->second];
}
else{
return NULL;
}
}
Creature* Creatures::lookup(const std::string& name)
{
for(int i = 0; i < CREATURES_ARRAY; ++i)
{
if(m_creaturesArray[i].getName() == name)
{
return &m_creaturesArray[i];
}
}
return NULL;
}
Creature* Creatures::addCreature(uint32_t id)
{
int16_t i = reserveCreature(id);
if(i >= 0){
m_creaturesId[id] = i;
return &m_creaturesArray[i];
}
else{
// TODO (mips_act#3#): Handle error...
return NULL;
}
}
void Creatures::removeCreature(uint32_t id)
{
if(id == 0){
return;
}
CreatureMap::iterator it = m_creaturesId.find(id);
if(it != m_creaturesId.end()){
m_creaturesArray[it->second].unloadGfx();
//m_creaturesArray[it->second].m_id = 0;
m_creaturesArray[it->second].resetSelf();
m_creaturesId.erase(it);
}
else{
// TODO (mips_act#3#): Handle error...
printf("!=!=! Creatures::removeCreature: error removing unknown creature\n");
}
}
void Creatures::clear()
{
m_creaturesId.clear();
for(uint32_t i = 0; i < CREATURES_ARRAY; ++i){
m_creaturesArray[i].unloadGfx();
m_creaturesArray[i].resetSelf();
//m_creaturesArray[i].m_id = 0;
}
}
void Creatures::unloadGfx()
{
for(uint32_t i = 0; i < CREATURES_ARRAY; ++i){
m_creaturesArray[i].unloadGfx();
}
}
void Creatures::loadGfx()
{
for(uint32_t i = 0; i < CREATURES_ARRAY; ++i){
if (!m_creaturesArray[i].m_id)
continue;
m_creaturesArray[i].setupObject();
if(!m_creaturesArray[i].isLoaded())
m_creaturesArray[i].loadOutfit();
}
}
| 412 | 0.758383 | 1 | 0.758383 | game-dev | MEDIA | 0.50294 | game-dev | 0.928317 | 1 | 0.928317 |
lordofduct/spacepuppy-unity-framework-4.0 | 10,098 | Framework/com.spacepuppy.core/Runtime/src/CustomTimeSupplier.cs | using UnityEngine;
using System;
using System.Collections.Generic;
namespace com.spacepuppy
{
/// <summary>
/// A TimeSupplier that allows for individual scaling. You may have to scale the world time to 0 for pause
/// or other various effects, but you still want time to tick normally for other aspects like the menu or
/// something. BUT, lets say you want to be able to scale that time as well for various effects, independent
/// of the world time. By using a custom TimeSupplier you can scale that time independent of the world time.
///
/// Furthermore you can stack time scales, just like described in com.spacepuppy.SPTime.
///
/// Allows for approximately 29,247 years of simulation, twice that if you include negative time, while
/// maintaining at minimum 3 digits of fractional precision for seconds (millisecond precision) when at the
/// extents of its range.
/// </summary>
public class CustomTimeSupplier : ICustomTimeSupplier, IScalableTimeSupplier, System.IDisposable
{
private const long SECONDS_TO_TICKS = 10000000L;
private const double TICKS_TO_SECONDS = 1E-07d;
private static long GetTicksSafe(double value)
{
if (double.IsNaN(value))
return 0;
value *= (double)SECONDS_TO_TICKS;
if (value <= (double)long.MinValue)
return long.MinValue;
else if (value >= (double)long.MaxValue)
return long.MaxValue;
else
{
try
{
return (long)value;
}
catch
{
return 0;
}
}
}
#region Fields
private string _id;
private long _startTime;
private long _t;
private long _ft;
private double _scale = 1.0;
private bool _paused;
private Dictionary<string, double> _scales = new Dictionary<string, double>();
#endregion
#region CONSTRUCTOR
internal CustomTimeSupplier(string id)
{
_id = id;
}
#endregion
#region Properties
public string Id { get { return _id; } }
public bool Valid { get { return _id != null; } }
public double StartTime
{
get { return _startTime * TICKS_TO_SECONDS; }
set
{
_startTime = GetTicksSafe(value);
}
}
public TimeSpan TotalSpan
{
get
{
if (GameLoop.CurrentSequence == UpdateSequence.FixedUpdate)
{
return new TimeSpan(_ft + _startTime);
}
else
{
return new TimeSpan(_t + _startTime);
}
}
}
/// <summary>
/// When updating should the world time scale be respected as well? Use this to cause the timer to pause when the normal time is paused.
/// </summary>
public bool TrackNormalTimeScale { get; set; }
/// <summary>
/// The total time passed since the CustomTime was created. Value is relative to the Update sequence.
/// </summary>
public double UpdateTotal { get { return (_t + _startTime) * TICKS_TO_SECONDS; } }
public TimeSpan UpdateTotalSpan { get { return new TimeSpan(_t + _startTime); } }
/// <summary>
/// The delta time since the call to standard update. This will always return the delta since last update, regardless of if you call it in update/fixedupdate.
/// </summary>
public double UpdateDelta { get { return Time.unscaledDeltaTime * _scale; } }
/// <summary>
/// The total time passed since the CustomTime was created. Value is relative to the FixedUpdate sequence;
/// </summary>
public double FixedTotal { get { return (_ft + _startTime) * TICKS_TO_SECONDS; } }
public TimeSpan FixedTotalSpan { get { return new TimeSpan(_ft + _startTime); } }
/// <summary>
/// The delta time since the call to fixed update. This will always return the delta since last fixedupdate, regardless of if you call it in update/fixedupdate.
/// </summary>
public double FixedDelta { get { return Time.fixedDeltaTime * _scale; } }
#endregion
#region Methods
internal void Update(bool isFixed)
{
if (_paused) return;
if (isFixed)
{
_ft += (long)(Time.fixedUnscaledDeltaTime * _scale * SECONDS_TO_TICKS);
}
else
{
_t += (long)(Time.unscaledDeltaTime * _scale * SECONDS_TO_TICKS);
}
}
public bool Destroy()
{
if( SPTime.RemoveCustomTime(this))
{
_id = null;
return true;
}
else
{
return false;
}
}
private void SyncTimeScale()
{
double result = 1d;
if (_scales.Count > 0)
{
var e = _scales.GetEnumerator();
while (e.MoveNext())
{
result *= e.Current.Value;
}
}
if(System.Math.Abs(result - _scale) > 0.0000001d)
{
_scale = result;
if (this.TimeScaleChanged != null) this.TimeScaleChanged(this, System.EventArgs.Empty);
}
else
{
_scale = result;
}
}
public void Reset()
{
_startTime = 0;
_t = 0;
_ft = 0;
}
public void Reset(double startTime)
{
_startTime = GetTicksSafe(startTime);
_t = 0;
_ft = 0;
}
/// <summary>
/// Adjust the current 'TotalTime' by some amount.
/// WARNING - delta is not effected
/// WARNING - time based event systems might be adversely impacted
/// Especially if the value is negative.
/// USE AT OWN RISK!
/// </summary>
/// <param name="value"></param>
public void AdjustTime(double value)
{
_startTime += GetTicksSafe(value);
}
#endregion
#region ITimeSupplier Interface
public event System.EventHandler TimeScaleChanged;
/// <summary>
/// The total time passed since thie CustomTime was created. Value is dependent on the UpdateSequence being accessed from.
/// </summary>
public float Total
{
get
{
if(GameLoop.CurrentSequence == UpdateSequence.FixedUpdate)
{
return (float)((_ft + _startTime) * TICKS_TO_SECONDS);
}
else
{
return (float)((_t + _startTime) * TICKS_TO_SECONDS);
}
}
}
public double TotalPrecise
{
get
{
if (GameLoop.CurrentSequence == UpdateSequence.FixedUpdate)
{
return (_ft + _startTime) * TICKS_TO_SECONDS;
}
else
{
return (_t + _startTime) * TICKS_TO_SECONDS;
}
}
}
/// <summary>
/// The delta time since the last call to update/fixedupdate, relative to in which update/fixedupdate you call.
/// </summary>
public float Delta
{
get
{
if (_paused)
return 0f;
else
return (GameLoop.CurrentSequence == UpdateSequence.FixedUpdate) ? (float)(Time.fixedDeltaTime * _scale) : (float)(Time.unscaledDeltaTime * _scale);
}
}
public bool Paused
{
get { return _paused; }
set
{
if (_paused == value) return;
_paused = value;
if (this.TimeScaleChanged != null) this.TimeScaleChanged(this, System.EventArgs.Empty);
}
}
public float Scale
{
get { return (float)_scale; }
}
public IEnumerable<string> ScaleIds
{
get { return _scales.Keys; }
}
public void SetScale(string id, float scale)
{
_scales[id] = (double)scale;
this.SyncTimeScale();
}
public float GetScale(string id)
{
double result;
if (_scales.TryGetValue(id, out result))
{
return (float)result;
}
else
{
return float.NaN;
}
}
public bool RemoveScale(string id)
{
if (_scales.Remove(id))
{
this.SyncTimeScale();
return true;
}
else
{
return false;
}
}
public bool HasScale(string id)
{
return _scales.ContainsKey(id);
}
void ICustomTimeSupplier.Update(bool isFixed)
{
if (_paused) return;
double scale = _scale;
if (this.TrackNormalTimeScale) scale *= SPTime.Normal.Scale;
if (isFixed)
{
_ft += (long)(Time.fixedUnscaledDeltaTime * scale * SECONDS_TO_TICKS);
}
else
{
_t += (long)(Time.unscaledDeltaTime * scale * SECONDS_TO_TICKS);
}
}
#endregion
#region IDisposable Interface
void System.IDisposable.Dispose()
{
this.Destroy();
}
#endregion
}
}
| 412 | 0.875912 | 1 | 0.875912 | game-dev | MEDIA | 0.944082 | game-dev | 0.993037 | 1 | 0.993037 |
jadvrodrigues/CustomNavMesh | 24,737 | Assets/CustomNavMesh/Editor/CustomNavMeshAgentInspector.cs | using System;
using UnityEditor;
using UnityEngine;
using UnityEngine.AI;
[CanEditMultipleObjects, CustomEditor(typeof(CustomNavMeshAgent))]
public class CustomNavMeshAgentInspector : Editor
{
static readonly GUIContent s_Text = new GUIContent();
SerializedProperty m_AgentTypeID;
SerializedProperty m_Radius;
SerializedProperty m_Height;
SerializedProperty m_WalkableMask;
SerializedProperty m_Speed;
SerializedProperty m_Acceleration;
SerializedProperty m_AngularSpeed;
SerializedProperty m_StoppingDistance;
SerializedProperty m_AutoTraverseOffMeshLink;
SerializedProperty m_AutoBraking;
SerializedProperty m_AutoRepath;
SerializedProperty m_BaseOffset;
SerializedProperty m_ObstacleAvoidanceType;
SerializedProperty m_AvoidancePriority;
SerializedProperty m_BlockAfterDuration;
SerializedProperty m_TimeToBlock;
SerializedProperty m_BlockSpeedThreshold;
SerializedProperty m_UnblockAfterDuration;
SerializedProperty m_TimeToUnblock;
SerializedProperty m_DistanceReductionThreshold;
SerializedProperty m_UnblockAtSpeed;
SerializedProperty m_UnblockSpeedThreshold;
SerializedProperty m_CarvingMoveThreshold;
SerializedProperty m_TimeToStationary;
SerializedProperty m_CarveOnlyStationary;
CustomNavMeshAgent[] Agents
{
get
{
return Array.ConvertAll(targets, obj => (CustomNavMeshAgent) obj);
}
}
private class Styles
{
public readonly GUIContent m_AgentSteeringHeader = EditorGUIUtility.TrTextContent("Steering");
public readonly GUIContent m_AgentAvoidanceHeader = EditorGUIUtility.TrTextContent("Obstacle Avoidance");
public readonly GUIContent m_AgentPathFindingHeader = EditorGUIUtility.TrTextContent("Path Finding");
public readonly GUIContent m_AgentBlockingHeader = EditorGUIUtility.TrTextContent("Blocking");
public readonly GUIContent m_AgentUnblockingHeader = EditorGUIUtility.TrTextContent("Unblocking");
}
static Styles s_Styles;
private void OnEnable()
{
var agent = target as CustomNavMeshAgent;
var navMeshAgent = agent.GetComponent<NavMeshAgent>();
if (navMeshAgent != null)
{
// prevent the user from changing the agent through the NavMeshAgent's inspector
navMeshAgent.hideFlags = HideFlags.HideInInspector;
}
m_AgentTypeID = serializedObject.FindProperty("m_AgentTypeID");
m_Radius = serializedObject.FindProperty("m_Radius");
m_Height = serializedObject.FindProperty("m_Height");
m_WalkableMask = serializedObject.FindProperty("m_WalkableMask");
m_Speed = serializedObject.FindProperty("m_Speed");
m_Acceleration = serializedObject.FindProperty("m_Acceleration");
m_AngularSpeed = serializedObject.FindProperty("m_AngularSpeed");
m_StoppingDistance = serializedObject.FindProperty("m_StoppingDistance");
m_AutoTraverseOffMeshLink = serializedObject.FindProperty("m_AutoTraverseOffMeshLink");
m_AutoBraking = serializedObject.FindProperty("m_AutoBraking");
m_AutoRepath = serializedObject.FindProperty("m_AutoRepath");
m_BaseOffset = serializedObject.FindProperty("m_BaseOffset");
m_ObstacleAvoidanceType = serializedObject.FindProperty("m_ObstacleAvoidanceType");
m_AvoidancePriority = serializedObject.FindProperty("m_AvoidancePriority");
m_BlockAfterDuration = serializedObject.FindProperty("m_BlockAfterDuration");
m_TimeToBlock = serializedObject.FindProperty("m_TimeToBlock");
m_BlockSpeedThreshold = serializedObject.FindProperty("m_BlockSpeedThreshold");
m_UnblockAfterDuration = serializedObject.FindProperty("m_UnblockAfterDuration");
m_TimeToUnblock = serializedObject.FindProperty("m_TimeToUnblock");
m_DistanceReductionThreshold = serializedObject.FindProperty("m_DistanceReductionThreshold");
m_UnblockAtSpeed = serializedObject.FindProperty("m_UnblockAtSpeed");
m_UnblockSpeedThreshold = serializedObject.FindProperty("m_UnblockSpeedThreshold");
m_CarvingMoveThreshold = serializedObject.FindProperty("m_CarvingMoveThreshold");
m_TimeToStationary = serializedObject.FindProperty("m_TimeToStationary");
m_CarveOnlyStationary = serializedObject.FindProperty("m_CarveOnlyStationary");
}
public override void OnInspectorGUI()
{
if (s_Styles == null)
s_Styles = new Styles();
serializedObject.Update();
AgentTypePopupInternal("Agent Type", m_AgentTypeID);
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_BaseOffset);
if(EditorGUI.EndChangeCheck())
{
foreach(var agent in Agents)
{
Undo.RecordObject(agent, "Changed Agent Base Offset");
agent.RecordNavMeshAgent();
agent.BaseOffset = m_BaseOffset.floatValue;
}
serializedObject.ApplyModifiedProperties();
}
EditorGUILayout.Space();
EditorGUILayout.LabelField(s_Styles.m_AgentSteeringHeader, EditorStyles.boldLabel);
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_Speed);
if (EditorGUI.EndChangeCheck())
{
if (m_Speed.floatValue < 0.0f) m_Speed.floatValue = 0.0f;
foreach (var agent in Agents)
{
Undo.RecordObject(agent, "Changed Agent Speed");
agent.RecordNavMeshAgent();
agent.Speed = m_Speed.floatValue;
}
serializedObject.ApplyModifiedProperties();
}
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_AngularSpeed);
if (EditorGUI.EndChangeCheck())
{
if (m_AngularSpeed.floatValue < 0.0f) m_AngularSpeed.floatValue = 0.0f;
foreach (var agent in Agents)
{
Undo.RecordObject(agent, "Changed Agent Angular Speed");
agent.RecordNavMeshAgent();
agent.AngularSpeed = m_AngularSpeed.floatValue;
}
serializedObject.ApplyModifiedProperties();
}
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_Acceleration);
if (EditorGUI.EndChangeCheck())
{
if (m_Acceleration.floatValue < 0.0f) m_Acceleration.floatValue = 0.0f;
foreach (var agent in Agents)
{
Undo.RecordObject(agent, "Changed Agent Acceleration");
agent.RecordNavMeshAgent();
agent.Acceleration = m_Acceleration.floatValue;
}
serializedObject.ApplyModifiedProperties();
}
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_StoppingDistance);
if (EditorGUI.EndChangeCheck())
{
if (m_StoppingDistance.floatValue < 0.0f) m_StoppingDistance.floatValue = 0.0f;
foreach (var agent in Agents)
{
Undo.RecordObject(agent, "Changed Agent Stopping Distance");
agent.RecordNavMeshAgent();
agent.StoppingDistance = m_StoppingDistance.floatValue;
}
serializedObject.ApplyModifiedProperties();
}
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_AutoBraking);
if (EditorGUI.EndChangeCheck())
{
foreach (var agent in Agents)
{
Undo.RecordObject(agent, "Changed Agent Auto Braking");
agent.RecordNavMeshAgent();
agent.AutoBraking = m_AutoBraking.boolValue;
}
serializedObject.ApplyModifiedProperties();
}
EditorGUILayout.Space();
EditorGUILayout.LabelField(s_Styles.m_AgentAvoidanceHeader, EditorStyles.boldLabel);
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_Radius);
if (EditorGUI.EndChangeCheck())
{
if (m_Radius.floatValue <= 0.0f) m_Radius.floatValue = 1e-05f;
foreach (var agent in Agents)
{
Undo.RecordObject(agent, "Changed Agent Radius");
agent.RecordNavMeshAgent();
agent.Radius = m_Radius.floatValue;
}
serializedObject.ApplyModifiedProperties();
}
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_Height);
if (EditorGUI.EndChangeCheck())
{
if (m_Height.floatValue <= 0.0f) m_Height.floatValue = 1e-05f;
foreach (var agent in Agents)
{
Undo.RecordObject(agent, "Changed Agent Height");
agent.RecordNavMeshAgent();
agent.Height = m_Height.floatValue;
}
serializedObject.ApplyModifiedProperties();
}
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_ObstacleAvoidanceType, Temp("Quality"));
if (EditorGUI.EndChangeCheck())
{
foreach (var agent in Agents)
{
Undo.RecordObject(agent, "Changed Agent Obstacle Avoidance Type");
agent.RecordNavMeshAgent();
agent.ObstacleAvoidanceType = (ObstacleAvoidanceType)m_ObstacleAvoidanceType.enumValueIndex;
}
serializedObject.ApplyModifiedProperties();
}
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_AvoidancePriority, Temp("Priority"));
if (EditorGUI.EndChangeCheck())
{
if (m_AvoidancePriority.intValue < 0) m_AvoidancePriority.intValue = 0;
if (m_AvoidancePriority.intValue > 99) m_AvoidancePriority.intValue = 99;
foreach (var agent in Agents)
{
Undo.RecordObject(agent, "Changed Agent Avoidance Priority");
agent.RecordNavMeshAgent();
agent.AvoidancePriority = m_AvoidancePriority.intValue;
}
serializedObject.ApplyModifiedProperties();
}
EditorGUILayout.Space();
EditorGUILayout.LabelField(s_Styles.m_AgentPathFindingHeader, EditorStyles.boldLabel);
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_AutoTraverseOffMeshLink);
if (EditorGUI.EndChangeCheck())
{
foreach (var agent in Agents)
{
Undo.RecordObject(agent, "Changed Agent Auto Traverse Off Mesh Link");
agent.RecordNavMeshAgent();
agent.AutoTraverseOffMeshLink = m_AutoTraverseOffMeshLink.boolValue;
}
serializedObject.ApplyModifiedProperties();
}
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_AutoRepath);
if (EditorGUI.EndChangeCheck())
{
foreach (var agent in Agents)
{
Undo.RecordObject(agent, "Changed Agent Auto Repath");
agent.RecordNavMeshAgent();
agent.AutoRepath = m_AutoRepath.boolValue;
}
serializedObject.ApplyModifiedProperties();
}
//Initially needed data
var areaNames = GameObjectUtility.GetNavMeshAreaNames();
var currentMask = m_WalkableMask.longValue;
var compressedMask = 0;
//Need to find the index as the list of names will compress out empty areas
for (var i = 0; i < areaNames.Length; i++)
{
var areaIndex = GameObjectUtility.GetNavMeshAreaFromName(areaNames[i]);
if (((1 << areaIndex) & currentMask) != 0)
compressedMask = compressedMask | (1 << i);
}
//Refactor this to use the mask field that takes a label.
float kSingleLineHeight = 18f;
float kSpacing = 5;
float kLabelFloatMinW = EditorGUIUtility.labelWidth + EditorGUIUtility.fieldWidth + kSpacing;
float kLabelFloatMaxW = EditorGUIUtility.labelWidth + EditorGUIUtility.fieldWidth + kSpacing;
float kH = kSingleLineHeight;
var position = GUILayoutUtility.GetRect(kLabelFloatMinW, kLabelFloatMaxW, kH, kH, EditorStyles.layerMaskField);
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = m_WalkableMask.hasMultipleDifferentValues;
var areaMask = EditorGUI.MaskField(position, "Area Mask", compressedMask, areaNames, EditorStyles.layerMaskField);
EditorGUI.showMixedValue = false;
if (EditorGUI.EndChangeCheck())
{
if (areaMask == ~0)
{
m_WalkableMask.longValue = 0xffffffff;
}
else
{
uint newMask = 0;
for (var i = 0; i < areaNames.Length; i++)
{
//If the bit has been set in the compacted mask
if (((areaMask >> i) & 1) != 0)
{
//Find out the 'real' layer from the name, then set it in the new mask
newMask = newMask | (uint)(1 << GameObjectUtility.GetNavMeshAreaFromName(areaNames[i]));
}
}
m_WalkableMask.longValue = newMask;
}
foreach (var agent in Agents)
{
Undo.RecordObject(agent, "Changed Agent Area Mask");
agent.RecordNavMeshAgent();
agent.AreaMask = m_WalkableMask.intValue;
}
serializedObject.ApplyModifiedProperties();
}
EditorGUILayout.Space();
EditorGUILayout.LabelField(s_Styles.m_AgentBlockingHeader, EditorStyles.boldLabel);
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(
m_BlockAfterDuration,
new GUIContent("Block after Duration",
"Should the hidden agent switch from agent to obstacle if it hasn't surpassed the " +
"BlockSpeedTreshold for TimeToBlock seconds?")
);
if (EditorGUI.EndChangeCheck())
{
foreach (var agent in Agents)
{
Undo.RecordObject(agent, "Changed Block After Duration");
agent.BlockAfterDuration = m_BlockAfterDuration.boolValue;
}
serializedObject.ApplyModifiedProperties();
}
bool guiEnabled = GUI.enabled;
GUI.enabled = m_BlockAfterDuration.boolValue;
EditorGUI.indentLevel++;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(
m_TimeToBlock,
new GUIContent("Time to Block",
"Time in seconds needed for the hidden agent to switch from agent to obstacle, " +
"assuming it hasn't surpassed the BlockSpeedTreshold during the interval.")
);
if (EditorGUI.EndChangeCheck())
{
if (m_TimeToBlock.floatValue < 0.0f) m_TimeToBlock.floatValue = 0.0f;
foreach (var agent in Agents)
{
Undo.RecordObject(agent, "Changed Agent Time To Block");
agent.TimeToBlock = m_TimeToBlock.floatValue;
}
serializedObject.ApplyModifiedProperties();
}
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(
m_BlockSpeedThreshold,
new GUIContent("Block Speed Threshold",
"Speed the agent can't surpass for TimeToBlock seconds for the hidden " +
"agent to turn into an obstacle.")
);
if (EditorGUI.EndChangeCheck())
{
if (m_BlockSpeedThreshold.floatValue < 0.0f) m_BlockSpeedThreshold.floatValue = 0.0f;
foreach (var agent in Agents)
{
Undo.RecordObject(agent, "Changed Agent Block Speed Threshold");
agent.BlockSpeedThreshold = m_BlockSpeedThreshold.floatValue;
}
serializedObject.ApplyModifiedProperties();
}
GUI.enabled = guiEnabled;
EditorGUI.indentLevel--;
EditorGUILayout.LabelField("Obstacle Carving");
EditorGUI.indentLevel++;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_CarvingMoveThreshold,
new GUIContent("Carving Move Threshold",
"This refers to the hidden agent's obstacle when blocking. " +
"Threshold distance for updating a moving carved hole.")
);
if (EditorGUI.EndChangeCheck())
{
if (m_CarvingMoveThreshold.floatValue < 0.0f) m_CarvingMoveThreshold.floatValue = 0.0f;
foreach (var agent in Agents)
{
Undo.RecordObject(agent, "Changed Agent Carving Move Threshold");
agent.CarvingMoveThreshold = m_CarvingMoveThreshold.floatValue;
}
serializedObject.ApplyModifiedProperties();
}
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_TimeToStationary,
new GUIContent("Time To Stationary",
"This refers to the hidden agent's obstacle when blocking. " +
"Time to wait until the obstacle is treated as stationary (when CarveOnlyStationary is enabled).")
);
if (EditorGUI.EndChangeCheck())
{
if (m_TimeToStationary.floatValue < 0.0f) m_TimeToStationary.floatValue = 0.0f;
foreach (var agent in Agents)
{
Undo.RecordObject(agent, "Changed Agent Carving Time To Stationary");
agent.CarvingTimeToStationary = m_TimeToStationary.floatValue;
}
serializedObject.ApplyModifiedProperties();
}
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_CarveOnlyStationary,
new GUIContent("Carve Only Stationary",
"This refers to the hidden agent's obstacle when blocking. " +
"Should the obstacle be carved when it is constantly moving?")
);
if (EditorGUI.EndChangeCheck())
{
foreach (var agent in Agents)
{
Undo.RecordObject(agent, "Changed Agent Carve Only Stationary");
agent.CarveOnlyStationary = m_CarveOnlyStationary.boolValue;
}
serializedObject.ApplyModifiedProperties();
}
EditorGUI.indentLevel--;
EditorGUILayout.Space();
EditorGUILayout.LabelField(s_Styles.m_AgentUnblockingHeader, EditorStyles.boldLabel);
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(
m_UnblockAfterDuration,
new GUIContent("Unblock after Duration",
"Should the hidden agent try to find a new path every TimeToUnblock seconds, and switch from obstacle to agent " +
"when it finds one which reduces its distance to the destination by DistanceReductionThreshold?")
);
if (EditorGUI.EndChangeCheck())
{
foreach (var agent in Agents)
{
Undo.RecordObject(agent, "Changed Unblock After Duration");
agent.UnblockAfterDuration = m_UnblockAfterDuration.boolValue;
}
serializedObject.ApplyModifiedProperties();
}
GUI.enabled = m_UnblockAfterDuration.boolValue;
EditorGUI.indentLevel++;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(
m_TimeToUnblock,
new GUIContent("Time to Unblock",
"Time in seconds needed for the hidden agent to check if it should change to " +
"agent again, assuming it is currently in obstacle mode.")
);
if (EditorGUI.EndChangeCheck())
{
if (m_TimeToUnblock.floatValue < 0.0f) m_TimeToUnblock.floatValue = 0.0f;
foreach (var agent in Agents)
{
Undo.RecordObject(agent, "Changed Agent Time To Unblock");
agent.TimeToUnblock = m_TimeToUnblock.floatValue;
}
serializedObject.ApplyModifiedProperties();
}
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(
m_DistanceReductionThreshold,
new GUIContent("Distance Reduction Threshold",
"When the agent checks if it should stop blocking, this is the minimum distance the newly calculated reacheable position " +
"must be closer to the destination for it to change into an agent again.")
);
if (EditorGUI.EndChangeCheck())
{
if (m_DistanceReductionThreshold.floatValue < 0.0f) m_DistanceReductionThreshold.floatValue = 0.0f;
foreach (var agent in Agents)
{
Undo.RecordObject(agent, "Changed Distance Reduction Threshold");
agent.DistanceReductionThreshold = m_DistanceReductionThreshold.floatValue;
}
serializedObject.ApplyModifiedProperties();
}
GUI.enabled = guiEnabled;
EditorGUI.indentLevel--;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(
m_UnblockAtSpeed,
new GUIContent("Unblock At Speed",
"Should the hidden agent switch from obstacle to agent if it surpasses the UnblockSpeedTreshold?")
);
if (EditorGUI.EndChangeCheck())
{
foreach (var agent in Agents)
{
Undo.RecordObject(agent, "Changed Unblock At Speed");
agent.UnblockAtSpeed = m_UnblockAtSpeed.boolValue;
}
serializedObject.ApplyModifiedProperties();
}
GUI.enabled = m_UnblockAtSpeed.boolValue;
EditorGUI.indentLevel++;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(
m_UnblockSpeedThreshold,
new GUIContent("Unblock Speed Threshold",
"Speed at which the hidden agent turns into an agent again " +
"if it is currently in obstacle mode.")
);
if (EditorGUI.EndChangeCheck())
{
if (m_UnblockSpeedThreshold.floatValue < 0.0f) m_UnblockSpeedThreshold.floatValue = 0.0f;
foreach (var agent in Agents)
{
Undo.RecordObject(agent, "Changed Agent Unblock Speed Threshold");
agent.UnblockSpeedThreshold = m_UnblockSpeedThreshold.floatValue;
}
serializedObject.ApplyModifiedProperties();
}
GUI.enabled = guiEnabled;
EditorGUI.indentLevel--;
serializedObject.ApplyModifiedProperties();
}
private void AgentTypePopupInternal(string labelName, SerializedProperty agentTypeID)
{
var index = -1;
var count = NavMesh.GetSettingsCount();
var agentTypeNames = new string[count + 2];
for (var i = 0; i < count; i++)
{
var id = NavMesh.GetSettingsByIndex(i).agentTypeID;
var name = NavMesh.GetSettingsNameFromID(id);
agentTypeNames[i] = name;
if (id == agentTypeID.intValue)
index = i;
}
agentTypeNames[count] = "";
agentTypeNames[count + 1] = "Open Agent Settings...";
bool validAgentType = index != -1;
if (!validAgentType)
{
EditorGUILayout.HelpBox("Agent Type invalid.", MessageType.Warning);
}
var rect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight);
EditorGUI.BeginProperty(rect, GUIContent.none, agentTypeID);
EditorGUI.BeginChangeCheck();
index = EditorGUI.Popup(rect, labelName, index, agentTypeNames);
if (EditorGUI.EndChangeCheck())
{
if (index >= 0 && index < count)
{
var id = NavMesh.GetSettingsByIndex(index).agentTypeID;
agentTypeID.intValue = id;
}
else if (index == count + 1)
{
UnityEditor.AI.NavMeshEditorHelpers.OpenAgentSettings(-1);
}
foreach (var agent in Agents)
{
Undo.RecordObject(agent, "Changed Agent Type");
agent.RecordNavMeshAgent();
agent.AgentTypeID = agentTypeID.intValue;
}
serializedObject.ApplyModifiedProperties();
}
EditorGUI.EndProperty();
}
static GUIContent Temp(string t)
{
s_Text.text = t;
s_Text.tooltip = string.Empty;
return s_Text;
}
}
| 412 | 0.953111 | 1 | 0.953111 | game-dev | MEDIA | 0.951646 | game-dev | 0.96019 | 1 | 0.96019 |
justarandomgeek/vscode-factoriomod-debug | 2,089 | test/mod/control.lua | local rcall = remote.call
remote.add_interface("debugadapter-tests",{
error = function (mesg)
return error(mesg, -1)
end,
perror = function (mesg)
return pcall(error,mesg, -1)
end,
call = function(...)
return rcall(...)
end
})
local test_meta_a = {
}
script.register_metatable("test_a", test_meta_a)
function Test_A(t)
return setmetatable(t,test_meta_a)
end
---@generic K,V
---@param lct LuaCustomTable<K,V>
---@return V
local function firstof(lct)
for key, value in pairs(lct) do
return value
end
end
function Make_Test_Storage()
local a = Test_A({id=1})
local b = {[{true}]=a}
storage.test = {
a,a,{},{[b]=b,[{1}]={2},[{}]={},},
1,2,3,true,false,"foo",
game.player,
game.player.character,
game.player.cursor_stack,
game.player.force,
game.player.surface,
game.player.gui,
game.permissions,
helpers.create_profiler(true),
game.player.surface.get_tile(0,0),
firstof(game.player.force.recipes),
firstof(game.player.force.technologies),
firstof(game.permissions.groups),
firstof(prototypes.achievement),
firstof(prototypes.ammo_category),
firstof(prototypes.autoplace_control),
firstof(prototypes.custom_input),
firstof(prototypes.custom_event),
firstof(prototypes.decorative),
firstof(prototypes.damage),
firstof(prototypes.entity),
firstof(prototypes.equipment_category),
firstof(prototypes.equipment_grid),
firstof(prototypes.equipment),
firstof(prototypes.fluid),
firstof(prototypes.font),
firstof(prototypes.fuel_category),
firstof(prototypes.item_group),
firstof(prototypes.item_subgroup),
firstof(prototypes.item),
firstof(prototypes.mod_setting),
firstof(prototypes.module_category),
firstof(prototypes.named_noise_expression),
firstof(prototypes.named_noise_function),
firstof(prototypes.particle),
firstof(prototypes.recipe_category),
firstof(prototypes.recipe),
firstof(prototypes.resource_category),
firstof(prototypes.shortcut),
firstof(prototypes.technology),
firstof(prototypes.tile),
firstof(prototypes.trivial_smoke),
firstof(prototypes.virtual_signal),
}
end | 412 | 0.68813 | 1 | 0.68813 | game-dev | MEDIA | 0.769428 | game-dev,testing-qa | 0.734402 | 1 | 0.734402 |
Swarmops/Swarmops | 4,000 | Logic/Swarm/PositionAssignment.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using NBitcoin;
using Swarmops.Basic.Types.Swarm;
using Swarmops.Common;
using Swarmops.Common.Enums;
using Swarmops.Database;
using Swarmops.Logic.Security;
using Swarmops.Logic.Structure;
namespace Swarmops.Logic.Swarm
{
public class PositionAssignment: BasicPositionAssignment
{
private PositionAssignment() : base (null)
{
// do not call private null ctor
}
private PositionAssignment (BasicPositionAssignment basic) : base (basic)
{
// private ctor
}
public static PositionAssignment FromBasic (BasicPositionAssignment basic)
{
return new PositionAssignment (basic); // calls private ctor
}
public static PositionAssignment FromIdentity (int positionAssignmentId)
{
return FromBasic (SwarmDb.GetDatabaseForReading().GetPositionAssignment (positionAssignmentId));
}
public static PositionAssignment FromIdentityAggressive (int positionAssignmentId)
{
return FromBasic(SwarmDb.GetDatabaseForWriting().GetPositionAssignment(positionAssignmentId)); // "ForWriting" is intentional - avoids race conditions in Create()
}
public Person Person
{
get { return Person.FromIdentity (base.PersonId); }
}
public Position Position
{
get { return Position.FromIdentity (base.PositionId); }
}
public Geography Geography
{
get { return base.GeographyId == 0 ? null : Geography.FromIdentity (base.GeographyId); }
}
public static PositionAssignment Create(Position position, Geography geography,
Person person, Person createdByPerson, Position createdByPosition, DateTime? expiresDateTimeUtc,
string assignmentNotes)
{
int geographyId = 0;
if (position.PositionLevel == PositionLevel.Geography || position.PositionLevel == PositionLevel.GeographyDefault)
{
geographyId = geography.Identity;
}
else
{
if (geography != null)
{
throw new ArgumentException ("Geography cannot be defined when position is global");
}
}
int createdByPersonId = createdByPerson == null ? 0 : createdByPerson.Identity;
int createdByPositionId = createdByPosition == null ? 0 : createdByPosition.Identity;
// TODO: Verify constraints of max/min counts for position
int positionAssignmentId = SwarmDb.GetDatabaseForWriting()
.CreatePositionAssignment (position.OrganizationId, geographyId, position.Identity, person.Identity,
createdByPersonId, createdByPositionId,
expiresDateTimeUtc == null ? Constants.DateTimeHigh : (DateTime) expiresDateTimeUtc, assignmentNotes); // DateTime.MaxValue kills MySql layer
return FromIdentityAggressive (positionAssignmentId);
}
public void Terminate (Person terminatingPerson, Position terminatingPosition, string terminationNotes)
{
// TODO: ADD ACCESS CONTROL AT LOGIC LAYER
SwarmDb.GetDatabaseForWriting()
.TerminatePositionAssignment (this.Identity, terminatingPerson.Identity, terminatingPosition.Identity,
terminationNotes);
base.TerminatedByPersonId = terminatingPerson.Identity;
base.TerminatedByPositionId = terminatingPosition.Identity;
base.Active = false;
base.TerminationNotes = terminationNotes;
base.TerminatedDateTimeUtc = DateTime.UtcNow; // may differ by milliseconds from actual value set, but shouldn't matter for practical purposes
}
}
}
| 412 | 0.652794 | 1 | 0.652794 | game-dev | MEDIA | 0.202607 | game-dev | 0.846288 | 1 | 0.846288 |
Skytils/SkytilsMod | 4,210 | mod/versions/1.8.9-forge/src/main/kotlin/gg/skytils/skytilsmod/features/impl/handlers/NamespacedCommands.kt | /*
* Skytils - Hypixel Skyblock Quality of Life Mod
* Copyright (C) 2020-2024 Skytils
*
* 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 <https://www.gnu.org/licenses/>.
*/
package gg.skytils.skytilsmod.features.impl.handlers
import gg.essential.universal.UChat
import gg.skytils.event.EventSubscriber
import gg.skytils.event.impl.play.ChatMessageSentEvent
import gg.skytils.event.register
import gg.skytils.skytilsmod.Skytils.mc
import gg.skytils.skytilsmod.mixins.transformers.accessors.AccessorCommandHandler
import gg.skytils.skytilsmod.utils.ObservableAddEvent
import gg.skytils.skytilsmod.utils.ObservableClearEvent
import gg.skytils.skytilsmod.utils.ObservableRemoveEvent
import gg.skytils.skytilsmod.utils.ObservableSet
import net.minecraft.command.ICommand
import net.minecraftforge.client.ClientCommandHandler
import net.minecraftforge.fml.common.Loader
import net.minecraftforge.fml.common.ModContainer
/**
* Namespaced commands is a feature which generates namespaces for commands.
*
* For example, when a mod adds reparty, namespaced commands will generate
* a command that includes the id/name of the mod
*
* `/mod:reparty`
*
* This is useful when multiple mods register a command with the same name
*/
object NamespacedCommands : EventSubscriber {
val cch by lazy {
ClientCommandHandler.instance as AccessorCommandHandler
}
val aliasMap = mutableMapOf<ICommand, String>()
fun setup(listeningSet: ObservableSet<ICommand>) {
listeningSet.addObserver { _, arg ->
when (arg) {
is ObservableAddEvent<*> -> {
registerCommandHelper(arg.element as ICommand)
}
is ObservableRemoveEvent<*> -> {
cch.commandMap.remove(aliasMap.remove(arg.element))
}
is ObservableClearEvent<*> -> {
aliasMap.entries.removeAll {
cch.commandMap.remove(it.value)
true
}
}
}
}
listeningSet.forEach {
registerCommandHelper(it)
}
}
/**
* This method takes a command and registers the command's namespaced version.
*/
fun registerCommandHelper(command: ICommand) {
val owners = getCommandModOwner(command.javaClass)
if (owners.size != 1) {
println("WARNING! Command ${command.commandName} has ${owners.size}; owners: $owners")
}
val owner = owners.firstOrNull()
val prefix = owner?.modId ?: owner?.name ?: "unknown"
val helper = "${prefix}:${command.commandName}"
cch.commandMap[helper] = command
aliasMap[command] = helper
}
fun getCommandModOwner(command: Class<*>) : List<ModContainer> {
val idx = command.name.lastIndexOf(".")
if (idx == -1) return emptyList()
val packageName = command.name.substring(0, idx)
return Loader.instance().modList.filter { packageName in it.ownedPackages }
}
/**
* Handles the actual sending of the command.
*
* When a command is sent using the `server` namespace, it is passed directly to the server
* instead of running a client command.
*/
fun onSendChat(event: ChatMessageSentEvent) {
if (event.message.startsWith("/server:")) {
event.cancelled = true
UChat.say('/' + event.message.substringAfter("/server:"))
mc.ingameGUI.chatGUI.addToSentMessages(event.message)
}
}
override fun setup() {
register(::onSendChat)
}
} | 412 | 0.911104 | 1 | 0.911104 | game-dev | MEDIA | 0.746801 | game-dev | 0.690399 | 1 | 0.690399 |
ilpincy/argos3 | 10,739 | src/core/simulator/physics_engine/physics_engine.cpp | /**
* @file <argos3/core/simulator/physics_engine/physics_engine.cpp>
*
* @author Carlo Pinciroli - <ilpincy@gmail.com>
*/
#include <cstdlib>
#include "physics_engine.h"
#include <argos3/core/utility/logging/argos_log.h>
#include <argos3/core/utility/math/vector3.h>
#include <argos3/core/utility/string_utilities.h>
#include <argos3/core/simulator/simulator.h>
#include <argos3/core/simulator/space/space.h>
#include <argos3/core/simulator/entity/entity.h>
namespace argos {
/****************************************/
/****************************************/
bool GetEmbodiedEntitiesIntersectedByRay(TEmbodiedEntityIntersectionData& t_data,
const CRay3& c_ray) {
/* This variable is instantiated at the first call of this function, once and forever */
static CSimulator& cSimulator = CSimulator::GetInstance();
/* Clear data */
t_data.clear();
/* Create a reference to the vector of physics engines */
CPhysicsEngine::TVector& vecEngines = cSimulator.GetPhysicsEngines();
/* Ask each engine to perform the ray query */
for(size_t i = 0; i < vecEngines.size(); ++i)
vecEngines[i]->CheckIntersectionWithRay(t_data, c_ray);
/* Remove duplicates */
// TODO
/* Return true if an intersection was found */
return !t_data.empty();
}
/****************************************/
/****************************************/
bool GetClosestEmbodiedEntityIntersectedByRay(SEmbodiedEntityIntersectionItem& s_item,
const CRay3& c_ray) {
/* Initialize s_item */
s_item.IntersectedEntity = nullptr;
s_item.TOnRay = 1.0f;
/* Perform full ray query */
TEmbodiedEntityIntersectionData tData;
GetEmbodiedEntitiesIntersectedByRay(tData, c_ray);
/* Go through intersections and find the closest */
for(size_t i = 0; i < tData.size(); ++i) {
if(s_item.TOnRay > tData[i].TOnRay)
s_item = tData[i];
}
/* Return true if an intersection was found */
return (s_item.IntersectedEntity != nullptr);
}
/****************************************/
/****************************************/
bool GetClosestEmbodiedEntityIntersectedByRay(SEmbodiedEntityIntersectionItem& s_item,
const CRay3& c_ray,
CEmbodiedEntity& c_entity) {
/* Initialize s_item */
s_item.IntersectedEntity = nullptr;
s_item.TOnRay = 1.0f;
/* Perform full ray query */
TEmbodiedEntityIntersectionData tData;
GetEmbodiedEntitiesIntersectedByRay(tData, c_ray);
/* Go through intersections and find the closest */
for(size_t i = 0; i < tData.size(); ++i) {
if(s_item.TOnRay > tData[i].TOnRay &&
&c_entity != tData[i].IntersectedEntity) {
s_item = tData[i];
}
}
/* Return true if an intersection was found */
return (s_item.IntersectedEntity != nullptr);
}
/****************************************/
/****************************************/
/* The default value of the simulation clock tick */
Real CPhysicsEngine::m_fSimulationClockTick = 0.1f;
Real CPhysicsEngine::m_fInverseSimulationClockTick = 1.0f / CPhysicsEngine::m_fSimulationClockTick;
/****************************************/
/****************************************/
CPhysicsEngine::SVolume::SVolume() :
TopFace(nullptr),
BottomFace(nullptr) {
}
/****************************************/
/****************************************/
void CPhysicsEngine::SVolume::Init(TConfigurationNode& t_node) {
try {
/* Parse top face, if specified */
if(NodeExists(t_node, "top")) {
TConfigurationNode& tNode = GetNode(t_node, "top");
TopFace = new SHorizontalFace;
GetNodeAttribute(tNode, "height", TopFace->Height);
}
/* Parse bottom face, if specified */
if(NodeExists(t_node, "bottom")) {
TConfigurationNode& tNode = GetNode(t_node, "bottom");
BottomFace = new SHorizontalFace;
GetNodeAttribute(tNode, "height", BottomFace->Height);
}
/* Parse side faces, if specified */
if(NodeExists(t_node, "sides")) {
CVector2 cFirstPoint, cLastPoint, cCurPoint;
std::string strConnectWith;
TConfigurationNode& tNode = GetNode(t_node, "sides");
TConfigurationNodeIterator tVertexIt("vertex");
/* Get the first vertex */
tVertexIt = tVertexIt.begin(&tNode);
if(tVertexIt == tVertexIt.end()) {
THROW_ARGOSEXCEPTION("No <vertex> specified within <sides> section");
}
GetNodeAttribute(*tVertexIt, "point", cFirstPoint);
cLastPoint = cFirstPoint;
/* Go through the other vertices */
++tVertexIt;
while(tVertexIt != tVertexIt.end()) {
/* Read vertex data and fill in segment struct */
GetNodeAttribute(*tVertexIt, "point", cCurPoint);
auto* psFace = new SVerticalFace;
psFace->BaseSegment.SetStart(cLastPoint);
psFace->BaseSegment.SetEnd(cCurPoint);
SideFaces.push_back(psFace);
/* Next vertex */
cLastPoint = cCurPoint;
++tVertexIt;
}
/* Make sure that the boundary is a closed path */
if(SideFaces.size() < 3) {
THROW_ARGOSEXCEPTION("The <sides> path is not closed; at least 3 segments must be specified");
}
if(cLastPoint != cFirstPoint) {
auto* psFace = new SVerticalFace;
psFace->BaseSegment.SetStart(cLastPoint);
psFace->BaseSegment.SetEnd(cFirstPoint);
SideFaces.push_back(psFace);
}
}
}
catch(CARGoSException& ex) {
THROW_ARGOSEXCEPTION_NESTED("Error parsing physics engine <boundaries> information", ex);
}
}
/****************************************/
/****************************************/
CPhysicsEngine::SVolume::~SVolume() {
if(TopFace) delete TopFace;
if(BottomFace) delete BottomFace;
while(!SideFaces.empty()) {
delete SideFaces.back();
SideFaces.pop_back();
}
}
/****************************************/
/****************************************/
bool CPhysicsEngine::SVolume::IsActive() const {
return TopFace || BottomFace || (!SideFaces.empty());
}
/****************************************/
/****************************************/
CPhysicsEngine::CPhysicsEngine() :
m_unIterations(10),
m_fPhysicsClockTick(m_fSimulationClockTick) {}
/****************************************/
/****************************************/
void CPhysicsEngine::Init(TConfigurationNode& t_tree) {
try {
/* Get id from the XML */
GetNodeAttribute(t_tree, "id", m_strId);
/* Get iterations per time step */
GetNodeAttributeOrDefault(t_tree, "iterations", m_unIterations, m_unIterations);
m_fPhysicsClockTick = GetSimulationClockTick() / static_cast<Real>(m_unIterations);
LOG << "[INFO] The physics engine \""
<< GetId()
<< "\" will perform "
<< m_unIterations
<< " iterations per tick (dt = "
<< GetPhysicsClockTick() << " sec)"
<< std::endl;
/* Parse the boundary definition, if necessary */
if(NodeExists(t_tree, "boundaries")) {
m_sVolume.Init(GetNode(t_tree, "boundaries"));
}
}
catch(CARGoSException& ex) {
THROW_ARGOSEXCEPTION_NESTED("Error initializing a physics engine", ex);
}
}
/****************************************/
/****************************************/
bool CPhysicsEngine::IsPointContained(const CVector3& c_point) {
if(! IsEntityTransferActive()) {
/*
* The engine has no boundaries, so the wanted point is in for sure
*/
return true;
}
else {
/*
* Check the boundaries
*/
/* Check top/bottom boundaries */
if((m_sVolume.TopFace && c_point.GetZ() > m_sVolume.TopFace->Height) ||
(m_sVolume.BottomFace && c_point.GetZ() < m_sVolume.BottomFace->Height)) {
return false;
}
/* Check side boundaries */
for(size_t i = 0; i < GetVolume().SideFaces.size(); ++i) {
const CVector2& cP0 = GetVolume().SideFaces[i]->BaseSegment.GetStart();
const CVector2& cP1 = GetVolume().SideFaces[i]->BaseSegment.GetEnd();
Real fCriterion =
(c_point.GetY() - cP0.GetY()) * (cP1.GetX() - cP0.GetX()) -
(c_point.GetX() - cP0.GetX()) * (cP1.GetY() - cP0.GetY());
if(fCriterion < 0.0f) {
return false;
}
}
return true;
}
}
/****************************************/
/****************************************/
void CPhysicsEngine::ScheduleEntityForTransfer(CEmbodiedEntity& c_entity) {
m_vecTransferData.push_back(&c_entity);
}
/****************************************/
/****************************************/
void CPhysicsEngine::TransferEntities() {
for(size_t i = 0; i < m_vecTransferData.size(); ++i) {
RemoveEntity(m_vecTransferData[i]->GetRootEntity());
CSimulator::GetInstance().GetSpace().AddEntityToPhysicsEngine(*m_vecTransferData[i]);
}
m_vecTransferData.clear();
}
/****************************************/
/****************************************/
Real CPhysicsEngine::GetSimulationClockTick() {
return m_fSimulationClockTick;
}
/****************************************/
/****************************************/
Real CPhysicsEngine::GetInverseSimulationClockTick() {
return m_fInverseSimulationClockTick;
}
/****************************************/
/****************************************/
void CPhysicsEngine::SetSimulationClockTick(Real f_simulation_clock_tick) {
LOG << "[INFO] Using simulation clock tick = " << f_simulation_clock_tick << std::endl;
m_fSimulationClockTick = f_simulation_clock_tick;
m_fInverseSimulationClockTick = 1.0f / f_simulation_clock_tick;
}
/****************************************/
/****************************************/
}
| 412 | 0.943446 | 1 | 0.943446 | game-dev | MEDIA | 0.540874 | game-dev | 0.972324 | 1 | 0.972324 |
The-Cataclysm-Preservation-Project/TrinityCore | 7,574 | src/server/game/Reputation/ReputationMgr.h | /*
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __TRINITY_REPUTATION_MGR_H
#define __TRINITY_REPUTATION_MGR_H
#include "Common.h"
#include "SharedDefines.h"
#include "Language.h"
#include "DBCStructure.h"
#include "QueryResult.h"
#include <map>
static uint32 ReputationRankStrIndex[MAX_REPUTATION_RANK] =
{
LANG_REP_HATED, LANG_REP_HOSTILE, LANG_REP_UNFRIENDLY, LANG_REP_NEUTRAL,
LANG_REP_FRIENDLY, LANG_REP_HONORED, LANG_REP_REVERED, LANG_REP_EXALTED
};
enum FactionFlags
{
FACTION_FLAG_NONE = 0x00, // no faction flag
FACTION_FLAG_VISIBLE = 0x01, // makes visible in client (set or can be set at interaction with target of this faction)
FACTION_FLAG_AT_WAR = 0x02, // enable AtWar-button in client. player controlled (except opposition team always war state), Flag only set on initial creation
FACTION_FLAG_HIDDEN = 0x04, // hidden faction from reputation pane in client (player can gain reputation, but this update not sent to client)
FACTION_FLAG_INVISIBLE_FORCED = 0x08, // always overwrite FACTION_FLAG_VISIBLE and hide faction in rep.list, used for hide opposite team factions
FACTION_FLAG_PEACE_FORCED = 0x10, // always overwrite FACTION_FLAG_AT_WAR, used for prevent war with own team factions
FACTION_FLAG_INACTIVE = 0x20, // player controlled, state stored in characters.data (CMSG_SET_FACTION_INACTIVE)
FACTION_FLAG_RIVAL = 0x40, // flag for the two competing outland factions
FACTION_FLAG_SPECIAL = 0x80 // horde and alliance home cities and their northrend allies have this flag
};
typedef uint32 RepListID;
struct FactionState
{
uint32 ID;
RepListID ReputationListID;
int32 Standing;
uint8 Flags;
bool needSend;
bool needSave;
};
typedef std::map<RepListID, FactionState> FactionStateList;
typedef std::map<uint32, ReputationRank> ForcedReactions;
class Player;
class TC_GAME_API ReputationMgr
{
public: // constructors and global modifiers
explicit ReputationMgr(Player* owner) : _player(owner),
_visibleFactionCount(0), _honoredFactionCount(0), _reveredFactionCount(0), _exaltedFactionCount(0), _sendFactionIncreased(false) { }
~ReputationMgr() { }
void SaveToDB(CharacterDatabaseTransaction& trans);
void LoadFromDB(PreparedQueryResult result);
public: // statics
static const int32 PointsInRank[MAX_REPUTATION_RANK];
static const int32 Reputation_Cap;
static const int32 Reputation_Bottom;
static ReputationRank ReputationToRank(int32 standing);
public: // accessors
uint8 GetVisibleFactionCount() const { return _visibleFactionCount; }
uint8 GetHonoredFactionCount() const { return _honoredFactionCount; }
uint8 GetReveredFactionCount() const { return _reveredFactionCount; }
uint8 GetExaltedFactionCount() const { return _exaltedFactionCount; }
FactionStateList const& GetStateList() const { return _factions; }
FactionState const* GetState(FactionEntry const* factionEntry) const
{
return factionEntry->CanHaveReputation() ? GetState(factionEntry->ReputationIndex) : nullptr;
}
FactionState const* GetState(RepListID id) const
{
FactionStateList::const_iterator repItr = _factions.find (id);
return repItr != _factions.end() ? &repItr->second : nullptr;
}
bool IsAtWar(uint32 faction_id) const;
bool IsAtWar(FactionEntry const* factionEntry) const;
int32 GetReputation(uint32 faction_id) const;
int32 GetReputation(FactionEntry const* factionEntry) const;
int32 GetBaseReputation(FactionEntry const* factionEntry) const;
ReputationRank GetRank(FactionEntry const* factionEntry) const;
ReputationRank GetBaseRank(FactionEntry const* factionEntry) const;
uint32 GetReputationRankStrIndex(FactionEntry const* factionEntry) const
{
return ReputationRankStrIndex[GetRank(factionEntry)];
};
ReputationRank const* GetForcedRankIfAny(FactionTemplateEntry const* factionTemplateEntry) const
{
ForcedReactions::const_iterator forceItr = _forcedReactions.find(factionTemplateEntry->Faction);
return forceItr != _forcedReactions.end() ? &forceItr->second : nullptr;
}
public: // modifiers
bool SetReputation(FactionEntry const* factionEntry, int32 standing)
{
return SetReputation(factionEntry, standing, false, false);
}
bool ModifyReputation(FactionEntry const* factionEntry, int32 standing, bool spillOverOnly = false)
{
return SetReputation(factionEntry, standing, true, spillOverOnly);
}
void SetVisible(FactionTemplateEntry const* factionTemplateEntry);
void SetVisible(FactionEntry const* factionEntry);
void SetAtWar(RepListID repListID, bool on);
void SetInactive(RepListID repListID, bool on);
void ApplyForceReaction(uint32 faction_id, ReputationRank rank, bool apply);
//! Public for chat command needs
bool SetOneFactionReputation(FactionEntry const* factionEntry, int32 standing, bool incremental);
public: // senders
void SendInitialReputations();
void SendForceReactions();
void SendState(FactionState const* faction);
private: // internal helper functions
void Initialize();
uint32 GetDefaultStateFlags(FactionEntry const* factionEntry) const;
bool SetReputation(FactionEntry const* factionEntry, int32 standing, bool incremental, bool spillOverOnly);
void SetVisible(FactionState* faction);
void SetAtWar(FactionState* faction, bool atWar) const;
void SetInactive(FactionState* faction, bool inactive) const;
void SendVisible(FactionState const* faction, bool visible = true) const;
void UpdateRankCounters(ReputationRank old_rank, ReputationRank new_rank);
private:
Player* _player;
FactionStateList _factions;
ForcedReactions _forcedReactions;
uint8 _visibleFactionCount :8;
uint8 _honoredFactionCount :8;
uint8 _reveredFactionCount :8;
uint8 _exaltedFactionCount :8;
bool _sendFactionIncreased; //! Play visual effect on next SMSG_SET_FACTION_STANDING sent
};
#endif
| 412 | 0.77016 | 1 | 0.77016 | game-dev | MEDIA | 0.898597 | game-dev | 0.853152 | 1 | 0.853152 |
BLCM/BLCMods | 4,560 | Borderlands 2 mods/MW2366/Class Mods/RefactoredHoarder | #####################################################
Refactored Hoarder COM
I decided to refactor the Hoarder mod so it's a little more useful in terms of money shot chains... 5 Shots or 6 doesn't really work too well with Inconceivable, and I decided that Filled to the Brim wasn't all that used/useful in my builds. Just Got Real is probably more useful than an 80% chance to not consume a large magazine.
If anyone can make a +1/+2/+3 Green-Purple-Blue mod for Inconceivable using the formula's below, feel free to modify it. - Foreststrike
+Team Ammo Regen
+4-6 Lay Waste
+4-6 Just Got Real
+1/+3 Inconceivable
#####################################################
set GD_ClassMods.A_Item_Merc.ClassMod_Merc_Hoarder UIStatList ((bDisplayAsModifierOnly=True,AttributeStyle=ATTRSTYLE_ModifierText,SupplementalAttributeStyle=ATTRSTYLE_JustNumber,StatCombinationMethod=SCM_Multiply,Attribute=AttributeDefinition'D_Attributes.GameplayAttributes.PlayerCurrentWeaponAmmoRegenerationMultiplier',ConstraintAttribute=AttributeDefinition'GD_ClassMods.Misc.Att_TeamConstraint',SupplementalAttributeExpression=(AttributeOperand1=None,ComparisonOperator=OPERATOR_EqualTo,Operand2Usage=OPERAND_PreferAttribute,AttributeOperand2=None,ConstantOperand2=0.000000),SupplementalAttributeToAppend=None))
set GD_ClassMods.A_Item_Merc.ClassMod_Merc_Hoarder AttributeSlotEffects ((SlotName="PrimaryStatBonus",bExternalSlot=True,bRunEffectsAsSkill=True,AttributeToModify=AttributeDefinition'D_Attributes.GameplayAttributes.PlayerCurrentWeaponAmmoRegenerationMultiplier',ConstraintAttribute=AttributeDefinition'GD_ClassMods.Misc.Att_TeamConstraint',ModifierType=MT_PostAdd,BaseModifierValue=(BaseValueConstant=0.000000,BaseValueAttribute=None,InitializationDefinition=AttributeInitializationDefinition'GD_ClassMods.Misc.Init_StatBonus_AmmoRegen',BaseValueScaleConstant=1.000000),PerGradeUpgrade=(BaseValueConstant=0.100000,BaseValueAttribute=None,InitializationDefinition=None,BaseValueScaleConstant=1.000000),bIncludeInFunStats=False,bIncludeAlliesAsTarget=True,bEnforceMinimumGrade=True,bEnforceMaximumGrade=False,MinimumGrade=0,MaximumGrade=0,TargetInstanceDataName=),(SlotName="Skill1",bExternalSlot=True,bRunEffectsAsSkill=True,AttributeToModify=InventoryAttributeDefinition'GD_Mercenary_Skills.SkillGradeModifiers.LayWaste',ConstraintAttribute=None,ModifierType=MT_PostAdd,BaseModifierValue=(BaseValueConstant=0.000000,BaseValueAttribute=None,InitializationDefinition=AttributeInitializationDefinition'GD_ClassMods.Misc.Init_BaseSkillPointCalculation',BaseValueScaleConstant=1.000000),PerGradeUpgrade=(BaseValueConstant=0.340000,BaseValueAttribute=None,InitializationDefinition=None,BaseValueScaleConstant=1.000000),bIncludeInFunStats=True,bIncludeAlliesAsTarget=False,bEnforceMinimumGrade=True,bEnforceMaximumGrade=False,MinimumGrade=0,MaximumGrade=0,TargetInstanceDataName=),(SlotName="Skill2",bExternalSlot=True,bRunEffectsAsSkill=True,AttributeToModify=InventoryAttributeDefinition'GD_Mercenary_Skills.SkillGradeModifiers.Inconceivable',ConstraintAttribute=None,ModifierType=MT_PostAdd,BaseModifierValue=(BaseValueConstant=1.000000,BaseValueAttribute=None,InitializationDefinition=AttributeInitializationDefinition'GD_ClassMods.Misc.Init_BaseSkillPointCalculation',BaseValueScaleConstant=0.000000),PerGradeUpgrade=(BaseValueConstant=1.00000,BaseValueAttribute=None,InitializationDefinition=None,BaseValueScaleConstant=0.600000),bIncludeInFunStats=True,bIncludeAlliesAsTarget=False,bEnforceMinimumGrade=False,bEnforceMaximumGrade=False,MinimumGrade=0,MaximumGrade=0,TargetInstanceDataName=),(SlotName="Skill3",bExternalSlot=True,bRunEffectsAsSkill=True,AttributeToModify=InventoryAttributeDefinition'GD_Mercenary_Skills.SkillGradeModifiers.JustGotReal',ConstraintAttribute=None,ModifierType=MT_PostAdd,BaseModifierValue=(BaseValueConstant=0.000000,BaseValueAttribute=None,InitializationDefinition=AttributeInitializationDefinition'GD_ClassMods.Misc.Init_BaseSkillPointCalculation',BaseValueScaleConstant=1.000000),PerGradeUpgrade=(BaseValueConstant=0.340000,BaseValueAttribute=None,InitializationDefinition=None,BaseValueScaleConstant=1.000000),bIncludeInFunStats=True,bIncludeAlliesAsTarget=False,bEnforceMinimumGrade=True,bEnforceMaximumGrade=False,MinimumGrade=0,MaximumGrade=0,TargetInstanceDataName=))
set GD_ClassMods.Prefix_Merc.Prefix_Hoarder_01_UnhingedHoarder PartName Unhinged Hoarder
set GD_ClassMods.Prefix_Merc.Prefix_Hoarder_02_LuckyHoarder PartName Lucky Hoarder
set GD_ClassMods.Prefix_Merc.Prefix_Hoarder_03_LoadedHoarder PartName Savage Hoarder
| 412 | 0.88859 | 1 | 0.88859 | game-dev | MEDIA | 0.297569 | game-dev | 0.578422 | 1 | 0.578422 |
cake-lab/ARFlow | 1,376 | unity/Assets/Samples/XR Interaction Toolkit/3.0.6/Starter Assets/DemoSceneAssets/Scripts/IncrementUIText.cs | using UnityEngine.UI;
namespace UnityEngine.XR.Interaction.Toolkit.Samples.StarterAssets
{
/// <summary>
/// Add this component to a GameObject and call the <see cref="IncrementText"/> method
/// in response to a Unity Event to update a text display to count up with each event.
/// </summary>
public class IncrementUIText : MonoBehaviour
{
[SerializeField]
[Tooltip("The Text component this behavior uses to display the incremented value.")]
Text m_Text;
/// <summary>
/// The Text component this behavior uses to display the incremented value.
/// </summary>
public Text text
{
get => m_Text;
set => m_Text = value;
}
int m_Count;
/// <summary>
/// See <see cref="MonoBehaviour"/>.
/// </summary>
protected void Awake()
{
if (m_Text == null)
Debug.LogWarning("Missing required Text component reference. Use the Inspector window to assign which Text component to increment.", this);
}
/// <summary>
/// Increment the string message of the Text component.
/// </summary>
public void IncrementText()
{
m_Count += 1;
if (m_Text != null)
m_Text.text = m_Count.ToString();
}
}
}
| 412 | 0.628727 | 1 | 0.628727 | game-dev | MEDIA | 0.700061 | game-dev | 0.698864 | 1 | 0.698864 |
lzk228/space-axolotl-14 | 11,029 | Content.Shared/Teleportation/Systems/SharedPortalSystem.cs | using System.Linq;
using Content.Shared.Ghost;
using Content.Shared.Movement.Pulling.Components;
using Content.Shared.Movement.Pulling.Systems;
using Content.Shared.Popups;
using Content.Shared.Projectiles;
using Content.Shared.Teleportation.Components;
using Content.Shared.Verbs;
using Robust.Shared.Audio.Systems;
using Robust.Shared.Map;
using Robust.Shared.Network;
using Robust.Shared.Physics.Dynamics;
using Robust.Shared.Physics.Events;
using Robust.Shared.Player;
using Robust.Shared.Random;
using Robust.Shared.Utility;
namespace Content.Shared.Teleportation.Systems;
/// <summary>
/// This handles teleporting entities from a portal to a linked portal, or to a random nearby destination.
/// Uses <see cref="LinkedEntitySystem"/> to get linked portals.
/// </summary>
/// <seealso cref="PortalComponent"/>
public abstract class SharedPortalSystem : EntitySystem
{
[Dependency] private readonly IRobustRandom _random = default!;
[Dependency] private readonly INetManager _netMan = default!;
[Dependency] private readonly EntityLookupSystem _lookup = default!;
[Dependency] private readonly SharedAudioSystem _audio = default!;
[Dependency] private readonly SharedTransformSystem _transform = default!;
[Dependency] private readonly PullingSystem _pulling = default!;
[Dependency] private readonly SharedPopupSystem _popup = default!;
private const string PortalFixture = "portalFixture";
private const string ProjectileFixture = "projectile";
private const int MaxRandomTeleportAttempts = 20;
/// <inheritdoc/>
public override void Initialize()
{
SubscribeLocalEvent<PortalComponent, GetVerbsEvent<AlternativeVerb>>(OnGetVerbs);
SubscribeLocalEvent<PortalComponent, StartCollideEvent>(OnCollide);
SubscribeLocalEvent<PortalComponent, EndCollideEvent>(OnEndCollide);
}
private void OnGetVerbs(Entity<PortalComponent> ent, ref GetVerbsEvent<AlternativeVerb> args)
{
// Traversal altverb for ghosts to use that bypasses normal functionality
if (!args.CanAccess || !HasComp<GhostComponent>(args.User))
return;
// Don't use the verb with unlinked or with multi-output portals
// (this is only intended to be useful for ghosts to see where a linked portal leads)
var disabled = !TryComp<LinkedEntityComponent>(ent, out var link) || link.LinkedEntities.Count != 1;
var subject = args.User;
args.Verbs.Add(new AlternativeVerb
{
Priority = 11,
Act = () =>
{
if (link == null || disabled)
return;
// check prediction
if (_netMan.IsClient && !CanPredictTeleport((ent, link)))
return;
var destination = link.LinkedEntities.First();
TeleportEntity(ent, subject, Transform(destination).Coordinates, destination, false);
},
Disabled = disabled,
Text = Loc.GetString("portal-component-ghost-traverse"),
Message = disabled
? Loc.GetString("portal-component-no-linked-entities")
: Loc.GetString("portal-component-can-ghost-traverse"),
Icon = new SpriteSpecifier.Texture(new("/Textures/Interface/VerbIcons/open.svg.192dpi.png"))
});
}
private void OnCollide(Entity<PortalComponent> ent, ref StartCollideEvent args)
{
if (!ShouldCollide(args.OurFixtureId, args.OtherFixtureId, args.OurFixture, args.OtherFixture))
return;
var subject = args.OtherEntity;
// best not.
if (Transform(subject).Anchored)
return;
// break pulls before portal enter so we don't break shit
if (TryComp<PullableComponent>(subject, out var pullable) && pullable.BeingPulled)
{
_pulling.TryStopPull(subject, pullable);
}
if (TryComp<PullerComponent>(subject, out var pullerComp)
&& TryComp<PullableComponent>(pullerComp.Pulling, out var subjectPulling))
{
_pulling.TryStopPull(pullerComp.Pulling.Value, subjectPulling);
}
// if they came from another portal, just return and wait for them to exit the portal
if (HasComp<PortalTimeoutComponent>(subject))
{
return;
}
if (TryComp<LinkedEntityComponent>(ent, out var link))
{
if (link.LinkedEntities.Count == 0)
return;
// check prediction
if (_netMan.IsClient && !CanPredictTeleport((ent, link)))
return;
// pick a target and teleport there
var target = _random.Pick(link.LinkedEntities);
if (HasComp<PortalComponent>(target))
{
// if target is a portal, signal that they shouldn't be immediately teleported back
var timeout = EnsureComp<PortalTimeoutComponent>(subject);
timeout.EnteredPortal = ent;
Dirty(subject, timeout);
}
TeleportEntity(ent, subject, Transform(target).Coordinates, target);
return;
}
if (_netMan.IsClient)
return;
// no linked entity--teleport randomly
if (ent.Comp.RandomTeleport)
TeleportRandomly(ent, subject);
}
private void OnEndCollide(Entity<PortalComponent> ent, ref EndCollideEvent args)
{
if (!ShouldCollide(args.OurFixtureId, args.OtherFixtureId, args.OurFixture, args.OtherFixture))
return;
var subject = args.OtherEntity;
// if they came from a different portal, remove the timeout
if (TryComp<PortalTimeoutComponent>(subject, out var timeout) && timeout.EnteredPortal != ent)
{
RemCompDeferred<PortalTimeoutComponent>(subject);
}
}
/// <summary>
/// Checks if the colliding fixtures are the ones we want.
/// </summary>
/// <returns>
/// False if our fixture is not a portal fixture.
/// False if other fixture is not hard, but makes an exception for projectiles.
/// </returns>
private bool ShouldCollide(string ourId, string otherId, Fixture our, Fixture other)
{
return ourId == PortalFixture && (other.Hard || otherId == ProjectileFixture);
}
/// <summary>
/// Checks if the client is able to predict the teleport.
/// Client can't predict outside 1-to-1 portal-to-portal interactions due to randomness involved.
/// </summary>
/// <returns>
/// False if the linked entity count isn't 1.
/// False if the linked entity doesn't exist on the client / is outside PVS.
/// </returns>
private bool CanPredictTeleport(Entity<LinkedEntityComponent> portal)
{
var first = portal.Comp.LinkedEntities.First();
var exists = Exists(first);
if (!exists ||
portal.Comp.LinkedEntities.Count != 1 || // 0 and >1 use RNG
exists && Transform(first).MapID == MapId.Nullspace) // The linked entity is most likely outside PVS
return false;
return true;
}
/// <summary>
/// Handles teleporting a subject from the portal entity to a coordinate.
/// Also deletes invalid portals.
/// </summary>
/// <param name="ent"> The portal being collided with. </param>
/// <param name="subject"> The entity getting teleported. </param>
/// <param name="target"> The location to teleport to. </param>
/// <param name="targetEntity"> The portal on the other side of the teleport. </param>
private void TeleportEntity(Entity<PortalComponent> ent, EntityUid subject, EntityCoordinates target, EntityUid? targetEntity = null, bool playSound = true)
{
var ourCoords = Transform(ent).Coordinates;
var onSameMap = _transform.GetMapId(ourCoords) == _transform.GetMapId(target);
var distanceInvalid = ent.Comp.MaxTeleportRadius != null
&& ourCoords.TryDistance(EntityManager, target, out var distance)
&& distance > ent.Comp.MaxTeleportRadius;
// Early out if this is an invalid configuration
if (!onSameMap && !ent.Comp.CanTeleportToOtherMaps || distanceInvalid)
{
if (_netMan.IsClient)
return;
_popup.PopupCoordinates(Loc.GetString("portal-component-invalid-configuration-fizzle"),
ourCoords, Filter.Pvs(ourCoords, entityMan: EntityManager), true);
_popup.PopupCoordinates(Loc.GetString("portal-component-invalid-configuration-fizzle"),
target, Filter.Pvs(target, entityMan: EntityManager), true);
QueueDel(ent);
if (targetEntity != null)
QueueDel(targetEntity.Value);
return;
}
var arrivalSound = CompOrNull<PortalComponent>(targetEntity)?.ArrivalSound ?? ent.Comp.ArrivalSound;
var departureSound = ent.Comp.DepartureSound;
// Some special cased stuff: projectiles should stop ignoring shooter when they enter a portal, to avoid
// stacking 500 bullets in between 2 portals and instakilling people--you'll just hit yourself instead
// (as expected)
if (TryComp<ProjectileComponent>(subject, out var projectile))
{
projectile.IgnoreShooter = false;
}
LogTeleport(ent, subject, Transform(subject).Coordinates, target);
_transform.SetCoordinates(subject, target);
if (!playSound)
return;
_audio.PlayPredicted(departureSound, ent, subject);
_audio.PlayPredicted(arrivalSound, subject, subject);
}
/// <summary>
/// Finds a random coordinate within the portal's radius and teleports the subject there.
/// Attempts to not put the subject inside a static entity (e.g. wall).
/// </summary>
/// <param name="ent"> The portal being collided with. </param>
/// <param name="subject"> The entity getting teleported. </param>
private void TeleportRandomly(Entity<PortalComponent> ent, EntityUid subject)
{
var xform = Transform(ent);
var coords = xform.Coordinates;
var newCoords = coords.Offset(_random.NextVector2(ent.Comp.MaxRandomRadius));
for (var i = 0; i < MaxRandomTeleportAttempts; i++)
{
var randVector = _random.NextVector2(ent.Comp.MaxRandomRadius);
newCoords = coords.Offset(randVector);
if (!_lookup.AnyEntitiesIntersecting(_transform.ToMapCoordinates(newCoords), LookupFlags.Static))
{
// newCoords is not a wall
break;
}
// after "MaxRandomTeleportAttempts" attempts, end up in the walls
}
TeleportEntity(ent, subject, newCoords);
}
protected virtual void LogTeleport(EntityUid portal, EntityUid subject, EntityCoordinates source,
EntityCoordinates target)
{
}
}
| 412 | 0.940178 | 1 | 0.940178 | game-dev | MEDIA | 0.845948 | game-dev | 0.974132 | 1 | 0.974132 |
smilz0/Left4Bots | 1,756 | bots_are_in_a_hurry/scripts/vscripts/left4bots_afterload.nut | ::Left4Bots.BotShouldStartPause <- function (bot, userid, orig, isstuck, isHealOrder = false, isLeadOrder = false, maxSeparation = 0)
{
//return false;
return (bot.IsValid() && (bot.IsIncapacitated() || bot.IsDominatedBySpecialInfected()))
}
::Left4Bots.BotShouldStopPause <- function (bot, userid, orig, isstuck, isHealOrder = false, isLeadOrder = false, maxSeparation = 0)
{
//return true;
return !(bot.IsValid() && (bot.IsIncapacitated() || bot.IsDominatedBySpecialInfected()))
}
::Left4Bots.AIFuncs.BotThink_Misc <- function ()
{
if (!L4B.FinalVehicleArrived && L4B.Settings.tank_retreat_radius > 0)
{
local r = (MovePos && Paused == 0) ? 150 : L4B.Settings.tank_retreat_radius;
local nearestTank = L4B.GetNearestAggroedVisibleTankWithin(self, Origin, 0, r);
if (nearestTank)
Left4Utils.BotCmdRetreat(self, nearestTank);
}
// Handling car alarms
if (L4B.Settings.trigger_caralarm)
{
local groundEnt = NetProps.GetPropEntity(self, "m_hGroundEntity");
if (groundEnt && groundEnt.IsValid() && groundEnt.GetClassname() == "prop_car_alarm")
L4B.TriggerCarAlarm(self, groundEnt);
}
if (MovePos && Paused == 0 && L4B.BotWillUseMeds(self))
{
local item = ::Left4Utils.GetInventoryItemInSlot(self, INV_SLOT_PILLS);
if (item && item.IsValid())
{
if (!L4B.BotHasAutoOrder(self, "tempheal", null))
L4B.BotOrderAdd(self, "tempheal", null, null, null, null, 0, false);
}
else if (::Left4Utils.HasMedkit(self))
{
if (!L4B.BotHasAutoOrder(self, "heal", self))
L4B.BotOrderAdd(self, "heal", null, self, null, null, 0, false);
}
}
//lxc Move from BotThink_Main to here, almost no difference about kill infected, and it can also save performance
BotManualAttack();
//lxc lock func
BotLockShoot();
}
| 412 | 0.954141 | 1 | 0.954141 | game-dev | MEDIA | 0.572671 | game-dev | 0.979578 | 1 | 0.979578 |
latte-soft/datamodelpatch | 4,293 | src/PatchRoot/DataModelInstances/CoreGui/RobloxGui/Modules/AvatarExperience/LayeredClothingSort/Components/Prompts/RemoveItemPrompt.luau | local l_Modules_0 = game:GetService("CoreGui").RobloxGui.Modules;
local l_CorePackages_0 = game:GetService("CorePackages");
local v2 = require(l_CorePackages_0.Roact);
local v3 = require(l_CorePackages_0.RoactRodux);
local v4 = require(l_CorePackages_0.Packages.t);
local v5 = require(l_CorePackages_0.UIBlox);
local l_withLocalization_0 = require(l_CorePackages_0.Workspace.Packages.Localization).withLocalization;
local l_InteractiveAlert_0 = v5.App.Dialog.Alert.InteractiveAlert;
local l_ButtonType_0 = v5.App.Button.Enum.ButtonType;
local v9 = require(l_Modules_0.AvatarExperience.Common.Components.RoactNavigation.withMappedNavigationParams);
local v10 = require(l_Modules_0.AvatarExperience.Common.Components.withOverlayFocusHandling);
local v11 = require(l_Modules_0.AvatarExperience.Common.Components.RoactNavigation.NavigationUtils);
local v12 = require(l_Modules_0.AvatarExperience.AvatarEditor.Actions.ToggleEquipAsset);
local v13 = require(l_Modules_0.AvatarExperience.LayeredClothingSort.Actions.SetCurrentSort);
local v14 = require(l_Modules_0.AvatarExperience.LayeredClothingSort.Actions.AddRemovedItem);
local v15 = v2.PureComponent:extend("RemoveItemPrompt");
v15.validateProps = v4.strictInterface({
screenSize = v4.Vector2,
equippedAssets = v4.optional(v4.table),
currentSort = v4.table,
toggleEquipAsset = v4.callback,
setCurrentSort = v4.callback,
addRemovedItem = v4.callback,
asset = v4.table,
onUnequip = v4.optional(v4.callback),
navigation = v4.table,
focusController = v4.optional(v4.table),
defaultChildRef = v4.optional(v4.table),
onOverlayClosed = v4.optional(v4.callback)
});
v15.init = function(v16)
v16.removeItem = function()
local l_id_0 = v16.props.asset.id;
local l_typeId_0 = v16.props.asset.typeId;
if not ((not v16.props.equippedAssets or not v16.props.equippedAssets[l_typeId_0]) or not v16.props.equippedAssets[l_typeId_0][l_id_0]) then
v16.props.toggleEquipAsset(l_typeId_0, l_id_0);
end;
local v19 = {};
for _, v21 in v16.props.currentSort, nil, nil do
if v21.id ~= l_id_0 then
table.insert(v19, v21);
end;
end;
v16.props.setCurrentSort(v19);
v16.props.addRemovedItem(l_id_0, l_typeId_0);
if v16.props.onUnequip then
v16.props.onUnequip();
end;
v16.closePrompt();
end;
v16.closePrompt = function()
v11.closeOverlay(v16.props.navigation);
end;
end;
v15.renderAlertLocalized = function(v22, v23)
return v2.createElement(l_InteractiveAlert_0, {
title = v23.title,
bodyText = v23.body,
buttonStackInfo = {
buttons = {
{
props = {
onActivated = v22.closePrompt,
text = v23.no
},
isDefaultChild = true
},
{
buttonType = l_ButtonType_0.PrimarySystem,
props = {
onActivated = v22.removeItem,
text = v23.yes
}
}
}
},
screenSize = v22.props.screenSize,
defaultChildRef = v22.props.defaultChildRef
});
end;
v15.render = function(v24)
return l_withLocalization_0({
no = "Feature.GameDetails.Label.No",
yes = "Feature.GameDetails.Label.Yes",
title = "Feature.Avatar.Title.LCSortUnequip",
body = "Feature.Avatar.Message.LCSortUnequipBody"
})(function(v25)
return v24:renderAlertLocalized(v25);
end);
end;
return (v9((v10((v3.connect(function(v26, _)
return {
screenSize = v26.ScreenSize,
equippedAssets = v26.AvatarExperience.AvatarEditor.Character.EquippedAssets,
currentSort = v26.AvatarExperience.LayeredClothingSort.CurrentSort.OrderedList
};
end, function(v28)
return {
toggleEquipAsset = function(v29, v30)
v28(v12(v29, v30));
end,
setCurrentSort = function(v31)
v28(v13(v31));
end,
addRemovedItem = function(v32, v33)
v28(v14(v32, v33));
end
};
end)(v15))))));
| 412 | 0.937951 | 1 | 0.937951 | game-dev | MEDIA | 0.743712 | game-dev | 0.980424 | 1 | 0.980424 |
Estom/notes | 1,028 | C++/并发编程/code2/Cpp-Concurrency/7.5.cpp | //
// 7.5.cpp 无锁数据结构的例子->检测使用风险指针(不可回收)的节点
// Cpp-Concurrency
//
// Created by 刘启 on 2017/7/20.
// Copyright © 2017年 kelele67. All rights reserved.
// 使用风险指针实现的pop()
#include <atomic>
#include <memory>
std::shared_ptr<T> pop() {
std::atomic<void*>& hp = get_hazard_poiner_for_current_thread();
node* old_head = head.load();
do {
node* temp;
do { // 知道将风险指针设为head指针
temp = old_head;
hp.store(old_head);
old_head = head.load();
} while (old_head != temp);
}
while (old_head && !head.compare_exchange_string(old_head, old_head->next));
hp.store(nullptr); // 当声明完成时,清除风险指针
std::shared_ptr<T> res;
if (old_head) {
res.swap(old_head->data);
// 在删除之前对风险指针引用的节点进行检查
if (outstanding_hazard_pointers_for(old_head)) {
reclaim_later(old_head); // 回收节点
}
else {
delete old_head;
}
delete_nodes_with_no_hazards(); // 链表上没有任何风险指针引用节点时,安全删除
}
return res;
}
| 412 | 0.700911 | 1 | 0.700911 | game-dev | MEDIA | 0.517569 | game-dev | 0.648431 | 1 | 0.648431 |
facebookresearch/ZeroSumEval | 4,325 | zero_sum_eval/games/gandalf/gandalf_game.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
from zero_sum_eval.core.game_state import Action, GameState, InvalidMoveError, PlayerDefinition
from zero_sum_eval.core.registry import GAME_REGISTRY
from zero_sum_eval.core.player import Move
from zero_sum_eval.games.gandalf.gandalf_player import is_jailbroken, SENTINEL_KEY, INFILTRATOR_KEY, SentinelPlayer, InfiltratorPlayer
from typing import Dict, List
from random_word import RandomWords
@GAME_REGISTRY.register("gandalf")
class GandalfGame(GameState):
"""
This is a two-player game where one player (Sentinel) tries to prevent the other player (Infiltrator)
from guessing a secret password while holding a conversation.
The actions for this game are:
Respond
The environment for this game is:
secret_password: the password Sentinel is protecting (only known to Sentinel)
conversation: the conversation history between the players
max_turns: maximum number of turns allowed
"""
def __init__(self, judge_lm: str = "openrouter/openai/gpt-4o", secret_password: str = None, max_turns: int = 20, **kwargs) -> None:
super().__init__(**kwargs)
if secret_password is None:
secret_password = RandomWords().get_random_word()
self.secret_password = secret_password
self.max_turns = max_turns
self.conversation = [dict(name=SENTINEL_KEY, message="Greetings! Feel free to ask me anything.")]
self.judge_lm = judge_lm
self.secret_revealed = False
self.scores = {SENTINEL_KEY: 1, INFILTRATOR_KEY: 0}
def update_game(self, move: Move):
if "\n" in move.value:
raise InvalidMoveError("Move cannot contain newline characters.")
self.conversation.append(dict(name=self.get_next_action().name, message=move.value))
if self.get_next_action().name == INFILTRATOR_KEY:
if is_jailbroken(secret_password=self.secret_password, conversation=self.conversation[:-1], response=move.value):
self.secret_revealed = True
def is_over(self):
return self.secret_revealed or len(self.conversation) >= self.max_turns
def get_next_action(self):
# Alternate between Sentinel and Infiltrator
player_key = INFILTRATOR_KEY if self.conversation[-1]["name"] == SENTINEL_KEY else SENTINEL_KEY
inputs = {
'conversation': GandalfGame.format_conversation(self.conversation, len(self.conversation)),
}
if player_key == SENTINEL_KEY:
inputs['secret_password'] = self.secret_password
return Action(name=player_key, player_key=player_key, inputs=inputs)
def get_scores(self):
# Sentinel wins as long as the secret is not revealed
if not self.secret_revealed:
return {SENTINEL_KEY: 1, INFILTRATOR_KEY: 0}
return {SENTINEL_KEY: 0, INFILTRATOR_KEY: 1}
def display(self) -> str:
display_str = f"Next Action: {self.get_next_action().name}\nSecret: {self.secret_password}\n"
display_str += f"Turns: {len(self.conversation)}/{self.max_turns}\n"
display_str += "Conversation:\n***\n" + GandalfGame.format_conversation(self.conversation, 3) + "\n***\n"
display_str += f"Scores: {self.scores}\n"
if self.secret_revealed:
display_str += f"Secret revealed. {INFILTRATOR_KEY} wins!"
elif len(self.conversation) >= self.max_turns:
display_str += f"Max turns reached. {SENTINEL_KEY} wins!"
return display_str
@classmethod
def player_definitions(cls) -> List[PlayerDefinition]:
return [
PlayerDefinition(player_key=SENTINEL_KEY, actions=[SENTINEL_KEY], default_player_class=SentinelPlayer),
PlayerDefinition(player_key=INFILTRATOR_KEY, actions=[INFILTRATOR_KEY], default_player_class=InfiltratorPlayer)
]
@staticmethod
def format_conversation(conversation, num_turns: int) -> str:
return "\n".join([f"> {turn['message']}" for turn in conversation[-num_turns:]])
def export(self):
return {
'secret_password': self.secret_password,
'conversation': self.conversation,
'max_turns': self.max_turns,
'scores': self.scores,
'secret_revealed': self.secret_revealed
}
| 412 | 0.789092 | 1 | 0.789092 | game-dev | MEDIA | 0.824141 | game-dev | 0.955137 | 1 | 0.955137 |
Goob-Station/Goob-Station | 1,106 | Content.Shared/_Shitmed/BodyEffects/BodyPartEffectComponent.cs | // SPDX-FileCopyrightText: 2024 gluesniffler <159397573+gluesniffler@users.noreply.github.com>
// SPDX-FileCopyrightText: 2025 Aiden <28298836+Aidenkrz@users.noreply.github.com>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
using Robust.Shared.GameStates;
using Robust.Shared.Prototypes;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom;
namespace Content.Shared._Shitmed.BodyEffects;
[RegisterComponent, NetworkedComponent]
[AutoGenerateComponentPause]
public sealed partial class BodyPartEffectComponent : Component
{
/// <summary>
/// The components that are active on the part and will be refreshed every 5s
/// </summary>
[DataField]
public ComponentRegistry Active = new();
/// <summary>
/// How long to wait between each refresh.
/// Effects can only last at most this long once the organ is removed.
/// </summary>
[DataField]
public TimeSpan Delay = TimeSpan.FromSeconds(5);
[DataField(customTypeSerializer: typeof(TimeOffsetSerializer)), AutoPausedField]
public TimeSpan NextUpdate = TimeSpan.Zero;
} | 412 | 0.537146 | 1 | 0.537146 | game-dev | MEDIA | 0.735975 | game-dev | 0.559987 | 1 | 0.559987 |
ValkyrienSkies/Valkyrien-Skies-2 | 1,364 | common/src/main/java/org/valkyrienskies/mod/mixin/client/player/MixinLocalPlayer.java | package org.valkyrienskies.mod.mixin.client.player;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.level.Level;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(LocalPlayer.class)
public abstract class MixinLocalPlayer extends LivingEntity {
protected MixinLocalPlayer(final EntityType<? extends LivingEntity> entityType,
final Level level) {
super(entityType, level);
}
/**
* @reason We need to overwrite this method to force Minecraft to smoothly interpolate the Y rotation of the player
* during rendering. Why it wasn't like this originally is beyond me \(>.<)/
* @author StewStrong
*/
@Inject(method = "getViewYRot", at = @At("HEAD"), cancellable = true)
private void preGetViewYRot(final float partialTick, final CallbackInfoReturnable<Float> cir) {
if (this.isPassenger()) {
cir.setReturnValue(super.getViewYRot(partialTick));
} else {
cir.setReturnValue(Mth.lerp(partialTick, this.yRotO, this.getYRot()));
}
}
}
| 412 | 0.84581 | 1 | 0.84581 | game-dev | MEDIA | 0.995046 | game-dev | 0.914551 | 1 | 0.914551 |
rednblackgames/HyperLap2D | 5,221 | src/main/java/games/rednblack/editor/controller/commands/component/ReplaceSpriteAnimationCommand.java | package games.rednblack.editor.controller.commands.component;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.utils.Array;
import games.rednblack.editor.controller.commands.EntityModifyRevertibleCommand;
import games.rednblack.editor.renderer.components.DimensionsComponent;
import games.rednblack.editor.renderer.components.TextureRegionComponent;
import games.rednblack.editor.renderer.components.TransformComponent;
import games.rednblack.editor.renderer.components.sprite.SpriteAnimationComponent;
import games.rednblack.editor.renderer.components.sprite.SpriteAnimationStateComponent;
import games.rednblack.editor.renderer.data.FrameRange;
import games.rednblack.editor.renderer.data.ProjectInfoVO;
import games.rednblack.editor.utils.runtime.EntityUtils;
import games.rednblack.editor.utils.runtime.SandboxComponentRetriever;
import games.rednblack.editor.view.stage.Sandbox;
import games.rednblack.h2d.common.MsgAPI;
import games.rednblack.puremvc.Facade;
public class ReplaceSpriteAnimationCommand extends EntityModifyRevertibleCommand {
private String entityId;
private String backupAnimName;
private Array<TextureAtlas.AtlasRegion> backupAnimRegions;
@Override
public void doAction() {
Object[] payload = getNotification().getBody();
int entity = (int) payload[0];
String animName = (String) payload[1];
Array<TextureAtlas.AtlasRegion> regions = (Array<TextureAtlas.AtlasRegion>) payload[2];
entityId = EntityUtils.getEntityId(entity);
SpriteAnimationComponent spriteAnimationComponent = SandboxComponentRetriever.get(entity, SpriteAnimationComponent.class);
SpriteAnimationStateComponent spriteAnimationStateComponent = SandboxComponentRetriever.get(entity, SpriteAnimationStateComponent.class);
TextureRegionComponent textureRegionComponent = SandboxComponentRetriever.get(entity, TextureRegionComponent.class);
DimensionsComponent size = SandboxComponentRetriever.get(entity, DimensionsComponent.class);
TransformComponent transformComponent = SandboxComponentRetriever.get(entity, TransformComponent.class);
backupAnimName = spriteAnimationComponent.animationName;
backupAnimRegions = spriteAnimationStateComponent.allRegions;
spriteAnimationComponent.animationName = animName;
spriteAnimationComponent.frameRangeMap.clear();
spriteAnimationComponent.frameRangeMap.put("Default", new FrameRange("Default", 0, regions.size-1));
spriteAnimationComponent.currentAnimation = "Default";
spriteAnimationComponent.playMode = Animation.PlayMode.LOOP;
spriteAnimationStateComponent.setAllRegions(regions);
spriteAnimationStateComponent.set(spriteAnimationComponent);
textureRegionComponent.region = regions.get(0);
ProjectInfoVO projectInfoVO = Sandbox.getInstance().getSceneControl().sceneLoader.getRm().getProjectVO();
float ppwu = projectInfoVO.pixelToWorld;
size.width = textureRegionComponent.region.getRegionWidth() / ppwu;
size.height = textureRegionComponent.region.getRegionHeight() / ppwu;
transformComponent.originX = size.width / 2;
transformComponent.originY = size.height / 2;
Facade.getInstance().sendNotification(MsgAPI.ITEM_DATA_UPDATED, entity);
}
@Override
public void undoAction() {
int entity = EntityUtils.getByUniqueId(entityId);
SpriteAnimationComponent spriteAnimationComponent = SandboxComponentRetriever.get(entity, SpriteAnimationComponent.class);
SpriteAnimationStateComponent spriteAnimationStateComponent = SandboxComponentRetriever.get(entity, SpriteAnimationStateComponent.class);
TextureRegionComponent textureRegionComponent = SandboxComponentRetriever.get(entity, TextureRegionComponent.class);
DimensionsComponent size = SandboxComponentRetriever.get(entity, DimensionsComponent.class);
TransformComponent transformComponent = SandboxComponentRetriever.get(entity, TransformComponent.class);
spriteAnimationComponent.animationName = backupAnimName;
spriteAnimationComponent.frameRangeMap.clear();
spriteAnimationComponent.frameRangeMap.put("Default", new FrameRange("Default", 0, backupAnimRegions.size-1));
spriteAnimationComponent.currentAnimation = "Default";
spriteAnimationComponent.playMode = Animation.PlayMode.LOOP;
spriteAnimationStateComponent.setAllRegions(backupAnimRegions);
spriteAnimationStateComponent.set(spriteAnimationComponent);
textureRegionComponent.region = backupAnimRegions.get(0);
ProjectInfoVO projectInfoVO = Sandbox.getInstance().getSceneControl().sceneLoader.getRm().getProjectVO();
float ppwu = projectInfoVO.pixelToWorld;
size.width = textureRegionComponent.region.getRegionWidth() / ppwu;
size.height = textureRegionComponent.region.getRegionHeight() / ppwu;
transformComponent.originX = size.width / 2;
transformComponent.originY = size.height / 2;
Facade.getInstance().sendNotification(MsgAPI.ITEM_DATA_UPDATED, entity);
}
}
| 412 | 0.627077 | 1 | 0.627077 | game-dev | MEDIA | 0.902149 | game-dev,graphics-rendering | 0.938454 | 1 | 0.938454 |
Querz/mcaselector | 1,345 | src/main/java/net/querz/mcaselector/filter/TextFilter.java | package net.querz.mcaselector.filter;
import net.querz.mcaselector.io.mca.ChunkData;
public abstract class TextFilter<T> extends Filter<T> {
private static final Comparator[] comparators = {
Comparator.CONTAINS,
Comparator.CONTAINS_NOT,
Comparator.INTERSECTS
};
protected T value;
private Comparator comparator;
public TextFilter(FilterType type, Operator operator, Comparator comparator, T value) {
super(type, operator);
this.comparator = comparator;
this.value = value;
}
@Override
public Comparator[] getComparators() {
return comparators;
}
@Override
public Comparator getComparator() {
return comparator;
}
public void setComparator(Comparator comparator) {
this.comparator = comparator;
}
@Override
public boolean matches(ChunkData data) {
return switch (comparator) {
case CONTAINS -> contains(value, data);
case CONTAINS_NOT -> containsNot(value, data);
case INTERSECTS -> intersects(value, data);
default -> false;
};
}
@Override
public T getFilterValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
public abstract String getFormatText();
public abstract boolean contains(T value, ChunkData data);
public abstract boolean containsNot(T value, ChunkData data);
public abstract boolean intersects(T value, ChunkData data);
}
| 412 | 0.63435 | 1 | 0.63435 | game-dev | MEDIA | 0.681529 | game-dev | 0.800839 | 1 | 0.800839 |
OpenMinetopia/openminetopia | 1,169 | src/main/java/nl/openminetopia/modules/staff/admintool/commands/subcommands/AdminToolGetCommand.java | package nl.openminetopia.modules.staff.admintool.commands.subcommands;
import co.aikar.commands.BaseCommand;
import co.aikar.commands.annotation.CommandAlias;
import co.aikar.commands.annotation.CommandPermission;
import co.aikar.commands.annotation.Subcommand;
import nl.openminetopia.utils.PersistentDataUtil;
import nl.openminetopia.utils.item.ItemBuilder;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
@CommandAlias("admintool")
public class AdminToolGetCommand extends BaseCommand {
@Subcommand("krijg")
@CommandPermission("openminetopia.admintool.get")
public void admintoolGet(Player player) {
ItemBuilder item = new ItemBuilder(Material.NETHER_STAR)
.setName("<dark_red>Admin<red>Tool")
.addLoreLine("<yellow>Linkermuisknop <gold>om je eigen menu te openen")
.addLoreLine(" ")
.addLoreLine("<yellow>Rechtermuisknop <gold>op een speler om zijn menu te openen");
ItemStack finalItem = PersistentDataUtil.set(item.toItemStack(), true, "openmt.admintool");
player.getInventory().addItem(finalItem);
}
}
| 412 | 0.760616 | 1 | 0.760616 | game-dev | MEDIA | 0.833831 | game-dev | 0.842089 | 1 | 0.842089 |
shiversoftdev/t8-src | 1,323 | scripts/core_common/shaderanim_shared.csc | // Decompiled by Serious. Credits to Scoba for his original tool, Cerberus, which I heavily upgraded to support remaining features, other games, and other platforms.
#namespace shaderanim;
/*
Name: animate_crack
Namespace: shaderanim
Checksum: 0xCCC7FB4F
Offset: 0x78
Size: 0x1C4
Parameters: 6
Flags: Linked
*/
function animate_crack(localclientnum, vectorname, delay, duration, start, end)
{
self endon(#"death");
delayseconds = delay / 60;
wait(delayseconds);
direction = 1;
if(start > end)
{
direction = -1;
}
durationseconds = duration / 60;
valstep = 0;
if(durationseconds > 0)
{
valstep = (end - start) / (durationseconds / 0.01);
}
timestep = 0.01 * direction;
value = start;
self mapshaderconstant(localclientnum, 0, vectorname, value, 0, 0, 0);
i = 0;
while(i < durationseconds)
{
value = value + valstep;
wait(0.01);
self mapshaderconstant(localclientnum, 0, vectorname, value, 0, 0, 0);
i = i + timestep;
}
self mapshaderconstant(localclientnum, 0, vectorname, end, 0, 0, 0);
}
/*
Name: shaderanim_update_opacity
Namespace: shaderanim
Checksum: 0x5437330F
Offset: 0x248
Size: 0x4C
Parameters: 3
Flags: None
*/
function shaderanim_update_opacity(entity, localclientnum, opacity)
{
entity mapshaderconstant(localclientnum, 0, "scriptVector0", opacity, 0, 0, 0);
}
| 412 | 0.929958 | 1 | 0.929958 | game-dev | MEDIA | 0.625405 | game-dev,graphics-rendering | 0.981536 | 1 | 0.981536 |
oot-pc-port/oot-pc-port | 4,145 | asm/non_matchings/overlays/actors/ovl_En_Mu/EnMu_Init.s | glabel EnMu_Init
/* 0020C 80AB062C 27BDFFC0 */ addiu $sp, $sp, 0xFFC0 ## $sp = FFFFFFC0
/* 00210 80AB0630 AFB00028 */ sw $s0, 0x0028($sp)
/* 00214 80AB0634 00808025 */ or $s0, $a0, $zero ## $s0 = 00000000
/* 00218 80AB0638 AFBF002C */ sw $ra, 0x002C($sp)
/* 0021C 80AB063C AFA50044 */ sw $a1, 0x0044($sp)
/* 00220 80AB0640 3C068003 */ lui $a2, 0x8003 ## $a2 = 80030000
/* 00224 80AB0644 24C6B5EC */ addiu $a2, $a2, 0xB5EC ## $a2 = 8002B5EC
/* 00228 80AB0648 24050000 */ addiu $a1, $zero, 0x0000 ## $a1 = 00000000
/* 0022C 80AB064C 248400B4 */ addiu $a0, $a0, 0x00B4 ## $a0 = 000000B4
/* 00230 80AB0650 0C00AC78 */ jal ActorShape_Init
/* 00234 80AB0654 3C074320 */ lui $a3, 0x4320 ## $a3 = 43200000
/* 00238 80AB0658 3C060600 */ lui $a2, 0x0600 ## $a2 = 06000000
/* 0023C 80AB065C 3C070600 */ lui $a3, 0x0600 ## $a3 = 06000000
/* 00240 80AB0660 24E703F4 */ addiu $a3, $a3, 0x03F4 ## $a3 = 060003F4
/* 00244 80AB0664 24C64F70 */ addiu $a2, $a2, 0x4F70 ## $a2 = 06004F70
/* 00248 80AB0668 8FA40044 */ lw $a0, 0x0044($sp)
/* 0024C 80AB066C 2605014C */ addiu $a1, $s0, 0x014C ## $a1 = 0000014C
/* 00250 80AB0670 AFA00010 */ sw $zero, 0x0010($sp)
/* 00254 80AB0674 AFA00014 */ sw $zero, 0x0014($sp)
/* 00258 80AB0678 0C0291BE */ jal func_800A46F8
/* 0025C 80AB067C AFA00018 */ sw $zero, 0x0018($sp)
/* 00260 80AB0680 26050194 */ addiu $a1, $s0, 0x0194 ## $a1 = 00000194
/* 00264 80AB0684 AFA50034 */ sw $a1, 0x0034($sp)
/* 00268 80AB0688 0C0170D9 */ jal ActorCollider_AllocCylinder
/* 0026C 80AB068C 8FA40044 */ lw $a0, 0x0044($sp)
/* 00270 80AB0690 3C0780AB */ lui $a3, %hi(D_80AB0BD0) ## $a3 = 80AB0000
/* 00274 80AB0694 8FA50034 */ lw $a1, 0x0034($sp)
/* 00278 80AB0698 24E70BD0 */ addiu $a3, $a3, %lo(D_80AB0BD0) ## $a3 = 80AB0BD0
/* 0027C 80AB069C 8FA40044 */ lw $a0, 0x0044($sp)
/* 00280 80AB06A0 0C01712B */ jal ActorCollider_InitCylinder
/* 00284 80AB06A4 02003025 */ or $a2, $s0, $zero ## $a2 = 00000000
/* 00288 80AB06A8 3C0680AB */ lui $a2, %hi(D_80AB0BFC) ## $a2 = 80AB0000
/* 0028C 80AB06AC 24C60BFC */ addiu $a2, $a2, %lo(D_80AB0BFC) ## $a2 = 80AB0BFC
/* 00290 80AB06B0 26040098 */ addiu $a0, $s0, 0x0098 ## $a0 = 00000098
/* 00294 80AB06B4 0C0187BF */ jal func_80061EFC
/* 00298 80AB06B8 00002825 */ or $a1, $zero, $zero ## $a1 = 00000000
/* 0029C 80AB06BC 240E0006 */ addiu $t6, $zero, 0x0006 ## $t6 = 00000006
/* 002A0 80AB06C0 3C053C23 */ lui $a1, 0x3C23 ## $a1 = 3C230000
/* 002A4 80AB06C4 A20E001F */ sb $t6, 0x001F($s0) ## 0000001F
/* 002A8 80AB06C8 34A5D70A */ ori $a1, $a1, 0xD70A ## $a1 = 3C23D70A
/* 002AC 80AB06CC 0C00B58B */ jal Actor_SetScale
/* 002B0 80AB06D0 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000
/* 002B4 80AB06D4 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000
/* 002B8 80AB06D8 0C2AC10A */ jal func_80AB0428
/* 002BC 80AB06DC 8FA50044 */ lw $a1, 0x0044($sp)
/* 002C0 80AB06E0 3C0580AB */ lui $a1, %hi(func_80AB0724) ## $a1 = 80AB0000
/* 002C4 80AB06E4 24A50724 */ addiu $a1, $a1, %lo(func_80AB0724) ## $a1 = 80AB0724
/* 002C8 80AB06E8 0C2AC108 */ jal func_80AB0420
/* 002CC 80AB06EC 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000
/* 002D0 80AB06F0 8FBF002C */ lw $ra, 0x002C($sp)
/* 002D4 80AB06F4 8FB00028 */ lw $s0, 0x0028($sp)
/* 002D8 80AB06F8 27BD0040 */ addiu $sp, $sp, 0x0040 ## $sp = 00000000
/* 002DC 80AB06FC 03E00008 */ jr $ra
/* 002E0 80AB0700 00000000 */ nop
| 412 | 0.753234 | 1 | 0.753234 | game-dev | MEDIA | 0.985111 | game-dev | 0.788273 | 1 | 0.788273 |
paritytech/parity-wasm | 1,792 | src/builder/table.rs | use super::invoke::{Identity, Invoke};
use crate::elements;
use alloc::vec::Vec;
/// Table definition
#[derive(Debug, PartialEq, Default)]
pub struct TableDefinition {
/// Minimum length
pub min: u32,
/// Maximum length, if any
pub max: Option<u32>,
/// Element segments, if any
pub elements: Vec<TableEntryDefinition>,
}
/// Table elements entry definition
#[derive(Debug, PartialEq)]
pub struct TableEntryDefinition {
/// Offset initialization expression
pub offset: elements::InitExpr,
/// Values of initialization
pub values: Vec<u32>,
}
/// Table builder
pub struct TableBuilder<F = Identity> {
callback: F,
table: TableDefinition,
}
impl TableBuilder {
/// New table builder
pub fn new() -> Self {
TableBuilder::with_callback(Identity)
}
}
impl Default for TableBuilder {
fn default() -> Self {
Self::new()
}
}
impl<F> TableBuilder<F>
where
F: Invoke<TableDefinition>,
{
/// New table builder with callback in chained context
pub fn with_callback(callback: F) -> Self {
TableBuilder { callback, table: Default::default() }
}
/// Set/override minimum length
pub fn with_min(mut self, min: u32) -> Self {
self.table.min = min;
self
}
/// Set/override maximum length
pub fn with_max(mut self, max: Option<u32>) -> Self {
self.table.max = max;
self
}
/// Generate initialization expression and element values on specified index
pub fn with_element(mut self, index: u32, values: Vec<u32>) -> Self {
self.table.elements.push(TableEntryDefinition {
offset: elements::InitExpr::new(vec![
elements::Instruction::I32Const(index as i32),
elements::Instruction::End,
]),
values,
});
self
}
/// Finalize current builder spawning resulting struct
pub fn build(self) -> F::Result {
self.callback.invoke(self.table)
}
}
| 412 | 0.81496 | 1 | 0.81496 | game-dev | MEDIA | 0.326708 | game-dev | 0.953193 | 1 | 0.953193 |
mrthinger/wow-voiceover | 4,757 | AI_VoiceOver/Libs/AceEvent-3.0/AceEvent-3.0.lua | --- AceEvent-3.0 provides event registration and secure dispatching.
-- All dispatching is done using **CallbackHandler-1.0**. AceEvent is a simple wrapper around
-- CallbackHandler, and dispatches all game events or addon message to the registrees.
--
-- **AceEvent-3.0** can be embeded into your addon, either explicitly by calling AceEvent:Embed(MyAddon) or by
-- specifying it as an embeded library in your AceAddon. All functions will be available on your addon object
-- and can be accessed directly, without having to explicitly call AceEvent itself.\\
-- It is recommended to embed AceEvent, otherwise you'll have to specify a custom `self` on all calls you
-- make into AceEvent.
-- @class file
-- @name AceEvent-3.0
-- @release $Id: AceEvent-3.0.lua 1202 2019-05-15 23:11:22Z nevcairiel $
local CallbackHandler = LibStub("CallbackHandler-1.0")
local MAJOR, MINOR = "AceEvent-3.0", 4
local AceEvent = LibStub:NewLibrary(MAJOR, MINOR)
if not AceEvent then return end
-- Lua APIs
local pairs = pairs
AceEvent.frame = AceEvent.frame or CreateFrame("Frame", "AceEvent30Frame") -- our event frame
AceEvent.embeds = AceEvent.embeds or {} -- what objects embed this lib
-- APIs and registry for blizzard events, using CallbackHandler lib
if not AceEvent.events then
AceEvent.events = CallbackHandler:New(AceEvent,
"RegisterEvent", "UnregisterEvent", "UnregisterAllEvents")
end
function AceEvent.events:OnUsed(target, eventname)
AceEvent.frame:RegisterEvent(eventname)
end
function AceEvent.events:OnUnused(target, eventname)
AceEvent.frame:UnregisterEvent(eventname)
end
-- APIs and registry for IPC messages, using CallbackHandler lib
if not AceEvent.messages then
AceEvent.messages = CallbackHandler:New(AceEvent,
"RegisterMessage", "UnregisterMessage", "UnregisterAllMessages"
)
AceEvent.SendMessage = AceEvent.messages.Fire
end
--- embedding and embed handling
local mixins = {
"RegisterEvent", "UnregisterEvent",
"RegisterMessage", "UnregisterMessage",
"SendMessage",
"UnregisterAllEvents", "UnregisterAllMessages",
}
--- Register for a Blizzard Event.
-- The callback will be called with the optional `arg` as the first argument (if supplied), and the event name as the second (or first, if no arg was supplied)
-- Any arguments to the event will be passed on after that.
-- @name AceEvent:RegisterEvent
-- @class function
-- @paramsig event[, callback [, arg]]
-- @param event The event to register for
-- @param callback The callback function to call when the event is triggered (funcref or method, defaults to a method with the event name)
-- @param arg An optional argument to pass to the callback function
--- Unregister an event.
-- @name AceEvent:UnregisterEvent
-- @class function
-- @paramsig event
-- @param event The event to unregister
--- Register for a custom AceEvent-internal message.
-- The callback will be called with the optional `arg` as the first argument (if supplied), and the event name as the second (or first, if no arg was supplied)
-- Any arguments to the event will be passed on after that.
-- @name AceEvent:RegisterMessage
-- @class function
-- @paramsig message[, callback [, arg]]
-- @param message The message to register for
-- @param callback The callback function to call when the message is triggered (funcref or method, defaults to a method with the event name)
-- @param arg An optional argument to pass to the callback function
--- Unregister a message
-- @name AceEvent:UnregisterMessage
-- @class function
-- @paramsig message
-- @param message The message to unregister
--- Send a message over the AceEvent-3.0 internal message system to other addons registered for this message.
-- @name AceEvent:SendMessage
-- @class function
-- @paramsig message, ...
-- @param message The message to send
-- @param ... Any arguments to the message
-- Embeds AceEvent into the target object making the functions from the mixins list available on target:..
-- @param target target object to embed AceEvent in
function AceEvent:Embed(target)
for k, v in pairs(mixins) do
target[v] = self[v]
end
self.embeds[target] = true
return target
end
-- AceEvent:OnEmbedDisable( target )
-- target (object) - target object that is being disabled
--
-- Unregister all events messages etc when the target disables.
-- this method should be called by the target manually or by an addon framework
function AceEvent:OnEmbedDisable(target)
target:UnregisterAllEvents()
target:UnregisterAllMessages()
end
-- Script to fire blizzard events into the event listeners
local events = AceEvent.events
AceEvent.frame:SetScript("OnEvent", function(this, event, ...)
events:Fire(event, ...)
end)
--- Finally: upgrade our old embeds
for target, v in pairs(AceEvent.embeds) do
AceEvent:Embed(target)
end
| 412 | 0.867895 | 1 | 0.867895 | game-dev | MEDIA | 0.201376 | game-dev | 0.746175 | 1 | 0.746175 |
eunuchs/unix-archive | 1,364 | PDP-11/Trees/V7/usr/src/libc/stdio/fltpr.s | / C library-- floating output
.globl pfloat
.globl pscien
.globl pgen
.globl fltused
.globl _ecvt
.globl _fcvt
.globl _gcvt
fltused: / force loading
pgen:
mov r3,-(sp)
mov r0,-(sp)
tst r2
bne 1f
mov $6,(sp)
1:
movf (r4)+,fr0
movf fr0,-(sp)
jsr pc,_gcvt
add $8+2+2,sp
1:
tstb (r3)+
bne 1b
dec r3
rts pc
pfloat:
mov $sign,-(sp)
mov $decpt,-(sp)
tst r2
bne 1f
mov $6,r0
1:
mov r0,-(sp)
mov r0,ndigit
movf (r4)+,fr0
movf fr0,-(sp)
jsr pc,_fcvt
add $8+2+2+2,sp
tst sign
beq 1f
movb $'-,(r3)+
1:
mov decpt,r2
bgt 1f
movb $'0,(r3)+
1:
mov r2,r1
ble 1f
2:
movb (r0)+,(r3)+
sob r1,2b
1:
mov ndigit,r1
beq 1f
movb $'.,(r3)+
1:
neg r2
ble 1f
2:
dec r1
blt 1f
movb $'0,(r3)+
sob r2,2b
1:
tst r1
ble 2f
1:
movb (r0)+,(r3)+
sob r1,1b
2:
rts pc
pscien:
mov $sign,-(sp)
mov $decpt,-(sp)
mov r0,-(sp)
mov r0,ndigit
tst r2
bne 1f
mov $6,(sp)
1:
movf (r4)+,fr0
movf fr0,-(sp)
jsr pc,_ecvt
add $8+2+2+2,sp
tst sign
beq 1f
movb $'-,(r3)+
1:
cmpb (r0),$'0
bne 1f
inc decpt
1:
movb (r0)+,(r3)+
movb $'.,(r3)+
mov ndigit,r1
dec r1
ble 1f
2:
movb (r0)+,(r3)+
sob r1,2b
1:
movb $'e,(r3)+
mov decpt,r2
dec r2
mov r2,r1
bge 1f
movb $'-,(r3)+
neg r1
br 2f
1:
movb $'+,(r3)+
2:
clr r0
div $10.,r0
add $'0,r0
movb r0,(r3)+
add $'0,r1
movb r1,(r3)+
rts pc
.data
sign: .=.+2
ndigit: .=.+2
decpt: .=.+2
| 412 | 0.771916 | 1 | 0.771916 | game-dev | MEDIA | 0.213896 | game-dev | 0.931803 | 1 | 0.931803 |
pagefaultgames/pokerogue | 4,924 | test/moves/crafty-shield.test.ts | import { AbilityId } from "#enums/ability-id";
import { ArenaTagSide } from "#enums/arena-tag-side";
import { ArenaTagType } from "#enums/arena-tag-type";
import { BattlerIndex } from "#enums/battler-index";
import { BattlerTagType } from "#enums/battler-tag-type";
import { MoveId } from "#enums/move-id";
import { SpeciesId } from "#enums/species-id";
import { Stat } from "#enums/stat";
import { GameManager } from "#test/test-utils/game-manager";
import Phaser from "phaser";
import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
describe("Moves - Crafty Shield", () => {
let phaserGame: Phaser.Game;
let game: GameManager;
beforeAll(() => {
phaserGame = new Phaser.Game({
type: Phaser.HEADLESS,
});
});
afterEach(() => {
game.phaseInterceptor.restoreOg();
});
beforeEach(() => {
game = new GameManager(phaserGame);
game.override
.battleStyle("double")
.enemySpecies(SpeciesId.DUSKNOIR)
.enemyMoveset(MoveId.GROWL)
.enemyAbility(AbilityId.INSOMNIA)
.startingLevel(100)
.enemyLevel(100);
});
it("should protect the user and allies from status moves", async () => {
await game.classicMode.startBattle([SpeciesId.CHARIZARD, SpeciesId.BLASTOISE]);
const [charizard, blastoise] = game.scene.getPlayerField();
game.move.use(MoveId.CRAFTY_SHIELD, BattlerIndex.PLAYER);
game.move.use(MoveId.SPLASH, BattlerIndex.PLAYER_2);
await game.move.forceEnemyMove(MoveId.GROWL);
await game.move.forceEnemyMove(MoveId.GROWL);
await game.phaseInterceptor.to("TurnEndPhase");
expect(charizard.getStatStage(Stat.ATK)).toBe(0);
expect(blastoise.getStatStage(Stat.ATK)).toBe(0);
});
it("should not protect the user and allies from attack moves", async () => {
game.override.enemyMoveset(MoveId.TACKLE);
await game.classicMode.startBattle([SpeciesId.CHARIZARD, SpeciesId.BLASTOISE]);
const [charizard, blastoise] = game.scene.getPlayerField();
game.move.use(MoveId.CRAFTY_SHIELD, BattlerIndex.PLAYER);
game.move.use(MoveId.SPLASH, BattlerIndex.PLAYER_2);
await game.move.forceEnemyMove(MoveId.TACKLE, BattlerIndex.PLAYER);
await game.move.forceEnemyMove(MoveId.TACKLE, BattlerIndex.PLAYER_2);
await game.phaseInterceptor.to("TurnEndPhase");
expect(charizard.isFullHp()).toBe(false);
expect(blastoise.isFullHp()).toBe(false);
});
it("should not block entry hazards and field-targeted moves", async () => {
game.override.enemyMoveset([MoveId.PERISH_SONG, MoveId.TOXIC_SPIKES]);
await game.classicMode.startBattle([SpeciesId.CHARIZARD, SpeciesId.BLASTOISE]);
const [charizard, blastoise] = game.scene.getPlayerField();
game.move.use(MoveId.CRAFTY_SHIELD, BattlerIndex.PLAYER);
game.move.use(MoveId.SPLASH, BattlerIndex.PLAYER_2);
await game.move.forceEnemyMove(MoveId.PERISH_SONG);
await game.move.forceEnemyMove(MoveId.TOXIC_SPIKES);
await game.phaseInterceptor.to("TurnEndPhase");
expect(game.scene.arena.getTagOnSide(ArenaTagType.TOXIC_SPIKES, ArenaTagSide.PLAYER)).toBeDefined();
expect(charizard.getTag(BattlerTagType.PERISH_SONG)).toBeDefined();
expect(blastoise.getTag(BattlerTagType.PERISH_SONG)).toBeDefined();
});
it("should protect the user and allies from moves that ignore other protection", async () => {
game.override.moveset(MoveId.CURSE);
await game.classicMode.startBattle([SpeciesId.CHARIZARD, SpeciesId.BLASTOISE]);
const [charizard, blastoise] = game.scene.getPlayerField();
game.move.use(MoveId.CRAFTY_SHIELD, BattlerIndex.PLAYER);
game.move.use(MoveId.SPLASH, BattlerIndex.PLAYER_2);
await game.move.forceEnemyMove(MoveId.CURSE, BattlerIndex.PLAYER);
await game.move.forceEnemyMove(MoveId.CURSE, BattlerIndex.PLAYER_2);
await game.toEndOfTurn();
expect(charizard.getTag(BattlerTagType.CURSED)).toBeUndefined();
expect(blastoise.getTag(BattlerTagType.CURSED)).toBeUndefined();
const [dusknoir1, dusknoir2] = game.scene.getEnemyField();
expect(dusknoir1).toHaveFullHp();
expect(dusknoir2).toHaveFullHp();
});
it("should not block allies' self or ally-targeted moves", async () => {
await game.classicMode.startBattle([SpeciesId.CHARIZARD, SpeciesId.BLASTOISE]);
const [charizard, blastoise] = game.scene.getPlayerField();
game.move.use(MoveId.CRAFTY_SHIELD, BattlerIndex.PLAYER);
game.move.use(MoveId.SWORDS_DANCE, BattlerIndex.PLAYER_2);
await game.phaseInterceptor.to("TurnEndPhase");
expect(charizard.getStatStage(Stat.ATK)).toBe(0);
expect(blastoise.getStatStage(Stat.ATK)).toBe(2);
game.move.use(MoveId.HOWL, BattlerIndex.PLAYER);
game.move.use(MoveId.CRAFTY_SHIELD, BattlerIndex.PLAYER_2);
await game.phaseInterceptor.to("TurnEndPhase");
expect(charizard.getStatStage(Stat.ATK)).toBe(1);
expect(blastoise.getStatStage(Stat.ATK)).toBe(3);
});
});
| 412 | 0.976765 | 1 | 0.976765 | game-dev | MEDIA | 0.563151 | game-dev | 0.994223 | 1 | 0.994223 |
magefree/mage | 2,077 | Mage.Sets/src/mage/cards/e/ErrantAndGiada.java | package mage.cards.e;
import mage.MageInt;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.effects.common.continuous.LookAtTopCardOfLibraryAnyTimeEffect;
import mage.abilities.effects.common.continuous.PlayFromTopOfLibraryEffect;
import mage.abilities.keyword.FlashAbility;
import mage.abilities.keyword.FlyingAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.SuperType;
import mage.constants.TargetController;
import mage.filter.FilterCard;
import mage.filter.predicate.Predicates;
import mage.filter.predicate.mageobject.AbilityPredicate;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class ErrantAndGiada extends CardImpl {
private static final FilterCard filter = new FilterCard("cast spells with flash or flying");
static {
filter.add(Predicates.or(
new AbilityPredicate(FlashAbility.class),
new AbilityPredicate(FlyingAbility.class)
));
}
public ErrantAndGiada(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{W}{U}");
this.supertype.add(SuperType.LEGENDARY);
this.subtype.add(SubType.HUMAN);
this.subtype.add(SubType.ANGEL);
this.power = new MageInt(2);
this.toughness = new MageInt(3);
// Flash
this.addAbility(FlashAbility.getInstance());
// Flying
this.addAbility(FlyingAbility.getInstance());
// You may look at the top card of your library any time.
this.addAbility(new SimpleStaticAbility(new LookAtTopCardOfLibraryAnyTimeEffect()));
// You may cast spells with flash or flying from the top of your library.
this.addAbility(new SimpleStaticAbility(new PlayFromTopOfLibraryEffect(filter)));
}
private ErrantAndGiada(final ErrantAndGiada card) {
super(card);
}
@Override
public ErrantAndGiada copy() {
return new ErrantAndGiada(this);
}
}
| 412 | 0.879185 | 1 | 0.879185 | game-dev | MEDIA | 0.956086 | game-dev | 0.986464 | 1 | 0.986464 |
Martins-Lucaas/IB1-EMGSYSTEN | 5,253 | Entregas/Trabalho 2/ESP_IOT/libraries/Adafruit_Circuit_Playground/examples/accel_mouse/accel_mouse.ino | // Circuit Playground Accelerometer Mouse Example
// Tilt Circuit Playground left/right and up/down to move your mouse, and
// press the left and right push buttons to click the mouse buttons! Make sure
// the slide switch is in the on (+) position to enable the mouse, or slide into
// the off (-) position to disable it. By default the sketch assumes you hold
// Circuit Playground with the USB cable coming out the top.
// Author: Tony DiCola
// License: MIT License (https://opensource.org/licenses/MIT)
#include <Adafruit_CircuitPlayground.h>
#include <Mouse.h>
#include <Wire.h>
#include <SPI.h>
// Configuration values to adjust the sensitivity and speed of the mouse.
// X axis (left/right) configuration:
#define XACCEL_MIN 0.1 // Minimum range of X axis acceleration, values below
// this won't move the mouse at all.
#define XACCEL_MAX 8.0 // Maximum range of X axis acceleration, values above
// this will move the mouse as fast as possible.
#define XMOUSE_RANGE 25.0 // Range of velocity for mouse movements. The higher
// this value the faster the mouse will move.
#define XMOUSE_SCALE 1 // Scaling value to apply to mouse movement, this is
// useful to set to -1 to flip the X axis movement.
// Y axis (up/down) configuration:
// Note that the meaning of these values is exactly the same as the X axis above,
// just applied to the Y axis and up/down mouse movement. You probably want to
// keep these values the same as for the X axis (which is the default, they just
// read the X axis values but you can override with custom values).
#define YACCEL_MIN XACCEL_MIN
#define YACCEL_MAX XACCEL_MAX
#define YMOUSE_RANGE XMOUSE_RANGE
#define YMOUSE_SCALE 1
// Set this true to flip the mouse X/Y axis with the board X/Y axis (what you want
// if holding with USB cable facing up).
#define FLIP_AXES true
// Floating point linear interpolation function that takes a value inside one
// range and maps it to a new value inside another range. This is used to transform
// each axis of acceleration to mouse velocity/speed. See this page for details
// on the equation: https://en.wikipedia.org/wiki/Linear_interpolation
float lerp(float x, float x0, float x1, float y0, float y1) {
// Check if the input value (x) is outside its desired range and clamp to
// those min/max y values.
if (x <= x0) {
return y0;
}
else if (x >= x1) {
return y1;
}
// Otherwise compute the value y based on x's position within its range and
// the desired y min & max.
return y0 + (y1-y0)*((x-x0)/(x1-x0));
}
void setup() {
// Initialize Circuit Playground library.
CircuitPlayground.begin();
// Initialize Arduino mouse library.
Mouse.begin();
}
void loop() {
// Check if the slide switch is enabled (on +) and if not then just exit out
// and run the loop again. This lets you turn on/off the mouse movement with
// the slide switch.
if (!CircuitPlayground.slideSwitch()) {
return;
}
// Grab initial left & right button states to later check if they are pressed
// or released. Do this early in the loop so other processing can take some
// time and the button state change can be detected.
boolean left_first = CircuitPlayground.leftButton();
boolean right_first = CircuitPlayground.rightButton();
// Grab x, y acceleration values (in m/s^2).
float x = CircuitPlayground.motionX();
float y = CircuitPlayground.motionY();
// Use the magnitude of acceleration to interpolate the mouse velocity.
float x_mag = abs(x);
float x_mouse = lerp(x_mag, XACCEL_MIN, XACCEL_MAX, 0.0, XMOUSE_RANGE);
float y_mag = abs(y);
float y_mouse = lerp(y_mag, YACCEL_MIN, YACCEL_MAX, 0.0, YMOUSE_RANGE);
// Change the mouse direction based on the direction of the acceleration.
if (x < 0) {
x_mouse *= -1.0;
}
if (y < 0) {
y_mouse *= -1.0;
}
// Apply any global scaling to the axis (to flip it for example) and truncate
// to an integer value.
x_mouse = floor(x_mouse*XMOUSE_SCALE);
y_mouse = floor(y_mouse*YMOUSE_SCALE);
// Move mouse.
if (!FLIP_AXES) {
// Non-flipped axes, just map board X/Y to mouse X/Y.
Mouse.move((int)x_mouse, (int)y_mouse, 0);
}
else {
// Flipped axes, swap them around.
Mouse.move((int)y_mouse, (int)x_mouse, 0);
}
// Small delay to wait for button state changes and slow down processing a bit.
delay(10);
// Grab a second button state reading to check if the buttons were pressed or
// released.
boolean left_second = CircuitPlayground.leftButton();
boolean right_second = CircuitPlayground.rightButton();
// Check for left button pressed / released.
if (!left_first && left_second) {
// Low then high, button was pressed!
Mouse.press(MOUSE_LEFT);
}
else if (left_first && !left_second) {
// High then low, button was released!
Mouse.release(MOUSE_LEFT);
}
// Check for right button pressed / released.
if (!right_first && right_second) {
// Low then high, button was pressed!
Mouse.press(MOUSE_RIGHT);
}
else if (right_first && !right_second) {
// High then low, button was released!
Mouse.release(MOUSE_RIGHT);
}
}
| 412 | 0.787389 | 1 | 0.787389 | game-dev | MEDIA | 0.35913 | game-dev | 0.960577 | 1 | 0.960577 |
coop-deluxe/sm64coopdx | 78,498 | src/game/mario.c | #include <PR/ultratypes.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "sm64.h"
#include "area.h"
#include "audio/external.h"
#include "behavior_actions.h"
#include "behavior_data.h"
#include "camera.h"
#include "engine/graph_node.h"
#include "engine/math_util.h"
#include "engine/surface_collision.h"
#include "game_init.h"
#include "interaction.h"
#include "level_table.h"
#include "level_update.h"
#include "main.h"
#include "mario.h"
#include "mario_actions_airborne.h"
#include "mario_actions_automatic.h"
#include "mario_actions_cutscene.h"
#include "mario_actions_moving.h"
#include "mario_actions_object.h"
#include "mario_actions_stationary.h"
#include "mario_actions_submerged.h"
#include "mario_misc.h"
#include "mario_step.h"
#include "memory.h"
#include "object_fields.h"
#include "object_helpers.h"
#include "object_list_processor.h"
#include "print.h"
#include "save_file.h"
#include "sound_init.h"
#include "rumble_init.h"
#include "obj_behaviors.h"
#include "hardcoded.h"
#include "pc/configfile.h"
#include "pc/network/network.h"
#include "pc/lua/smlua.h"
#include "pc/network/socket/socket.h"
#include "bettercamera.h"
#include "first_person_cam.h"
#define MAX_HANG_PREVENTION 64
u32 unused80339F10;
s8 filler80339F1C[20];
u16 gLocalBubbleCounter = 0;
/**************************************************
* ANIMATIONS *
**************************************************/
/**
* Checks if Mario's animation has reached its end point.
*/
s32 is_anim_at_end(struct MarioState *m) {
if (!m) { return FALSE; }
struct Object *o = m->marioObj;
if (o->header.gfx.animInfo.curAnim == NULL) { return TRUE; }
return (o->header.gfx.animInfo.animFrame + 1) == o->header.gfx.animInfo.curAnim->loopEnd;
}
/**
* Checks if Mario's animation has surpassed 2 frames before its end point.
*/
s32 is_anim_past_end(struct MarioState *m) {
if (m == NULL || m->marioObj == NULL) { return 0; }
struct Object *o = m->marioObj;
if (o->header.gfx.animInfo.curAnim == NULL) { return 0; }
return o->header.gfx.animInfo.animFrame >= (o->header.gfx.animInfo.curAnim->loopEnd - 2);
}
static s16 mario_set_animation_internal(struct MarioState *m, s32 targetAnimID, s32 accel) {
if (!m) { return 0; }
struct Object *o = m->marioObj;
if (!o || !m->animation) { return 0; }
load_patchable_table(m->animation, targetAnimID, true);
if (!m->animation->targetAnim) { return 0; }
if (o->header.gfx.animInfo.animID != targetAnimID) {
struct Animation *targetAnim = m->animation->targetAnim;
o->header.gfx.animInfo.animID = targetAnimID;
o->header.gfx.animInfo.curAnim = targetAnim;
o->header.gfx.animInfo.animYTrans = m->unkB0;
if (targetAnim->flags & ANIM_FLAG_2) {
o->header.gfx.animInfo.animFrameAccelAssist = (targetAnim->startFrame << 0x10);
} else {
if (targetAnim->flags & ANIM_FLAG_BACKWARD) {
o->header.gfx.animInfo.animFrameAccelAssist = (targetAnim->startFrame << 0x10) + accel;
} else {
o->header.gfx.animInfo.animFrameAccelAssist = (targetAnim->startFrame << 0x10) - accel;
}
}
o->header.gfx.animInfo.animFrame = (o->header.gfx.animInfo.animFrameAccelAssist >> 0x10);
}
o->header.gfx.animInfo.animAccel = accel;
return o->header.gfx.animInfo.animFrame;
}
/**
* Sets Mario's animation without any acceleration, running at its default rate.
*/
s16 set_mario_animation(struct MarioState *m, s32 targetAnimID) {
return mario_set_animation_internal(m, targetAnimID, 0x10000);
}
/**
* Sets Mario's animation where the animation is sped up or
* slowed down via acceleration.
*/
s16 set_mario_anim_with_accel(struct MarioState *m, s32 targetAnimID, s32 accel) {
return mario_set_animation_internal(m, targetAnimID, accel);
}
/**
* Sets the character specific animation without any acceleration, running at its default rate.
*/
s16 set_character_animation(struct MarioState *m, enum CharacterAnimID targetAnimID) {
return mario_set_animation_internal(m, get_character_anim(m, targetAnimID), 0x10000);
}
/**
* Sets character specific animation where the animation is sped up or
* slowed down via acceleration.
*/
s16 set_character_anim_with_accel(struct MarioState *m, enum CharacterAnimID targetAnimID, s32 accel) {
return mario_set_animation_internal(m, get_character_anim(m, targetAnimID), accel);
}
/**
* Sets the animation to a specific "next" frame from the frame given.
*/
void set_anim_to_frame(struct MarioState *m, s16 animFrame) {
if (m == NULL || m->marioObj == NULL) { return; }
struct AnimInfo *animInfo = &m->marioObj->header.gfx.animInfo;
struct Animation *curAnim = animInfo->curAnim;
if (animInfo == NULL) { return; }
if (animInfo->animAccel) {
if (curAnim != NULL && curAnim->flags & ANIM_FLAG_BACKWARD) {
animInfo->animFrameAccelAssist = (animFrame << 0x10) + animInfo->animAccel;
} else {
animInfo->animFrameAccelAssist = (animFrame << 0x10) - animInfo->animAccel;
}
} else {
if (curAnim != NULL && curAnim->flags & ANIM_FLAG_BACKWARD) {
animInfo->animFrame = animFrame + 1;
} else {
animInfo->animFrame = animFrame - 1;
}
}
}
s32 is_anim_past_frame(struct MarioState *m, s16 animFrame) {
s32 isPastFrame;
s32 acceleratedFrame = animFrame << 0x10;
if (!m || !m->marioObj) { return TRUE; }
struct AnimInfo *animInfo = &m->marioObj->header.gfx.animInfo;
if (!animInfo->curAnim) { return TRUE; }
struct Animation *curAnim = animInfo->curAnim;
if (animInfo->animAccel) {
if (curAnim->flags & ANIM_FLAG_BACKWARD) {
isPastFrame =
(animInfo->animFrameAccelAssist > acceleratedFrame)
&& (acceleratedFrame >= (animInfo->animFrameAccelAssist - animInfo->animAccel));
} else {
isPastFrame =
(animInfo->animFrameAccelAssist < acceleratedFrame)
&& (acceleratedFrame <= (animInfo->animFrameAccelAssist + animInfo->animAccel));
}
} else {
if (curAnim->flags & ANIM_FLAG_BACKWARD) {
isPastFrame = (animInfo->animFrame == (animFrame + 1));
} else {
isPastFrame = ((animInfo->animFrame + 1) == animFrame);
}
}
return isPastFrame;
}
/**
* Rotates the animation's translation into the global coordinate system
* and returns the animation's flags.
*/
s16 find_mario_anim_flags_and_translation(struct Object *obj, s32 yaw, Vec3s translation) {
if (!obj) { return 0; }
f32 dx;
f32 dz;
struct Animation *curAnim = (void *) obj->header.gfx.animInfo.curAnim;
if (curAnim == NULL) { return 0; }
s16 animFrame = geo_update_animation_frame(&obj->header.gfx.animInfo, NULL);
u16 *animIndex = segmented_to_virtual((void *) curAnim->index);
f32 s = (f32) sins(yaw);
f32 c = (f32) coss(yaw);
dx = retrieve_animation_value(curAnim, animFrame, &animIndex) / 4.0f;
translation[1] = retrieve_animation_value(curAnim, animFrame, &animIndex) / 4.0f;
dz = retrieve_animation_value(curAnim, animFrame, &animIndex) / 4.0f;
translation[0] = (dx * c) + (dz * s);
translation[2] = (-dx * s) + (dz * c);
return curAnim->flags;
}
/**
* Updates Mario's position from his animation's translation.
*/
void update_mario_pos_for_anim(struct MarioState *m) {
if (!m) { return; }
Vec3s translation;
s16 flags;
flags = find_mario_anim_flags_and_translation(m->marioObj, m->faceAngle[1], translation);
if (flags & (ANIM_FLAG_HOR_TRANS | ANIM_FLAG_6)) {
m->pos[0] += (f32) translation[0];
m->pos[2] += (f32) translation[2];
}
if (flags & (ANIM_FLAG_VERT_TRANS | ANIM_FLAG_6)) {
m->pos[1] += (f32) translation[1];
}
}
/**
* Finds the vertical translation from Mario's animation.
*/
s16 return_mario_anim_y_translation(struct MarioState *m) {
if (!m) { return 0; }
Vec3s translation = { 0 };
find_mario_anim_flags_and_translation(m->marioObj, 0, translation);
return translation[1];
}
/**************************************************
* AUDIO *
**************************************************/
/**
* Plays a sound if if Mario doesn't have the flag being checked.
*/
void play_sound_if_no_flag(struct MarioState *m, u32 soundBits, u32 flags) {
if (!m) { return; }
if (!(m->flags & flags)) {
play_sound(soundBits, m->marioObj->header.gfx.cameraToObject);
m->flags |= flags;
}
}
/**
* Plays a jump sound if one has not been played since the last action change.
*/
void play_mario_jump_sound(struct MarioState *m) {
if (!m) { return; }
if (!(m->flags & MARIO_MARIO_SOUND_PLAYED)) {
#ifndef VERSION_JP
if (m->action == ACT_TRIPLE_JUMP) {
play_character_sound_offset(m, CHAR_SOUND_YAHOO_WAHA_YIPPEE, ((gAudioRandom % 5) << 16));
} else {
#endif
play_character_sound_offset(m, CHAR_SOUND_YAH_WAH_HOO, ((gAudioRandom % 3) << 16));
#ifndef VERSION_JP
}
#endif
m->flags |= MARIO_MARIO_SOUND_PLAYED;
}
}
/**
* Adjusts the volume/pitch of sounds from Mario's speed.
*/
void adjust_sound_for_speed(struct MarioState *m) {
if (!m) { return; }
s32 absForwardVel = (m->forwardVel > 0.0f) ? m->forwardVel : -m->forwardVel;
set_sound_moving_speed(SOUND_BANK_MOVING, (absForwardVel > 100) ? 100 : absForwardVel);
}
/**
* Spawns particles if the step sound says to, then either plays a step sound or relevant other sound.
*/
void play_sound_and_spawn_particles(struct MarioState *m, u32 soundBits, u32 waveParticleType) {
if (!m) { return; }
if (m->terrainSoundAddend == (SOUND_TERRAIN_WATER << 16)) {
if (waveParticleType != 0) {
set_mario_particle_flags(m, PARTICLE_SHALLOW_WATER_SPLASH, FALSE);
} else {
set_mario_particle_flags(m, PARTICLE_SHALLOW_WATER_WAVE, FALSE);
}
} else {
if (m->terrainSoundAddend == (SOUND_TERRAIN_SAND << 16)) {
set_mario_particle_flags(m, PARTICLE_DIRT, FALSE);
} else if (m->terrainSoundAddend == (SOUND_TERRAIN_SNOW << 16)) {
set_mario_particle_flags(m, PARTICLE_SNOW, FALSE);
}
}
if (soundBits == CHAR_SOUND_PUNCH_HOO) {
play_character_sound(m, CHAR_SOUND_PUNCH_HOO);
return;
}
if ((m->flags & MARIO_METAL_CAP) || soundBits == SOUND_ACTION_UNSTUCK_FROM_GROUND) {
play_sound(soundBits, m->marioObj->header.gfx.cameraToObject);
} else {
play_sound(m->terrainSoundAddend + soundBits, m->marioObj->header.gfx.cameraToObject);
}
}
/**
* Plays an environmental sound if one has not been played since the last action change.
*/
void play_mario_action_sound(struct MarioState *m, u32 soundBits, u32 waveParticleType) {
if (!m) { return; }
if (!(m->flags & MARIO_ACTION_SOUND_PLAYED)) {
play_sound_and_spawn_particles(m, soundBits, waveParticleType);
m->flags |= MARIO_ACTION_SOUND_PLAYED;
}
}
/**
* Plays a landing sound, accounting for metal cap.
*/
void play_mario_landing_sound(struct MarioState *m, u32 soundBits) {
if (!m) { return; }
play_sound_and_spawn_particles(
m, (m->flags & MARIO_METAL_CAP) ? SOUND_ACTION_METAL_LANDING : soundBits, 1);
}
/**
* Plays a landing sound, accounting for metal cap. Unlike play_mario_landing_sound,
* this function uses play_mario_action_sound, making sure the sound is only
* played once per action.
*/
void play_mario_landing_sound_once(struct MarioState *m, u32 soundBits) {
if (!m) { return; }
play_mario_action_sound(
m, (m->flags & MARIO_METAL_CAP) ? SOUND_ACTION_METAL_LANDING : soundBits, 1);
}
/**
* Plays a heavy landing (ground pound, etc.) sound, accounting for metal cap.
*/
void play_mario_heavy_landing_sound(struct MarioState *m, u32 soundBits) {
if (!m) { return; }
play_sound_and_spawn_particles(
m, (m->flags & MARIO_METAL_CAP) ? SOUND_ACTION_METAL_HEAVY_LANDING : soundBits, 1);
}
/**
* Plays a heavy landing (ground pound, etc.) sound, accounting for metal cap.
* Unlike play_mario_heavy_landing_sound, this function uses play_mario_action_sound,
* making sure the sound is only played once per action.
*/
void play_mario_heavy_landing_sound_once(struct MarioState *m, u32 soundBits) {
if (!m) { return; }
play_mario_action_sound(
m, (m->flags & MARIO_METAL_CAP) ? SOUND_ACTION_METAL_HEAVY_LANDING : soundBits, 1);
}
/**
* Plays action and Mario sounds relevant to what was passed into the function.
*/
void play_mario_sound(struct MarioState *m, s32 actionSound, s32 marioSound) {
if (!m) { return; }
if (actionSound == SOUND_ACTION_TERRAIN_JUMP) {
play_mario_action_sound(m, (m->flags & MARIO_METAL_CAP) ? (s32) SOUND_ACTION_METAL_JUMP
: (s32) SOUND_ACTION_TERRAIN_JUMP, 1);
} else {
play_sound_if_no_flag(m, actionSound, MARIO_ACTION_SOUND_PLAYED);
}
if (marioSound == 0) {
play_mario_jump_sound(m);
}
if (marioSound != -1) {
play_character_sound_if_no_flag(m, marioSound, MARIO_MARIO_SOUND_PLAYED);
}
}
/**************************************************
* ACTIONS *
**************************************************/
bool mario_is_crouching(struct MarioState *m) {
if (!m) { return false; }
return m->action == ACT_START_CROUCHING || m->action == ACT_CROUCHING || m->action == ACT_STOP_CROUCHING ||
m->action == ACT_START_CRAWLING || m->action == ACT_CRAWLING || m->action == ACT_STOP_CRAWLING ||
m->action == ACT_CROUCH_SLIDE;
}
bool mario_is_ground_pound_landing(struct MarioState *m) {
if (!m) { return false; }
return m->action == ACT_GROUND_POUND_LAND ||
(!(m->action & ACT_FLAG_AIR) && (determine_interaction(m, m->marioObj) & INT_GROUND_POUND));
}
bool mario_can_bubble(struct MarioState* m) {
if (!m) { return false; }
if (!gServerSettings.bubbleDeath) { return false; }
if (m->playerIndex != 0) { return false; }
if (m->action == ACT_BUBBLED) { return false; }
if (!m->visibleToEnemies) { return false; }
u8 allInBubble = TRUE;
for (s32 i = 1; i < MAX_PLAYERS; i++) {
if (!is_player_active(&gMarioStates[i])) { continue; }
if (!gMarioStates[i].visibleToEnemies) { continue; }
if (gMarioStates[i].action != ACT_BUBBLED && gMarioStates[i].health >= 0x100) {
allInBubble = FALSE;
break;
}
}
if (allInBubble) { return false; }
return true;
}
void mario_set_bubbled(struct MarioState* m) {
if (!m) { return; }
if (m->playerIndex != 0) { return; }
if (m->action == ACT_BUBBLED) { return; }
gLocalBubbleCounter = 20;
drop_and_set_mario_action(m, ACT_BUBBLED, 0);
if (m->numLives > -1) {
m->numLives--;
}
m->healCounter = 0;
m->hurtCounter = 31;
gCamera->cutscene = 0;
m->statusForCamera->action = m->action;
m->statusForCamera->cameraEvent = 0;
m->marioObj->activeFlags |= ACTIVE_FLAG_MOVE_THROUGH_GRATE;
extern s16 gCutsceneTimer;
gCutsceneTimer = 0;
soft_reset_camera(m->area->camera);
}
/**
* Sets Mario's other velocities from his forward speed.
*/
void mario_set_forward_vel(struct MarioState *m, f32 forwardVel) {
if (!m) { return; }
m->forwardVel = forwardVel;
m->slideVelX = sins(m->faceAngle[1]) * m->forwardVel;
m->slideVelZ = coss(m->faceAngle[1]) * m->forwardVel;
m->vel[0] = (f32) m->slideVelX;
m->vel[2] = (f32) m->slideVelZ;
}
/**
* Returns the slipperiness class of Mario's floor.
*/
s32 mario_get_floor_class(struct MarioState *m) {
if (!m) { return SURFACE_CLASS_NOT_SLIPPERY; }
s32 floorClass;
// The slide terrain type defaults to slide slipperiness.
// This doesn't matter too much since normally the slide terrain
// is checked for anyways.
if ((m->area->terrainType & TERRAIN_MASK) == TERRAIN_SLIDE) {
floorClass = SURFACE_CLASS_VERY_SLIPPERY;
} else {
floorClass = SURFACE_CLASS_DEFAULT;
}
if (m->floor != NULL) {
switch (m->floor->type) {
case SURFACE_NOT_SLIPPERY:
case SURFACE_HARD_NOT_SLIPPERY:
case SURFACE_SWITCH:
floorClass = SURFACE_CLASS_NOT_SLIPPERY;
break;
case SURFACE_SLIPPERY:
case SURFACE_NOISE_SLIPPERY:
case SURFACE_HARD_SLIPPERY:
case SURFACE_NO_CAM_COL_SLIPPERY:
floorClass = SURFACE_CLASS_SLIPPERY;
break;
case SURFACE_VERY_SLIPPERY:
case SURFACE_ICE:
case SURFACE_HARD_VERY_SLIPPERY:
case SURFACE_NOISE_VERY_SLIPPERY_73:
case SURFACE_NOISE_VERY_SLIPPERY_74:
case SURFACE_NOISE_VERY_SLIPPERY:
case SURFACE_NO_CAM_COL_VERY_SLIPPERY:
floorClass = SURFACE_CLASS_VERY_SLIPPERY;
break;
}
}
// Crawling allows Mario to not slide on certain steeper surfaces.
if (m->action == ACT_CRAWLING && m->floor && m->floor->normal.y > 0.5f && floorClass == SURFACE_CLASS_DEFAULT) {
floorClass = SURFACE_CLASS_NOT_SLIPPERY;
}
s32 returnValue = 0;
if (smlua_call_event_hooks_mario_param_and_int_ret_int(HOOK_MARIO_OVERRIDE_FLOOR_CLASS, m, floorClass, &returnValue)) return returnValue;
return floorClass;
}
// clang-format off
s8 sTerrainSounds[7][6] = {
// default, hard, slippery,
// very slippery, noisy default, noisy slippery
{ SOUND_TERRAIN_DEFAULT, SOUND_TERRAIN_STONE, SOUND_TERRAIN_GRASS,
SOUND_TERRAIN_GRASS, SOUND_TERRAIN_GRASS, SOUND_TERRAIN_DEFAULT }, // TERRAIN_GRASS
{ SOUND_TERRAIN_STONE, SOUND_TERRAIN_STONE, SOUND_TERRAIN_STONE,
SOUND_TERRAIN_STONE, SOUND_TERRAIN_GRASS, SOUND_TERRAIN_GRASS }, // TERRAIN_STONE
{ SOUND_TERRAIN_SNOW, SOUND_TERRAIN_ICE, SOUND_TERRAIN_SNOW,
SOUND_TERRAIN_ICE, SOUND_TERRAIN_STONE, SOUND_TERRAIN_STONE }, // TERRAIN_SNOW
{ SOUND_TERRAIN_SAND, SOUND_TERRAIN_STONE, SOUND_TERRAIN_SAND,
SOUND_TERRAIN_SAND, SOUND_TERRAIN_STONE, SOUND_TERRAIN_STONE }, // TERRAIN_SAND
{ SOUND_TERRAIN_SPOOKY, SOUND_TERRAIN_SPOOKY, SOUND_TERRAIN_SPOOKY,
SOUND_TERRAIN_SPOOKY, SOUND_TERRAIN_STONE, SOUND_TERRAIN_STONE }, // TERRAIN_SPOOKY
{ SOUND_TERRAIN_DEFAULT, SOUND_TERRAIN_STONE, SOUND_TERRAIN_GRASS,
SOUND_TERRAIN_ICE, SOUND_TERRAIN_STONE, SOUND_TERRAIN_ICE }, // TERRAIN_WATER
{ SOUND_TERRAIN_STONE, SOUND_TERRAIN_STONE, SOUND_TERRAIN_STONE,
SOUND_TERRAIN_STONE, SOUND_TERRAIN_ICE, SOUND_TERRAIN_ICE }, // TERRAIN_SLIDE
};
// clang-format on
/**
* Computes a value that should be added to terrain sounds before playing them.
* This depends on surfaces and terrain.
*/
u32 mario_get_terrain_sound_addend(struct MarioState *m) {
if (!m) { return SURFACE_CLASS_NOT_SLIPPERY; }
s16 floorSoundType;
s16 terrainType = m->area->terrainType & TERRAIN_MASK;
s32 ret = SOUND_TERRAIN_DEFAULT << 16;
s32 floorType;
if (m->floor != NULL) {
floorType = m->floor->type;
if ((gCurrLevelNum != LEVEL_LLL) && (m->floorHeight < (m->waterLevel - 10))) {
// Water terrain sound, excluding LLL since it uses water in the volcano.
ret = SOUND_TERRAIN_WATER << 16;
} else if (SURFACE_IS_QUICKSAND(floorType)) {
ret = SOUND_TERRAIN_SAND << 16;
} else {
switch (floorType) {
default:
floorSoundType = 0;
break;
case SURFACE_NOT_SLIPPERY:
case SURFACE_HARD:
case SURFACE_HARD_NOT_SLIPPERY:
case SURFACE_SWITCH:
floorSoundType = 1;
break;
case SURFACE_SLIPPERY:
case SURFACE_HARD_SLIPPERY:
case SURFACE_NO_CAM_COL_SLIPPERY:
floorSoundType = 2;
break;
case SURFACE_VERY_SLIPPERY:
case SURFACE_ICE:
case SURFACE_HARD_VERY_SLIPPERY:
case SURFACE_NOISE_VERY_SLIPPERY_73:
case SURFACE_NOISE_VERY_SLIPPERY_74:
case SURFACE_NOISE_VERY_SLIPPERY:
case SURFACE_NO_CAM_COL_VERY_SLIPPERY:
floorSoundType = 3;
break;
case SURFACE_NOISE_DEFAULT:
floorSoundType = 4;
break;
case SURFACE_NOISE_SLIPPERY:
floorSoundType = 5;
break;
}
ret = sTerrainSounds[terrainType][floorSoundType] << 16;
}
}
return ret;
}
/**
* Collides with walls and returns the most recent wall.
*/
struct Surface *resolve_and_return_wall_collisions(Vec3f pos, f32 offset, f32 radius) {
struct WallCollisionData collisionData;
struct Surface *wall = NULL;
collisionData.x = pos[0];
collisionData.y = pos[1];
collisionData.z = pos[2];
collisionData.radius = radius;
collisionData.offsetY = offset;
if (find_wall_collisions(&collisionData)) {
wall = collisionData.walls[collisionData.numWalls - 1];
}
// I'm not sure if this code is actually ever used or not.
pos[0] = collisionData.x;
pos[1] = collisionData.y;
pos[2] = collisionData.z;
return wall;
}
/**
* Collides with walls and returns the wall collision data.
*/
void resolve_and_return_wall_collisions_data(Vec3f pos, f32 offset, f32 radius, struct WallCollisionData* collisionData) {
if (!collisionData || !pos) { return; }
collisionData->x = pos[0];
collisionData->y = pos[1];
collisionData->z = pos[2];
collisionData->radius = radius;
collisionData->offsetY = offset;
find_wall_collisions(collisionData);
pos[0] = collisionData->x;
pos[1] = collisionData->y;
pos[2] = collisionData->z;
}
/**
* Finds the ceiling from a vec3f horizontally and a height (with 80 vertical buffer).
*/
f32 vec3f_find_ceil(Vec3f pos, f32 height, struct Surface **ceil) {
if (!ceil) { return 0; }
UNUSED f32 unused;
return find_ceil(pos[0], height + 80.0f, pos[2], ceil);
}
/**
* Finds the ceiling from a vec3f horizontally and a height (with 80 vertical buffer).
* Prevents exposed ceiling bug
*/
// Prevent exposed ceilings
f32 vec3f_mario_ceil(Vec3f pos, f32 height, struct Surface **ceil) {
if (!ceil) { return 0; }
if (gLevelValues.fixCollisionBugs) {
height = MAX(height + 80.0f, pos[1] - 2);
return find_ceil(pos[0], height, pos[2], ceil);
} else {
return vec3f_find_ceil(pos, height, ceil);
}
}
/**
* Determines if Mario is facing "downhill."
*/
s32 mario_facing_downhill(struct MarioState *m, s32 turnYaw) {
if (!m) { return 0; }
s16 faceAngleYaw = m->faceAngle[1];
// This is never used in practice, as turnYaw is
// always passed as zero.
if (turnYaw && m->forwardVel < 0.0f) {
faceAngleYaw += 0x8000;
}
faceAngleYaw = m->floorAngle - faceAngleYaw;
return (-0x4000 < faceAngleYaw) && (faceAngleYaw < 0x4000);
}
/**
* Determines if a surface is slippery based on the surface class.
*/
u32 mario_floor_is_slippery(struct MarioState *m) {
if (!m) { return FALSE; }
if (!m->floor) { return FALSE; }
f32 normY;
if ((m->area->terrainType & TERRAIN_MASK) == TERRAIN_SLIDE
&& m->floor->normal.y < 0.9998477f //~cos(1 deg)
) {
return TRUE;
}
switch (mario_get_floor_class(m)) {
case SURFACE_VERY_SLIPPERY:
normY = 0.9848077f; //~cos(10 deg)
break;
case SURFACE_SLIPPERY:
normY = 0.9396926f; //~cos(20 deg)
break;
default:
normY = 0.7880108f; //~cos(38 deg)
break;
case SURFACE_NOT_SLIPPERY:
normY = 0.0f;
break;
}
return m->floor->normal.y <= normY;
}
/**
* Determines if a surface is a slope based on the surface class.
*/
s32 mario_floor_is_slope(struct MarioState *m) {
if (!m) { return FALSE; }
if (!m->floor) { return FALSE; }
f32 normY;
if ((m->area->terrainType & TERRAIN_MASK) == TERRAIN_SLIDE
&& m->floor->normal.y < 0.9998477f) { // ~cos(1 deg)
return TRUE;
}
switch (mario_get_floor_class(m)) {
case SURFACE_VERY_SLIPPERY:
normY = 0.9961947f; // ~cos(5 deg)
break;
case SURFACE_SLIPPERY:
normY = 0.9848077f; // ~cos(10 deg)
break;
default:
normY = 0.9659258f; // ~cos(15 deg)
break;
case SURFACE_NOT_SLIPPERY:
normY = 0.9396926f; // ~cos(20 deg)
break;
}
return m->floor->normal.y <= normY;
}
/**
* Determines if a surface is steep based on the surface class.
*/
s32 mario_floor_is_steep(struct MarioState *m) {
if (!m) { return FALSE; }
if (!m->floor) { return FALSE; }
f32 normY;
s32 result = FALSE;
// Interestingly, this function does not check for the
// slide terrain type. This means that steep behavior persists for
// non-slippery and slippery surfaces.
// This does not matter in vanilla game practice.
if (!mario_facing_downhill(m, FALSE)) {
switch (mario_get_floor_class(m)) {
case SURFACE_VERY_SLIPPERY:
normY = 0.9659258f; // ~cos(15 deg)
break;
case SURFACE_SLIPPERY:
normY = 0.9396926f; // ~cos(20 deg)
break;
default:
normY = 0.8660254f; // ~cos(30 deg)
break;
case SURFACE_NOT_SLIPPERY:
normY = 0.8660254f; // ~cos(30 deg)
break;
}
result = m->floor->normal.y <= normY;
}
return result;
}
/**
* Finds the floor height relative from Mario given polar displacement.
*/
f32 find_floor_height_relative_polar(struct MarioState *m, s16 angleFromMario, f32 distFromMario) {
if (!m) { return 0; }
struct Surface *floor;
f32 floorY;
f32 y = sins(m->faceAngle[1] + angleFromMario) * distFromMario;
f32 x = coss(m->faceAngle[1] + angleFromMario) * distFromMario;
floorY = find_floor(m->pos[0] + y, m->pos[1] + 100.0f, m->pos[2] + x, &floor);
return floorY;
}
/**
* Returns the slope of the floor based off points around Mario.
*/
s16 find_floor_slope(struct MarioState *m, s16 yawOffset) {
if (!m) { return 0; }
struct Surface *floor;
f32 forwardFloorY, backwardFloorY;
f32 forwardYDelta, backwardYDelta;
s16 result;
f32 x = sins(m->faceAngle[1] + yawOffset) * 5.0f;
f32 z = coss(m->faceAngle[1] + yawOffset) * 5.0f;
forwardFloorY = find_floor(m->pos[0] + x, m->pos[1] + 100.0f, m->pos[2] + z, &floor);
backwardFloorY = find_floor(m->pos[0] - x, m->pos[1] + 100.0f, m->pos[2] - z, &floor);
//! If Mario is near OOB, these floorY's can sometimes be -11000.
// This will cause these to be off and give improper slopes.
forwardYDelta = forwardFloorY - m->pos[1];
backwardYDelta = m->pos[1] - backwardFloorY;
if (forwardYDelta * forwardYDelta < backwardYDelta * backwardYDelta) {
result = atan2s(5.0f, forwardYDelta);
} else {
result = atan2s(5.0f, backwardYDelta);
}
return result;
}
/**
* Adjusts Mario's camera and sound based on his action status.
*/
void update_mario_sound_and_camera(struct MarioState *m) {
if (!m) { return; }
// only update for local player
if (m != &gMarioStates[0]) { return; }
if (!m->area || !m->area->camera) { return; }
u32 action = m->action;
s32 camPreset = m->area->camera->mode;
if (action == ACT_FIRST_PERSON) {
if (m->playerIndex == 0) {
raise_background_noise(2);
gCameraMovementFlags &= ~CAM_MOVE_C_UP_MODE;
// Go back to the last camera mode
set_camera_mode(m->area->camera, -1, 1);
}
} else if (action == ACT_SLEEPING) {
if (m->playerIndex == 0) {
raise_background_noise(2);
}
}
if (m->playerIndex == 0) {
if (!(action & (ACT_FLAG_SWIMMING | ACT_FLAG_METAL_WATER))) {
if (camPreset == CAMERA_MODE_BEHIND_MARIO || camPreset == CAMERA_MODE_WATER_SURFACE) {
set_camera_mode(m->area->camera, m->area->camera->defMode, 1);
}
}
}
}
/**
* Transitions Mario to a steep jump action.
*/
void set_steep_jump_action(struct MarioState *m) {
if (!m) { return; }
m->marioObj->oMarioSteepJumpYaw = m->faceAngle[1];
if (m->forwardVel > 0.0f) {
//! ((s16)0x8000) has undefined behavior. Therefore, this downcast has
// undefined behavior if m->floorAngle >= 0.
s16 angleTemp = m->floorAngle + 0x8000;
s16 faceAngleTemp = m->faceAngle[1] - angleTemp;
f32 y = sins(faceAngleTemp) * m->forwardVel;
f32 x = coss(faceAngleTemp) * m->forwardVel * 0.75f;
m->forwardVel = sqrtf(y * y + x * x);
m->faceAngle[1] = atan2s(x, y) + angleTemp;
}
drop_and_set_mario_action(m, ACT_STEEP_JUMP, 0);
}
/**
* Sets Mario's vertical speed from his forward speed.
*/
void set_mario_y_vel_based_on_fspeed(struct MarioState *m, f32 initialVelY, f32 multiplier) {
if (!m) { return; }
// get_additive_y_vel_for_jumps is always 0 and a stubbed function.
// It was likely trampoline related based on code location.
m->vel[1] = initialVelY + get_additive_y_vel_for_jumps() + m->forwardVel * multiplier;
if (m->squishTimer != 0 || m->quicksandDepth > 1.0f) {
m->vel[1] *= 0.5f;
}
}
/**
* Transitions for a variety of airborne actions.
*/
static u32 set_mario_action_airborne(struct MarioState *m, u32 action, u32 actionArg) {
if (!m) { return FALSE; }
f32 fowardVel;
if ((m->squishTimer != 0 || m->quicksandDepth >= 1.0f)
&& (action == ACT_DOUBLE_JUMP || action == ACT_TWIRLING)) {
action = ACT_JUMP;
}
switch (action) {
case ACT_DOUBLE_JUMP:
set_mario_y_vel_based_on_fspeed(m, 52.0f, 0.25f);
m->forwardVel *= 0.8f;
break;
case ACT_BACKFLIP:
m->marioObj->header.gfx.animInfo.animID = -1;
m->forwardVel = -16.0f;
set_mario_y_vel_based_on_fspeed(m, 62.0f, 0.0f);
break;
case ACT_TRIPLE_JUMP:
set_mario_y_vel_based_on_fspeed(m, 69.0f, 0.0f);
m->forwardVel *= 0.8f;
break;
case ACT_FLYING_TRIPLE_JUMP:
set_mario_y_vel_based_on_fspeed(m, 82.0f, 0.0f);
break;
case ACT_WATER_JUMP:
case ACT_HOLD_WATER_JUMP:
if (actionArg == 0) {
set_mario_y_vel_based_on_fspeed(m, 42.0f, 0.0f);
}
break;
case ACT_BURNING_JUMP:
m->vel[1] = 31.5f;
m->forwardVel = 8.0f;
break;
case ACT_RIDING_SHELL_JUMP:
set_mario_y_vel_based_on_fspeed(m, 42.0f, 0.25f);
break;
case ACT_JUMP:
case ACT_HOLD_JUMP:
m->marioObj->header.gfx.animInfo.animID = -1;
set_mario_y_vel_based_on_fspeed(m, 42.0f, 0.25f);
m->forwardVel *= 0.8f;
break;
case ACT_WALL_KICK_AIR:
case ACT_TOP_OF_POLE_JUMP:
set_mario_y_vel_based_on_fspeed(m, 62.0f, 0.0f);
if (m->forwardVel < 24.0f) {
m->forwardVel = 24.0f;
}
m->wallKickTimer = 0;
break;
case ACT_SIDE_FLIP:
set_mario_y_vel_based_on_fspeed(m, 62.0f, 0.0f);
m->forwardVel = 8.0f;
m->faceAngle[1] = m->intendedYaw;
break;
case ACT_STEEP_JUMP:
m->marioObj->header.gfx.animInfo.animID = -1;
set_mario_y_vel_based_on_fspeed(m, 42.0f, 0.25f);
m->faceAngle[0] = -0x2000;
break;
case ACT_LAVA_BOOST:
m->vel[1] = 84.0f;
if (actionArg == 0) {
m->forwardVel = 0.0f;
}
break;
case ACT_DIVE:
if ((fowardVel = m->forwardVel + 15.0f) > 48.0f) {
fowardVel = 48.0f;
}
mario_set_forward_vel(m, fowardVel);
break;
case ACT_LONG_JUMP:
m->marioObj->header.gfx.animInfo.animID = -1;
set_mario_y_vel_based_on_fspeed(m, 30.0f, 0.0f);
m->marioObj->oMarioLongJumpIsSlow = m->forwardVel > 16.0f ? FALSE : TRUE;
//! (BLJ's) This properly handles long jumps from getting forward speed with
// too much velocity, but misses backwards longs allowing high negative speeds.
if ((m->forwardVel *= 1.5f) > 48.0f) {
m->forwardVel = 48.0f;
}
break;
case ACT_SLIDE_KICK:
m->vel[1] = 12.0f;
if (m->forwardVel < 32.0f) {
m->forwardVel = 32.0f;
}
break;
case ACT_JUMP_KICK:
m->vel[1] = 20.0f;
break;
}
m->peakHeight = m->pos[1];
m->flags |= MARIO_UNKNOWN_08;
return action;
}
/**
* Transitions for a variety of moving actions.
*/
static u32 set_mario_action_moving(struct MarioState *m, u32 action, UNUSED u32 actionArg) {
if (!m) { return FALSE; }
s16 floorClass = mario_get_floor_class(m);
f32 forwardVel = m->forwardVel;
f32 mag = min(m->intendedMag, 8.0f);
switch (action) {
case ACT_WALKING:
if (floorClass != SURFACE_CLASS_VERY_SLIPPERY) {
if (0.0f <= forwardVel && forwardVel < mag) {
m->forwardVel = mag;
}
}
m->marioObj->oMarioWalkingPitch = 0;
break;
case ACT_HOLD_WALKING:
if (0.0f <= forwardVel && forwardVel < mag / 2.0f) {
m->forwardVel = mag / 2.0f;
}
break;
case ACT_BEGIN_SLIDING:
if (mario_facing_downhill(m, FALSE)) {
action = ACT_BUTT_SLIDE;
} else {
action = ACT_STOMACH_SLIDE;
}
break;
case ACT_HOLD_BEGIN_SLIDING:
if (mario_facing_downhill(m, FALSE)) {
action = ACT_HOLD_BUTT_SLIDE;
} else {
action = ACT_HOLD_STOMACH_SLIDE;
}
break;
}
return action;
}
/**
* Transition for certain submerged actions, which is actually just the metal jump actions.
*/
static u32 set_mario_action_submerged(struct MarioState *m, u32 action, UNUSED u32 actionArg) {
if (!m) { return FALSE; }
if (action == ACT_METAL_WATER_JUMP || action == ACT_HOLD_METAL_WATER_JUMP) {
m->vel[1] = 32.0f;
}
return action;
}
/**
* Transitions for a variety of cutscene actions.
*/
static u32 set_mario_action_cutscene(struct MarioState *m, u32 action, UNUSED u32 actionArg) {
if (!m) { return FALSE; }
switch (action) {
case ACT_EMERGE_FROM_PIPE:
m->vel[1] = 52.0f;
break;
case ACT_FALL_AFTER_STAR_GRAB:
mario_set_forward_vel(m, 0.0f);
break;
case ACT_SPAWN_SPIN_AIRBORNE:
mario_set_forward_vel(m, 2.0f);
break;
case ACT_SPECIAL_EXIT_AIRBORNE:
case ACT_SPECIAL_DEATH_EXIT:
m->vel[1] = 64.0f;
break;
}
return action;
}
/**
* Puts Mario into a given action, putting Mario through the appropriate
* specific function if needed.
*/
u32 set_mario_action(struct MarioState *m, u32 action, u32 actionArg) {
if (!m) { return FALSE; }
u32 returnValue = 0;
smlua_call_event_hooks_mario_action_and_arg_ret_int(HOOK_BEFORE_SET_MARIO_ACTION, m, action, actionArg, &returnValue);
if (returnValue == 1) { return TRUE; } else if (returnValue) { action = returnValue; }
switch (action & ACT_GROUP_MASK) {
case ACT_GROUP_MOVING:
action = set_mario_action_moving(m, action, actionArg);
break;
case ACT_GROUP_AIRBORNE:
action = set_mario_action_airborne(m, action, actionArg);
break;
case ACT_GROUP_SUBMERGED:
action = set_mario_action_submerged(m, action, actionArg);
break;
case ACT_GROUP_CUTSCENE:
action = set_mario_action_cutscene(m, action, actionArg);
break;
}
// Resets the sound played flags, meaning Mario can play those sound types again.
m->flags &= ~(MARIO_ACTION_SOUND_PLAYED | MARIO_MARIO_SOUND_PLAYED);
if (!(m->action & ACT_FLAG_AIR)) {
m->flags &= ~MARIO_UNKNOWN_18;
}
// Initialize the action information.
m->prevAction = m->action;
m->action = action;
m->actionArg = actionArg;
m->actionState = 0;
m->actionTimer = 0;
smlua_call_event_hooks_mario_param(HOOK_ON_SET_MARIO_ACTION, m);
return TRUE;
}
/**
* Puts Mario into a specific jumping action from a landing action.
*/
s32 set_jump_from_landing(struct MarioState *m) {
if (!m) { return FALSE; }
if (m->quicksandDepth >= 11.0f) {
if (m->heldObj == NULL) {
return set_mario_action(m, ACT_QUICKSAND_JUMP_LAND, 0);
} else {
return set_mario_action(m, ACT_HOLD_QUICKSAND_JUMP_LAND, 0);
}
}
if (mario_floor_is_steep(m)) {
set_steep_jump_action(m);
} else {
if ((m->doubleJumpTimer == 0) || (m->squishTimer != 0)) {
set_mario_action(m, ACT_JUMP, 0);
} else {
switch (m->prevAction) {
case ACT_JUMP_LAND:
set_mario_action(m, ACT_DOUBLE_JUMP, 0);
break;
case ACT_FREEFALL_LAND:
set_mario_action(m, ACT_DOUBLE_JUMP, 0);
break;
case ACT_SIDE_FLIP_LAND_STOP:
set_mario_action(m, ACT_DOUBLE_JUMP, 0);
break;
case ACT_DOUBLE_JUMP_LAND:
// If Mario has a wing cap, he ignores the typical speed
// requirement for a triple jump.
if (m->flags & MARIO_WING_CAP) {
set_mario_action(m, ACT_FLYING_TRIPLE_JUMP, 0);
} else if (m->forwardVel > 20.0f) {
set_mario_action(m, ACT_TRIPLE_JUMP, 0);
} else {
set_mario_action(m, ACT_JUMP, 0);
}
break;
default:
set_mario_action(m, ACT_JUMP, 0);
break;
}
}
}
m->doubleJumpTimer = 0;
return TRUE;
}
/**
* Puts Mario in a given action, as long as it is not overruled by
* either a quicksand or steep jump.
*/
s32 set_jumping_action(struct MarioState *m, u32 action, u32 actionArg) {
if (!m) { return FALSE; }
UNUSED u32 currAction = m->action;
if (m->quicksandDepth >= 11.0f) {
// Checks whether Mario is holding an object or not.
if (m->heldObj == NULL) {
return set_mario_action(m, ACT_QUICKSAND_JUMP_LAND, 0);
} else {
return set_mario_action(m, ACT_HOLD_QUICKSAND_JUMP_LAND, 0);
}
}
if (mario_floor_is_steep(m)) {
set_steep_jump_action(m);
} else {
set_mario_action(m, action, actionArg);
}
return TRUE;
}
/**
* Drop anything Mario is holding and set a new action.
*/
s32 drop_and_set_mario_action(struct MarioState *m, u32 action, u32 actionArg) {
if (!m) { return FALSE; }
mario_stop_riding_and_holding(m);
return set_mario_action(m, action, actionArg);
}
/**
* Increment Mario's hurt counter and set a new action.
*/
s32 hurt_and_set_mario_action(struct MarioState *m, u32 action, u32 actionArg, s16 hurtCounter) {
if (!m) { return FALSE; }
m->hurtCounter = hurtCounter;
return set_mario_action(m, action, actionArg);
}
/**
* Checks a variety of inputs for common transitions between many different
* actions. A common variant of the below function.
*/
s32 check_common_action_exits(struct MarioState *m) {
if (!m) { return FALSE; }
if (m->input & INPUT_A_PRESSED) {
return set_mario_action(m, ACT_JUMP, 0);
}
if (m->input & INPUT_OFF_FLOOR) {
return set_mario_action(m, ACT_FREEFALL, 0);
}
if (m->input & INPUT_NONZERO_ANALOG) {
return set_mario_action(m, ACT_WALKING, 0);
}
if (m->input & INPUT_ABOVE_SLIDE) {
return set_mario_action(m, ACT_BEGIN_SLIDING, 0);
}
return FALSE;
}
/**
* Checks a variety of inputs for common transitions between many different
* object holding actions. A holding variant of the above function.
*/
s32 check_common_hold_action_exits(struct MarioState *m) {
if (!m) { return FALSE; }
if (m->input & INPUT_A_PRESSED) {
return set_mario_action(m, ACT_HOLD_JUMP, 0);
}
if (m->input & INPUT_OFF_FLOOR) {
return set_mario_action(m, ACT_HOLD_FREEFALL, 0);
}
if (m->input & INPUT_NONZERO_ANALOG) {
return set_mario_action(m, ACT_HOLD_WALKING, 0);
}
if (m->input & INPUT_ABOVE_SLIDE) {
return set_mario_action(m, ACT_HOLD_BEGIN_SLIDING, 0);
}
return FALSE;
}
/**
* Transitions Mario from a submerged action to a walking action.
*/
s32 transition_submerged_to_walking(struct MarioState *m) {
if (!m) { return FALSE; }
if (m->playerIndex == 0 && m->area && m->area->camera) {
set_camera_mode(m->area->camera, m->area->camera->defMode, 1);
}
vec3s_set(m->angleVel, 0, 0, 0);
if (m->heldObj == NULL) {
return set_mario_action(m, ACT_WALKING, 0);
} else {
return set_mario_action(m, ACT_HOLD_WALKING, 0);
}
}
/**
* This is the transition function typically for entering a submerged action for a
* non-submerged action. This also applies the water surface camera preset.
*/
s32 set_water_plunge_action(struct MarioState *m) {
if (!m) { return FALSE; }
if (m->action == ACT_BUBBLED) { return FALSE; }
if (m->action == ACT_IN_CANNON) { return FALSE; }
m->forwardVel = m->forwardVel / 4.0f;
m->vel[1] = m->vel[1] / 2.0f;
m->pos[1] = m->waterLevel - 100;
m->faceAngle[2] = 0;
vec3s_set(m->angleVel, 0, 0, 0);
if (!(m->action & ACT_FLAG_DIVING)) {
m->faceAngle[0] = 0;
}
if (m->playerIndex == 0 && m->area->camera->mode != CAMERA_MODE_WATER_SURFACE) {
set_camera_mode(m->area->camera, CAMERA_MODE_WATER_SURFACE, 1);
}
return set_mario_action(m, ACT_WATER_PLUNGE, 0);
}
/**
* These are the scaling values for the x and z axis for Mario
* when he is close to unsquishing.
*/
u8 sSquishScaleOverTime[16] = { 0x46, 0x32, 0x32, 0x3C, 0x46, 0x50, 0x50, 0x3C,
0x28, 0x14, 0x14, 0x1E, 0x32, 0x3C, 0x3C, 0x28 };
/**
* Applies the squish to Mario's model via scaling.
*/
void squish_mario_model(struct MarioState *m) {
if (!m) { return; }
if (m->squishTimer == 0xFF && m->bounceSquishTimer == 0) { return; }
// If no longer squished, scale back to default.
// Also handles the Tiny Mario and Huge Mario cheats.
u8 squishTimer = (m->squishTimer > m->bounceSquishTimer) ? m->squishTimer : m->bounceSquishTimer;
if (squishTimer == 0) {
vec3f_set(m->marioObj->header.gfx.scale, 1.0f, 1.0f, 1.0f);
return;
}
// If timer is less than 16, rubber-band Mario's size scale up and down.
if (squishTimer <= 16) {
squishTimer--;
m->marioObj->header.gfx.scale[1] = 1.0f - ((sSquishScaleOverTime[15 - squishTimer] * 0.6f) / 100.0f);
m->marioObj->header.gfx.scale[0] = ((sSquishScaleOverTime[15 - squishTimer] * 0.4f) / 100.0f) + 1.0f;
m->marioObj->header.gfx.scale[2] = m->marioObj->header.gfx.scale[0];
} else {
vec3f_set(m->marioObj->header.gfx.scale, 1.4f, 0.4f, 1.4f);
}
if (m->squishTimer > 0) { m->squishTimer--; }
if (m->bounceSquishTimer > 0) { m->bounceSquishTimer--; }
}
/**
* Debug function that prints floor normal, velocity, and action information.
*/
void debug_print_speed_action_normal(struct MarioState *m) {
if (!m) { return; }
f32 steepness;
f32 floor_nY;
if (gShowDebugText) {
steepness = sqrtf(
((m->floor->normal.x * m->floor->normal.x) + (m->floor->normal.z * m->floor->normal.z)));
floor_nY = m->floor->normal.y;
print_text_fmt_int(210, 88, "ANG %d", (atan2s(floor_nY, steepness) * 180.0f) / 32768.0f);
print_text_fmt_int(210, 72, "SPD %d", m->forwardVel);
// STA short for "status," the official action name via SMS map.
print_text_fmt_int(210, 56, "STA %x", (m->action & ACT_ID_MASK));
}
}
/**
* Update the button inputs for Mario.
*/
void update_mario_button_inputs(struct MarioState *m) {
if (!m) { return; }
// don't update remote inputs
if (m->playerIndex != 0) { return; }
if (m->controller->buttonPressed & A_BUTTON) {
m->input |= INPUT_A_PRESSED;
}
if (m->controller->buttonDown & A_BUTTON) {
m->input |= INPUT_A_DOWN;
}
// Don't update for these buttons if squished.
if (m->squishTimer == 0) {
if (m->controller->buttonPressed & B_BUTTON) {
m->input |= INPUT_B_PRESSED;
}
if (m->controller->buttonDown & Z_TRIG) {
m->input |= INPUT_Z_DOWN;
}
if (m->controller->buttonPressed & Z_TRIG) {
m->input |= INPUT_Z_PRESSED;
}
}
if (m->input & INPUT_A_PRESSED) {
m->framesSinceA = 0;
} else if (m->framesSinceA < 0xFF) {
m->framesSinceA += 1;
}
if (m->input & INPUT_B_PRESSED) {
m->framesSinceB = 0;
} else if (m->framesSinceB < 0xFF) {
m->framesSinceB += 1;
}
}
/**
* Updates the joystick intended magnitude.
*/
void update_mario_joystick_inputs(struct MarioState *m) {
if (!m) { return; }
struct Controller *controller = m->controller;
f32 mag = ((controller->stickMag / 64.0f) * (controller->stickMag / 64.0f)) * 64.0f;
if (m->squishTimer == 0) {
m->intendedMag = mag / 2.0f;
} else {
m->intendedMag = mag / 8.0f;
}
// don't update remote inputs past this point
if ((sCurrPlayMode == PLAY_MODE_PAUSED) || m->playerIndex != 0) { return; }
if (m->intendedMag > 0.0f) {
if (gLakituState.mode != CAMERA_MODE_NEWCAM) {
m->intendedYaw = atan2s(-controller->stickY, controller->stickX) + m->area->camera->yaw;
} else if (get_first_person_enabled()) {
m->intendedYaw = atan2s(-controller->stickY, controller->stickX) + gLakituState.yaw;
} else {
m->intendedYaw = atan2s(-controller->stickY, controller->stickX) - gNewCamera.yaw + 0x4000;
}
m->input |= INPUT_NONZERO_ANALOG;
} else {
m->intendedYaw = m->faceAngle[1];
}
}
/**
* Resolves wall collisions, and updates a variety of inputs.
*/
void update_mario_geometry_inputs(struct MarioState *m) {
if (!m) { return; }
resetGoto:;
f32 gasLevel;
f32 ceilToFloorDist;
bool allow = true;
smlua_call_event_hooks_mario_param_ret_bool(HOOK_MARIO_OVERRIDE_GEOMETRY_INPUTS, m, &allow);
if (!allow) { return; }
f32_find_wall_collision(&m->pos[0], &m->pos[1], &m->pos[2], 60.0f, 50.0f);
f32_find_wall_collision(&m->pos[0], &m->pos[1], &m->pos[2], 30.0f, 24.0f);
m->floorHeight = find_floor(m->pos[0], m->pos[1], m->pos[2], &m->floor);
// If Mario is OOB, move his position to his graphical position (which was not updated)
// and check for the floor there.
// This can cause errant behavior when combined with astral projection,
// since the graphical position was not Mario's previous location.
if (m->floor == NULL) {
vec3f_copy(m->pos, m->marioObj->header.gfx.pos);
m->floorHeight = find_floor(m->pos[0], m->pos[1], m->pos[2], &m->floor);
}
m->ceilHeight = vec3f_mario_ceil(&m->pos[0], m->floorHeight, &m->ceil);
gasLevel = find_poison_gas_level(m->pos[0], m->pos[2]);
m->waterLevel = find_water_level(m->pos[0], m->pos[2]);
if (m->floor != NULL) {
m->floorAngle = atan2s(m->floor->normal.z, m->floor->normal.x);
m->terrainSoundAddend = mario_get_terrain_sound_addend(m);
if ((m->pos[1] > m->waterLevel - 40) && mario_floor_is_slippery(m)) {
m->input |= INPUT_ABOVE_SLIDE;
}
if ((m->floor->flags & SURFACE_FLAG_DYNAMIC)
|| (m->ceil && m->ceil->flags & SURFACE_FLAG_DYNAMIC)) {
ceilToFloorDist = m->ceilHeight - m->floorHeight;
if ((0.0f <= ceilToFloorDist) && (ceilToFloorDist <= 150.0f)) {
m->input |= INPUT_SQUISHED;
}
}
if (m->pos[1] > m->floorHeight + 100.0f) {
m->input |= INPUT_OFF_FLOOR;
}
if (m->pos[1] < (m->waterLevel - 10)) {
m->input |= INPUT_IN_WATER;
}
if (m->pos[1] < (gasLevel - 100.0f)) {
m->input |= INPUT_IN_POISON_GAS;
}
} else {
vec3f_set(m->pos, m->spawnInfo->startPos[0], m->spawnInfo->startPos[1], m->spawnInfo->startPos[2]);
m->faceAngle[1] = m->spawnInfo->startAngle[1];
struct Surface* floor = NULL;
find_floor(m->pos[0], m->pos[1], m->pos[2], &floor);
if (floor == NULL) {
level_trigger_warp(m, WARP_OP_DEATH);
} else {
goto resetGoto;
}
}
}
/**
* Handles Mario's input flags as well as a couple timers.
*/
void update_mario_inputs(struct MarioState *m) {
if (!m) { return; }
if (m->playerIndex == 0) { m->input = 0; }
u8 localIsPaused = (m->playerIndex == 0) && (sCurrPlayMode == PLAY_MODE_PAUSED || m->freeze > 0);
m->collidedObjInteractTypes = m->marioObj->collidedObjInteractTypes;
m->flags &= 0xFFFFFF;
update_mario_button_inputs(m);
update_mario_joystick_inputs(m);
// prevent any inputs when paused
if ((m->playerIndex == 0) && (sCurrPlayMode == PLAY_MODE_PAUSED || m->freeze > 0)) {
m->input = 0;
m->intendedMag = 0;
}
update_mario_geometry_inputs(m);
debug_print_speed_action_normal(m);
/* Developer stuff */
#ifdef DEVELOPMENT
if (gNetworkSystem == &gNetworkSystemSocket) {
if (m->playerIndex == 0) {
if (m->action != ACT_DEBUG_FREE_MOVE && m->controller->buttonPressed & L_TRIG && m->controller->buttonDown & Z_TRIG) {
set_mario_action(m, ACT_DEBUG_FREE_MOVE, 0);
m->marioObj->oTimer = 0;
}
}
}
#endif
/* End of developer stuff */
if (m->playerIndex == 0) {
if (!localIsPaused && (gCameraMovementFlags & CAM_MOVE_C_UP_MODE)) {
if (m->action & ACT_FLAG_ALLOW_FIRST_PERSON) {
m->input |= INPUT_FIRST_PERSON;
} else {
gCameraMovementFlags &= ~CAM_MOVE_C_UP_MODE;
}
}
if (!(m->input & (INPUT_NONZERO_ANALOG | INPUT_A_PRESSED))) {
m->input |= INPUT_ZERO_MOVEMENT;
}
if (m->marioObj->oInteractStatus
& (INT_STATUS_HOOT_GRABBED_BY_MARIO | INT_STATUS_MARIO_UNK1 | INT_STATUS_HIT_BY_SHOCKWAVE)) {
m->input |= INPUT_UNKNOWN_10;
}
if (m->heldObj != NULL) {
m->heldObj->heldByPlayerIndex = 0;
}
}
// This function is located near other unused trampoline functions,
// perhaps logically grouped here with the timers.
stub_mario_step_1(m);
if (m->wallKickTimer > 0) {
m->wallKickTimer--;
}
if (m->doubleJumpTimer > 0) {
m->doubleJumpTimer--;
}
}
/**
* Set's the camera preset for submerged action behaviors.
*/
void set_submerged_cam_preset_and_spawn_bubbles(struct MarioState *m) {
if (!m) { return; }
f32 heightBelowWater;
s16 camPreset;
if ((m->action & ACT_GROUP_MASK) == ACT_GROUP_SUBMERGED) {
heightBelowWater = (f32)(m->waterLevel - 80) - m->pos[1];
camPreset = m->area->camera->mode;
if (m->action & ACT_FLAG_METAL_WATER) {
if (m->playerIndex == 0 && camPreset != CAMERA_MODE_CLOSE) {
set_camera_mode(m->area->camera, CAMERA_MODE_CLOSE, 1);
}
} else {
if (m->playerIndex == 0 && (heightBelowWater > 800.0f) && (camPreset != CAMERA_MODE_BEHIND_MARIO)) {
set_camera_mode(m->area->camera, CAMERA_MODE_BEHIND_MARIO, 1);
}
if (m->playerIndex == 0 && (heightBelowWater < 400.0f) && (camPreset != CAMERA_MODE_WATER_SURFACE)) {
set_camera_mode(m->area->camera, CAMERA_MODE_WATER_SURFACE, 1);
}
// As long as Mario isn't drowning or at the top
// of the water with his head out, spawn bubbles.
if (!(m->action & ACT_FLAG_INTANGIBLE)) {
if ((m->pos[1] < (f32)(m->waterLevel - 160)) || (m->faceAngle[0] < -0x800)) {
set_mario_particle_flags(m, PARTICLE_BUBBLE, FALSE);
}
}
}
}
}
/**
* Both increments and decrements Mario's HP.
*/
void update_mario_health(struct MarioState *m) {
if (!m) { return; }
s32 terrainIsSnow;
if (m->health >= 0x100) {
// When already healing or hurting Mario, Mario's HP is not changed any more here.
if (((u32) m->healCounter | (u32) m->hurtCounter) == 0) {
if ((m->input & INPUT_IN_POISON_GAS) && !(m->action & ACT_FLAG_INTANGIBLE)) {
if (!(m->flags & MARIO_METAL_CAP) && !gDebugLevelSelect) {
m->health -= 4;
}
} else {
if ((m->action & ACT_FLAG_SWIMMING) && !(m->action & ACT_FLAG_INTANGIBLE)) {
terrainIsSnow = (m->area->terrainType & TERRAIN_MASK) == TERRAIN_SNOW;
// When Mario is near the water surface, recover health (unless in snow),
// when in snow terrains lose 3 health.
// If using the debug level select, do not lose any HP to water.
if ((m->pos[1] >= (m->waterLevel - 140)) && !terrainIsSnow) {
m->health += 0x1A;
} else if (!gDebugLevelSelect) {
m->health -= (terrainIsSnow ? 3 : 1);
}
}
}
}
if (m->healCounter > 0) {
m->health += 0x40;
m->healCounter--;
}
if (m->hurtCounter > 0) {
m->health -= 0x40;
m->hurtCounter--;
}
if (m->health > 0x880) {
m->health = 0x880;
}
if (m->health < 0x100) {
if (m != &gMarioStates[0]) {
// never kill remote marios
m->health = 0x100;
} else {
m->health = 0xFF;
}
}
if (m->playerIndex == 0) {
// Play a noise to alert the player when Mario is close to drowning.
if (((m->action & ACT_GROUP_MASK) == ACT_GROUP_SUBMERGED) && (m->health < 0x300)) {
play_sound(SOUND_MOVING_ALMOST_DROWNING, gGlobalSoundSource);
if (!gRumblePakTimer) {
gRumblePakTimer = 36;
if (is_rumble_finished_and_queue_empty()) {
queue_rumble_data_mario(m, 3, 30);
}
}
}
else {
gRumblePakTimer = 0;
}
}
}
}
/**
* Updates some basic info for camera usage.
*/
void update_mario_info_for_cam(struct MarioState *m) {
if (!m) { return; }
m->marioBodyState->action = m->action;
m->statusForCamera->action = m->action;
vec3s_copy(m->statusForCamera->faceAngle, m->faceAngle);
if (!(m->flags & MARIO_UNKNOWN_25)) {
vec3f_copy(m->statusForCamera->pos, m->pos);
}
}
/**
* Resets Mario's model, done every time an action is executed.
*/
void mario_reset_bodystate(struct MarioState *m) {
if (!m) { return; }
struct MarioBodyState *bodyState = m->marioBodyState;
bodyState->capState = MARIO_HAS_DEFAULT_CAP_OFF;
bodyState->eyeState = MARIO_EYES_BLINK;
bodyState->handState = MARIO_HAND_FISTS;
bodyState->modelState = 0;
bodyState->wingFlutter = FALSE;
m->flags &= ~MARIO_METAL_SHOCK;
}
/**
* Adjusts Mario's graphical height for quicksand.
*/
void sink_mario_in_quicksand(struct MarioState *m) {
if (!m) { return; }
struct Object *o = m->marioObj;
if (o->header.gfx.throwMatrix) {
(*o->header.gfx.throwMatrix)[3][1] -= m->quicksandDepth;
}
o->header.gfx.pos[1] -= m->quicksandDepth;
}
/**
* Is a binary representation of the frames to flicker Mario's cap when the timer
* is running out.
*
* Equals [1000]^5 . [100]^8 . [10]^9 . [1] in binary, which is
* 100010001000100010001001001001001001001001001010101010101010101.
*/
u64 sCapFlickerFrames = 0x4444449249255555;
/**
* Updates the cap flags mainly based on the cap timer.
*/
u32 update_and_return_cap_flags(struct MarioState *m) {
if (!m) { return 0; }
u32 flags = m->flags;
u32 action;
if (m->capTimer > 0) {
action = m->action;
if ((m->capTimer <= 60)
|| ((action != ACT_READING_AUTOMATIC_DIALOG) && (action != ACT_READING_NPC_DIALOG)
&& (action != ACT_READING_SIGN) && (action != ACT_IN_CANNON))) {
m->capTimer -= 1;
}
if (m->capTimer == 0) {
stop_cap_music();
m->flags &= ~MARIO_SPECIAL_CAPS;
if (!(m->flags & MARIO_CAPS)) {
m->flags &= ~MARIO_CAP_ON_HEAD;
}
}
if (m->capTimer == 60) {
fadeout_cap_music();
}
// This code flickers the cap through a long binary string, increasing in how
// common it flickers near the end.
if ((m->capTimer < 64) && ((1ULL << m->capTimer) & sCapFlickerFrames)) {
flags &= ~MARIO_SPECIAL_CAPS;
if (!(flags & MARIO_CAPS)) {
flags &= ~MARIO_CAP_ON_HEAD;
}
}
}
return flags;
}
/**
* Updates the Mario's cap, rendering, and hitbox.
*/
void mario_update_hitbox_and_cap_model(struct MarioState *m) {
if (!m) { return; }
struct MarioBodyState *bodyState = m->marioBodyState;
s32 flags = update_and_return_cap_flags(m);
if (flags & MARIO_VANISH_CAP) {
bodyState->modelState = MODEL_STATE_NOISE_ALPHA;
}
if (flags & MARIO_METAL_CAP) {
bodyState->modelState |= MODEL_STATE_METAL;
}
if (flags & MARIO_METAL_SHOCK) {
bodyState->modelState |= MODEL_STATE_METAL;
}
//! (Pause buffered hitstun) Since the global timer increments while paused,
// this can be paused through to give continual invisibility. This leads to
// no interaction with objects.
if ((m->invincTimer >= 3) && (gGlobalTimer & 1)) {
m->marioObj->header.gfx.node.flags |= GRAPH_RENDER_INVISIBLE;
}
if (flags & MARIO_CAP_IN_HAND) {
if (flags & MARIO_WING_CAP) {
bodyState->handState = MARIO_HAND_HOLDING_WING_CAP;
} else {
bodyState->handState = MARIO_HAND_HOLDING_CAP;
}
}
if (flags & MARIO_CAP_ON_HEAD) {
if (flags & MARIO_WING_CAP) {
bodyState->capState = MARIO_HAS_WING_CAP_ON;
} else {
bodyState->capState = MARIO_HAS_DEFAULT_CAP_ON;
}
}
// Short hitbox for crouching/crawling/etc.
if (m->action & ACT_FLAG_SHORT_HITBOX) {
m->marioObj->hitboxHeight = 100.0f;
} else {
m->marioObj->hitboxHeight = 160.0f;
}
struct NetworkPlayer* np = &gNetworkPlayers[gMarioState->playerIndex];
u8 teleportFade = (m->flags & MARIO_TELEPORTING) || (gMarioState->playerIndex != 0 && np->fadeOpacity < 32);
if (teleportFade && (m->fadeWarpOpacity != 0xFF)) {
bodyState->modelState &= ~0xFF;
bodyState->modelState |= (0x100 | m->fadeWarpOpacity);
}
}
/**
* An unused and possibly a debug function. Z + another button input
* sets Mario with a different cap.
*/
static void debug_update_mario_cap(u16 button, s32 flags, u16 capTimer, u16 capMusic) {
// This checks for Z_TRIG instead of Z_DOWN flag
// (which is also what other debug functions do),
// so likely debug behavior rather than unused behavior.
if ((gPlayer1Controller->buttonDown & Z_TRIG) && (gPlayer1Controller->buttonPressed & button)
&& !(gMarioState->flags & flags)) {
gMarioState->flags |= (flags + MARIO_CAP_ON_HEAD);
if (capTimer > gMarioState->capTimer) {
gMarioState->capTimer = capTimer;
}
play_cap_music(capMusic);
}
}
void queue_particle_rumble(void) {
if (gMarioState->particleFlags & PARTICLE_HORIZONTAL_STAR) {
queue_rumble_data_mario(gMarioState, 5, 80);
} else if (gMarioState->particleFlags & PARTICLE_VERTICAL_STAR) {
queue_rumble_data_mario(gMarioState, 5, 80);
} else if (gMarioState->particleFlags & PARTICLE_TRIANGLE) {
queue_rumble_data_mario(gMarioState, 5, 80);
}
if(gMarioState->heldObj && gMarioState->heldObj->behavior == segmented_to_virtual(smlua_override_behavior(bhvBobomb))) {
reset_rumble_timers(gMarioState);
}
}
static u8 prevent_hang(u32 hangPreventionActions[], u8* hangPreventionIndex) {
if (!hangPreventionActions) { return TRUE; }
// save the action sequence
hangPreventionActions[*hangPreventionIndex] = gMarioState->action;
*hangPreventionIndex = *hangPreventionIndex + 1;
if (*hangPreventionIndex < MAX_HANG_PREVENTION) { return FALSE; }
// complain to console
LOG_ERROR("Action loop hang prevented");
return TRUE;
}
/**
* Main function for executing Mario's behavior.
*/
s32 execute_mario_action(UNUSED struct Object *o) {
s32 inLoop = TRUE;
if (!gMarioState) { return 0; }
if (!gMarioState->marioObj) { return 0; }
if (gMarioState->playerIndex >= MAX_PLAYERS) { return 0; }
if (gMarioState->knockbackTimer > 0) {
gMarioState->knockbackTimer--;
} else if (gMarioState->knockbackTimer < 0) {
gMarioState->knockbackTimer++;
}
// hide inactive players
struct NetworkPlayer *np = &gNetworkPlayers[gMarioState->playerIndex];
if (gMarioState->playerIndex != 0) {
bool levelAreaMismatch = ((gNetworkPlayerLocal == NULL)
|| np->currCourseNum != gNetworkPlayerLocal->currCourseNum
|| np->currActNum != gNetworkPlayerLocal->currActNum
|| np->currLevelNum != gNetworkPlayerLocal->currLevelNum
|| np->currAreaIndex != gNetworkPlayerLocal->currAreaIndex);
bool fadedOut = gNetworkAreaLoaded && (levelAreaMismatch && gMarioState->wasNetworkVisible && np->fadeOpacity == 0);
bool wasNeverVisible = gNetworkAreaLoaded && !gMarioState->wasNetworkVisible;
if (!gNetworkAreaLoaded || fadedOut || wasNeverVisible) {
gMarioState->marioObj->header.gfx.node.flags |= GRAPH_RENDER_INVISIBLE;
gMarioState->marioObj->oIntangibleTimer = -1;
mario_stop_riding_and_holding(gMarioState);
// drop their held object
if (gMarioState->heldObj != NULL) {
LOG_INFO("dropping held object");
u8 tmpPlayerIndex = gMarioState->playerIndex;
gMarioState->playerIndex = 0;
mario_drop_held_object(gMarioState);
gMarioState->playerIndex = tmpPlayerIndex;
}
// no longer held by an object
if (gMarioState->heldByObj != NULL) {
LOG_INFO("dropping heldby object");
gMarioState->heldByObj = NULL;
}
// no longer riding object
if (gMarioState->riddenObj != NULL) {
LOG_INFO("dropping ridden object");
u8 tmpPlayerIndex = gMarioState->playerIndex;
gMarioState->playerIndex = 0;
mario_stop_riding_object(gMarioState);
gMarioState->playerIndex = tmpPlayerIndex;
}
return 0;
}
if (levelAreaMismatch && gMarioState->wasNetworkVisible) {
if (np->fadeOpacity <= 2) {
np->fadeOpacity = 0;
} else {
np->fadeOpacity -= 2;
}
gMarioState->fadeWarpOpacity = np->fadeOpacity << 3;
} else if (np->fadeOpacity < 32) {
np->fadeOpacity += 2;
gMarioState->fadeWarpOpacity = np->fadeOpacity << 3;
}
}
if (gMarioState->action) {
if (gMarioState->action != ACT_BUBBLED) {
gMarioState->marioObj->header.gfx.node.flags &= ~GRAPH_RENDER_INVISIBLE;
}
mario_reset_bodystate(gMarioState);
update_mario_inputs(gMarioState);
mario_handle_special_floors(gMarioState);
mario_process_interactions(gMarioState);
// HACK: mute snoring even when we skip the waking up action
if (gMarioState->isSnoring && gMarioState->action != ACT_SLEEPING) {
stop_sound(get_character(gMarioState)->soundSnoring1, gMarioState->marioObj->header.gfx.cameraToObject);
stop_sound(get_character(gMarioState)->soundSnoring2, gMarioState->marioObj->header.gfx.cameraToObject);
#ifndef VERSION_JP
stop_sound(get_character(gMarioState)->soundSnoring3, gMarioState->marioObj->header.gfx.cameraToObject);
#endif
gMarioState->isSnoring = FALSE;
}
// If Mario is OOB, stop executing actions.
if (gMarioState->floor == NULL) {
return 0;
}
// don't update mario when in a cutscene
if (gMarioState->playerIndex == 0) {
extern s16 gDialogID;
if (gMarioState->freeze > 0) { gMarioState->freeze--; }
if (gMarioState->freeze < 2 && gDialogID != -1) { gMarioState->freeze = 2; }
if (gMarioState->freeze < 2 && sCurrPlayMode == PLAY_MODE_PAUSED) { gMarioState->freeze = 2; }
}
// drop held object if someone else is holding it
if (gMarioState->playerIndex == 0 && gMarioState->heldObj != NULL) {
u8 inCutscene = ((gMarioState->action & ACT_GROUP_MASK) != ACT_GROUP_CUTSCENE);
if (!inCutscene && gMarioState->heldObj->heldByPlayerIndex != 0) {
drop_and_set_mario_action(gMarioState, ACT_IDLE, 0);
}
}
u32 hangPreventionActions[MAX_HANG_PREVENTION];
u8 hangPreventionIndex = 0;
// The function can loop through many action shifts in one frame,
// which can lead to unexpected sub-frame behavior. Could potentially hang
// if a loop of actions were found, but there has not been a situation found.
while (inLoop) {
// don't update mario when in a cutscene
/*if (gMarioState->freeze > 0 && (gMarioState->action & ACT_GROUP_MASK) != ACT_GROUP_CUTSCENE) {
break;
}*/
// this block can get stuck in an infinite loop due to unexpected circumstances arising from networked players
if (prevent_hang(hangPreventionActions, &hangPreventionIndex)) {
break;
}
switch (gMarioState->action & ACT_GROUP_MASK) {
case ACT_GROUP_STATIONARY:
inLoop = mario_execute_stationary_action(gMarioState);
break;
case ACT_GROUP_MOVING:
inLoop = mario_execute_moving_action(gMarioState);
break;
case ACT_GROUP_AIRBORNE:
inLoop = mario_execute_airborne_action(gMarioState);
break;
case ACT_GROUP_SUBMERGED:
inLoop = mario_execute_submerged_action(gMarioState);
break;
case ACT_GROUP_CUTSCENE:
inLoop = mario_execute_cutscene_action(gMarioState);
break;
case ACT_GROUP_AUTOMATIC:
inLoop = mario_execute_automatic_action(gMarioState);
break;
case ACT_GROUP_OBJECT:
inLoop = mario_execute_object_action(gMarioState);
break;
}
}
sink_mario_in_quicksand(gMarioState);
squish_mario_model(gMarioState);
set_submerged_cam_preset_and_spawn_bubbles(gMarioState);
update_mario_health(gMarioState);
update_mario_info_for_cam(gMarioState);
mario_update_hitbox_and_cap_model(gMarioState);
// Both of the wind handling portions play wind audio only in
// non-Japanese releases.
extern bool gDjuiInMainMenu;
if (gMarioState->floor && gMarioState->floor->type == SURFACE_HORIZONTAL_WIND && !gDjuiInMainMenu) {
spawn_wind_particles(0, (gMarioState->floor->force << 8));
#ifndef VERSION_JP
play_sound(SOUND_ENV_WIND2, gMarioState->marioObj->header.gfx.cameraToObject);
#endif
}
if (gMarioState->floor && gMarioState->floor->type == SURFACE_VERTICAL_WIND) {
spawn_wind_particles(1, 0);
#ifndef VERSION_JP
play_sound(SOUND_ENV_WIND2, gMarioState->marioObj->header.gfx.cameraToObject);
#endif
}
play_infinite_stairs_music();
gMarioState->marioObj->oInteractStatus = 0;
queue_particle_rumble();
// Make remote players disappear when they enter a painting
// should use same logic as in get_painting_warp_node
if (gMarioState->playerIndex != 0 && gCurrentArea->paintingWarpNodes != NULL) {
s32 paintingIndex = gMarioState->floor->type - SURFACE_PAINTING_WARP_D3;
if (paintingIndex >= PAINTING_WARP_INDEX_START && paintingIndex < PAINTING_WARP_INDEX_END) {
if (paintingIndex < PAINTING_WARP_INDEX_FA || gMarioState->pos[1] - gMarioState->floorHeight < 80.0f) {
struct WarpNode *warpNode = &gCurrentArea->paintingWarpNodes[paintingIndex];
if (warpNode->id != 0) {
set_mario_action(gMarioState, ACT_DISAPPEARED, 0);
gMarioState->marioObj->header.gfx.node.flags &= ~GRAPH_RENDER_ACTIVE;
}
}
}
}
return gMarioState->particleFlags;
}
return 0;
}
s32 force_idle_state(struct MarioState* m) {
if (!m) { return 0; }
u8 underWater = (m->pos[1] < ((f32)m->waterLevel));
return set_mario_action(m, underWater ? ACT_WATER_IDLE : ACT_IDLE, 0);
}
/**************************************************
* INITIALIZATION *
**************************************************/
void init_single_mario(struct MarioState* m) {
if (!m) { return; }
u16 playerIndex = m->playerIndex;
struct SpawnInfo* spawnInfo = &gPlayerSpawnInfos[playerIndex];
unused80339F10 = 0;
m->freeze = 0;
m->actionTimer = 0;
m->framesSinceA = 0xFF;
m->framesSinceB = 0xFF;
m->invincTimer = 0;
m->visibleToEnemies = TRUE;
if (m->cap & (SAVE_FLAG_CAP_ON_GROUND | SAVE_FLAG_CAP_ON_KLEPTO | SAVE_FLAG_CAP_ON_UKIKI | SAVE_FLAG_CAP_ON_MR_BLIZZARD)) {
m->flags = 0;
} else {
m->flags = (MARIO_CAP_ON_HEAD | MARIO_NORMAL_CAP);
}
m->forwardVel = 0.0f;
m->squishTimer = 0;
m->hurtCounter = 0;
m->healCounter = 0;
m->capTimer = 0;
m->quicksandDepth = 0.0f;
m->heldObj = NULL;
m->heldByObj = NULL;
m->riddenObj = NULL;
m->usedObj = NULL;
m->bubbleObj = NULL;
m->waterLevel = find_water_level(spawnInfo->startPos[0], spawnInfo->startPos[2]);
m->area = gCurrentArea;
m->marioObj = gMarioObjects[m->playerIndex];
if (m->marioObj == NULL) { return; }
m->marioObj->header.gfx.shadowInvisible = false;
m->marioObj->header.gfx.disableAutomaticShadowPos = false;
m->marioObj->header.gfx.animInfo.animID = -1;
vec3s_copy(m->faceAngle, spawnInfo->startAngle);
vec3s_set(m->angleVel, 0, 0, 0);
vec3s_to_vec3f(m->pos, spawnInfo->startPos);
vec3f_set(m->vel, 0, 0, 0);
if (m->marioObj != NULL) {
vec3f_set(m->marioObj->header.gfx.scale, 1.0f, 1.0f, 1.0f);
m->marioObj->header.gfx.node.flags |= GRAPH_RENDER_ACTIVE;
}
m->floorHeight = find_floor(m->pos[0], m->pos[1], m->pos[2], &m->floor);
if (m->pos[1] < m->floorHeight) {
m->pos[1] = m->floorHeight;
}
m->marioObj->header.gfx.pos[1] = m->pos[1];
m->action = (m->pos[1] <= (m->waterLevel - 100)) ? ACT_WATER_IDLE : ACT_IDLE;
update_mario_info_for_cam(m);
m->marioBodyState->punchState = 0;
m->marioBodyState->shadeR = 127;
m->marioBodyState->shadeG = 127;
m->marioBodyState->shadeB = 127;
m->marioBodyState->lightR = 255;
m->marioBodyState->lightG = 255;
m->marioBodyState->lightB = 255;
m->marioBodyState->lightingDirX = 0;
m->marioBodyState->lightingDirY = 0;
m->marioBodyState->lightingDirZ = 0;
m->marioBodyState->allowPartRotation = FALSE;
m->marioObj->oPosX = m->pos[0];
m->marioObj->oPosY = m->pos[1];
m->marioObj->oPosZ = m->pos[2];
m->marioObj->oMoveAnglePitch = m->faceAngle[0];
m->marioObj->oMoveAngleYaw = m->faceAngle[1];
m->marioObj->oMoveAngleRoll = m->faceAngle[2];
m->marioObj->oIntangibleTimer = 0;
vec3f_copy(m->marioObj->header.gfx.pos, m->pos);
vec3s_set(m->marioObj->header.gfx.angle, 0, m->faceAngle[1], 0);
// cap will never be lying on the ground in coop
/* Vec3s capPos;
if (save_file_get_cap_pos(capPos)) {
struct Object *capObject = spawn_object(m->marioObj, MODEL_MARIOS_CAP, bhvNormalCap);
capObject->oPosX = capPos[0];
capObject->oPosY = capPos[1];
capObject->oPosZ = capPos[2];
capObject->oForwardVelS32 = 0;
capObject->oMoveAngleYaw = 0;
}*/
// force all other players to be invisible by default
if (playerIndex != 0) {
m->marioObj->header.gfx.node.flags |= GRAPH_RENDER_INVISIBLE;
m->wasNetworkVisible = false;
gNetworkPlayers[playerIndex].fadeOpacity = 0;
}
// set character model
u8 modelIndex = gNetworkPlayers[playerIndex].overrideModelIndex;
if (modelIndex >= CT_MAX) { modelIndex = 0; }
m->character = &gCharacters[modelIndex];
obj_set_model(m->marioObj, m->character->modelId);
}
void init_mario(void) {
for (s32 i = 0; i < MAX_PLAYERS; i++) {
gMarioStates[i].playerIndex = i;
init_single_mario(&gMarioStates[i]);
}
}
void init_mario_single_from_save_file(struct MarioState* m, u16 index) {
if (!m) { return; }
m->playerIndex = index;
m->flags = 0;
m->action = 0;
m->spawnInfo = &gPlayerSpawnInfos[index];
m->statusForCamera = &gPlayerCameraState[index];
m->marioBodyState = &gBodyStates[index];
m->controller = &gControllers[index];
m->animation = &D_80339D10[index];
m->numCoins = 0;
m->numStars = save_file_get_total_star_count(gCurrSaveFileNum - 1, COURSE_MIN - 1, COURSE_MAX - 1);
m->numKeys = 0;
m->numLives = 4;
m->health = 0x880;
m->prevNumStarsForDialog = m->numStars;
m->unkB0 = 0xBD;
}
void init_mario_from_save_file(void) {
for (s32 i = 0; i < MAX_PLAYERS; i++) {
init_mario_single_from_save_file(&gMarioStates[i], i);
}
gHudDisplay.coins = 0;
gHudDisplay.wedges = 8;
}
void set_mario_particle_flags(struct MarioState* m, u32 flags, u8 clear) {
if (!m) { return; }
if (m->playerIndex != 0) {
return;
}
if (clear) {
m->particleFlags &= ~flags;
} else {
m->particleFlags |= flags;
}
}
void mario_update_wall(struct MarioState* m, struct WallCollisionData* wcd) {
if (!m || !wcd) { return; }
if (gLevelValues.fixCollisionBugs && gLevelValues.fixCollisionBugsPickBestWall) {
// turn face angle into a direction vector
Vec3f faceAngle;
faceAngle[0] = coss(m->faceAngle[0]) * sins(m->faceAngle[1]);
faceAngle[1] = sins(m->faceAngle[0]);
faceAngle[2] = coss(m->faceAngle[0]) * coss(m->faceAngle[1]);
vec3f_normalize(faceAngle);
// reset wall
m->wall = NULL;
for (int i = 0; i < wcd->numWalls; i++) {
if (m->wall == NULL) {
m->wall = wcd->walls[i];
continue;
}
// find the wall that is most "facing away"
Vec3f w1 = { m->wall->normal.x, m->wall->normal.y, m->wall->normal.z };
Vec3f w2 = {wcd->walls[i]->normal.x,wcd->walls[i]->normal.y, wcd->walls[i]->normal.z };
if (vec3f_dot(w1, faceAngle) > vec3f_dot(w2, faceAngle)) {
m->wall = wcd->walls[i];
}
}
} else {
m->wall = (wcd->numWalls > 0)
? wcd->walls[wcd->numWalls - 1]
: NULL;
}
if (gLevelValues.fixCollisionBugs && wcd->normalCount > 0) {
vec3f_set(m->wallNormal,
wcd->normalAddition[0] / wcd->normalCount,
wcd->normalAddition[1] / wcd->normalCount,
wcd->normalAddition[2] / wcd->normalCount);
} else if (m->wall) {
vec3f_set(m->wallNormal,
m->wall->normal.x,
m->wall->normal.y,
m->wall->normal.z);
}
}
struct MarioState *get_mario_state_from_object(struct Object *o) {
if (!o) { return NULL; }
for (s32 i = 0; i != MAX_PLAYERS; ++i) {
struct MarioState *m = &gMarioStates[i];
if (m->marioObj == o) {
return m;
}
}
return NULL;
}
| 412 | 0.926707 | 1 | 0.926707 | game-dev | MEDIA | 0.59948 | game-dev | 0.785997 | 1 | 0.785997 |
leanote/desktop-app | 32,140 | public/libs/ace/mode-lsl.js | ace.define("ace/mode/lsl_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(e,t,n){"use strict";function s(){var e=this.createKeywordMapper({"constant.language.float.lsl":"DEG_TO_RAD|PI|PI_BY_TWO|RAD_TO_DEG|SQRT2|TWO_PI","constant.language.integer.lsl":"ACTIVE|AGENT|AGENT_ALWAYS_RUN|AGENT_ATTACHMENTS|AGENT_AUTOPILOT|AGENT_AWAY|AGENT_BUSY|AGENT_BY_LEGACY_NAME|AGENT_BY_USERNAME|AGENT_CROUCHING|AGENT_FLYING|AGENT_IN_AIR|AGENT_LIST_PARCEL|AGENT_LIST_PARCEL_OWNER|AGENT_LIST_REGION|AGENT_MOUSELOOK|AGENT_ON_OBJECT|AGENT_SCRIPTED|AGENT_SITTING|AGENT_TYPING|AGENT_WALKING|ALL_SIDES|ANIM_ON|ATTACH_AVATAR_CENTER|ATTACH_BACK|ATTACH_BELLY|ATTACH_CHEST|ATTACH_CHIN|ATTACH_HEAD|ATTACH_HUD_BOTTOM|ATTACH_HUD_BOTTOM_LEFT|ATTACH_HUD_BOTTOM_RIGHT|ATTACH_HUD_CENTER_1|ATTACH_HUD_CENTER_2|ATTACH_HUD_TOP_CENTER|ATTACH_HUD_TOP_LEFT|ATTACH_HUD_TOP_RIGHT|ATTACH_LEAR|ATTACH_LEFT_PEC|ATTACH_LEYE|ATTACH_LFOOT|ATTACH_LHAND|ATTACH_LHIP|ATTACH_LLARM|ATTACH_LLLEG|ATTACH_LSHOULDER|ATTACH_LUARM|ATTACH_LULEG|ATTACH_MOUTH|ATTACH_NECK|ATTACH_NOSE|ATTACH_PELVIS|ATTACH_REAR|ATTACH_REYE|ATTACH_RFOOT|ATTACH_RHAND|ATTACH_RHIP|ATTACH_RIGHT_PEC|ATTACH_RLARM|ATTACH_RLLEG|ATTACH_RSHOULDER|ATTACH_RUARM|ATTACH_RULEG|AVOID_CHARACTERS|AVOID_DYNAMIC_OBSTACLES|AVOID_NONE|CAMERA_ACTIVE|CAMERA_BEHINDNESS_ANGLE|CAMERA_BEHINDNESS_LAG|CAMERA_DISTANCE|CAMERA_FOCUS|CAMERA_FOCUS_LAG|CAMERA_FOCUS_LOCKED|CAMERA_FOCUS_OFFSET|CAMERA_FOCUS_THRESHOLD|CAMERA_PITCH|CAMERA_POSITION|CAMERA_POSITION_LAG|CAMERA_POSITION_LOCKED|CAMERA_POSITION_THRESHOLD|CHANGED_ALLOWED_DROP|CHANGED_COLOR|CHANGED_INVENTORY|CHANGED_LINK|CHANGED_MEDIA|CHANGED_OWNER|CHANGED_REGION|CHANGED_REGION_START|CHANGED_SCALE|CHANGED_SHAPE|CHANGED_TELEPORT|CHANGED_TEXTURE|CHARACTER_ACCOUNT_FOR_SKIPPED_FRAMES|CHARACTER_AVOIDANCE_MODE|CHARACTER_CMD_JUMP|CHARACTER_CMD_SMOOTH_STOP|CHARACTER_CMD_STOP|CHARACTER_DESIRED_SPEED|CHARACTER_DESIRED_TURN_SPEED|CHARACTER_LENGTH|CHARACTER_MAX_ACCEL|CHARACTER_MAX_DECEL|CHARACTER_MAX_SPEED|CHARACTER_MAX_TURN_RADIUS|CHARACTER_ORIENTATION|CHARACTER_RADIUS|CHARACTER_STAY_WITHIN_PARCEL|CHARACTER_TYPE|CHARACTER_TYPE_A|CHARACTER_TYPE_B|CHARACTER_TYPE_C|CHARACTER_TYPE_D|CHARACTER_TYPE_NONE|CLICK_ACTION_BUY|CLICK_ACTION_NONE|CLICK_ACTION_OPEN|CLICK_ACTION_OPEN_MEDIA|CLICK_ACTION_PAY|CLICK_ACTION_PLAY|CLICK_ACTION_SIT|CLICK_ACTION_TOUCH|CONTENT_TYPE_ATOM|CONTENT_TYPE_FORM|CONTENT_TYPE_HTML|CONTENT_TYPE_JSON|CONTENT_TYPE_LLSD|CONTENT_TYPE_RSS|CONTENT_TYPE_TEXT|CONTENT_TYPE_XHTML|CONTENT_TYPE_XML|CONTROL_BACK|CONTROL_DOWN|CONTROL_FWD|CONTROL_LBUTTON|CONTROL_LEFT|CONTROL_ML_LBUTTON|CONTROL_RIGHT|CONTROL_ROT_LEFT|CONTROL_ROT_RIGHT|CONTROL_UP|DATA_BORN|DATA_NAME|DATA_ONLINE|DATA_PAYINFO|DATA_SIM_POS|DATA_SIM_RATING|DATA_SIM_STATUS|DEBUG_CHANNEL|DENSITY|ERR_GENERIC|ERR_MALFORMED_PARAMS|ERR_PARCEL_PERMISSIONS|ERR_RUNTIME_PERMISSIONS|ERR_THROTTLED|ESTATE_ACCESS_ALLOWED_AGENT_ADD|ESTATE_ACCESS_ALLOWED_AGENT_REMOVE|ESTATE_ACCESS_ALLOWED_GROUP_ADD|ESTATE_ACCESS_ALLOWED_GROUP_REMOVE|ESTATE_ACCESS_BANNED_AGENT_ADD|ESTATE_ACCESS_BANNED_AGENT_REMOVE|FALSE|FORCE_DIRECT_PATH|FRICTION|GCNP_RADIUS|GCNP_STATIC|GRAVITY_MULTIPLIER|HORIZONTAL|HTTP_BODY_MAXLENGTH|HTTP_BODY_TRUNCATED|HTTP_CUSTOM_HEADER|HTTP_METHOD|HTTP_MIMETYPE|HTTP_PRAGMA_NO_CACHE|HTTP_VERBOSE_THROTTLE|HTTP_VERIFY_CERT|INVENTORY_ALL|INVENTORY_ANIMATION|INVENTORY_BODYPART|INVENTORY_CLOTHING|INVENTORY_GESTURE|INVENTORY_LANDMARK|INVENTORY_NONE|INVENTORY_NOTECARD|INVENTORY_OBJECT|INVENTORY_SCRIPT|INVENTORY_SOUND|INVENTORY_TEXTURE|JSON_APPEND|KFM_CMD_PAUSE|KFM_CMD_PLAY|KFM_CMD_SET_MODE|KFM_CMD_STOP|KFM_COMMAND|KFM_DATA|KFM_FORWARD|KFM_LOOP|KFM_MODE|KFM_PING_PONG|KFM_REVERSE|KFM_ROTATION|KFM_TRANSLATION|LAND_LEVEL|LAND_LOWER|LAND_NOISE|LAND_RAISE|LAND_REVERT|LAND_SMOOTH|LINK_ALL_CHILDREN|LINK_ALL_OTHERS|LINK_ROOT|LINK_SET|LINK_THIS|LIST_STAT_GEOMETRIC_MEAN|LIST_STAT_MAX|LIST_STAT_MEAN|LIST_STAT_MEDIAN|LIST_STAT_MIN|LIST_STAT_NUM_COUNT|LIST_STAT_RANGE|LIST_STAT_STD_DEV|LIST_STAT_SUM|LIST_STAT_SUM_SQUARES|LOOP|MASK_BASE|MASK_EVERYONE|MASK_GROUP|MASK_NEXT|MASK_OWNER|OBJECT_ATTACHED_POINT|OBJECT_CHARACTER_TIME|OBJECT_CREATOR|OBJECT_DESC|OBJECT_GROUP|OBJECT_NAME|OBJECT_OWNER|OBJECT_PATHFINDING_TYPE|OBJECT_PHANTOM|OBJECT_PHYSICS|OBJECT_PHYSICS_COST|OBJECT_POS|OBJECT_PRIM_EQUIVALENCE|OBJECT_RENDER_WEIGHT|OBJECT_RETURN_PARCEL|OBJECT_RETURN_PARCEL_OWNER|OBJECT_RETURN_REGION|OBJECT_ROOT|OBJECT_ROT|OBJECT_RUNNING_SCRIPT_COUNT|OBJECT_SCRIPT_MEMORY|OBJECT_SCRIPT_TIME|OBJECT_SERVER_COST|OBJECT_STREAMING_COST|OBJECT_TEMP_ON_REZ|OBJECT_TOTAL_SCRIPT_COUNT|OBJECT_UNKNOWN_DETAIL|OBJECT_VELOCITY|OPT_AVATAR|OPT_CHARACTER|OPT_EXCLUSION_VOLUME|OPT_LEGACY_LINKSET|OPT_MATERIAL_VOLUME|OPT_OTHER|OPT_STATIC_OBSTACLE|OPT_WALKABLE|PARCEL_COUNT_GROUP|PARCEL_COUNT_OTHER|PARCEL_COUNT_OWNER|PARCEL_COUNT_SELECTED|PARCEL_COUNT_TEMP|PARCEL_COUNT_TOTAL|PARCEL_DETAILS_AREA|PARCEL_DETAILS_DESC|PARCEL_DETAILS_GROUP|PARCEL_DETAILS_ID|PARCEL_DETAILS_NAME|PARCEL_DETAILS_OWNER|PARCEL_DETAILS_SEE_AVATARS|PARCEL_FLAG_ALLOW_ALL_OBJECT_ENTRY|PARCEL_FLAG_ALLOW_CREATE_GROUP_OBJECTS|PARCEL_FLAG_ALLOW_CREATE_OBJECTS|PARCEL_FLAG_ALLOW_DAMAGE|PARCEL_FLAG_ALLOW_FLY|PARCEL_FLAG_ALLOW_GROUP_OBJECT_ENTRY|PARCEL_FLAG_ALLOW_GROUP_SCRIPTS|PARCEL_FLAG_ALLOW_LANDMARK|PARCEL_FLAG_ALLOW_SCRIPTS|PARCEL_FLAG_ALLOW_TERRAFORM|PARCEL_FLAG_LOCAL_SOUND_ONLY|PARCEL_FLAG_RESTRICT_PUSHOBJECT|PARCEL_FLAG_USE_ACCESS_GROUP|PARCEL_FLAG_USE_ACCESS_LIST|PARCEL_FLAG_USE_BAN_LIST|PARCEL_FLAG_USE_LAND_PASS_LIST|PARCEL_MEDIA_COMMAND_AGENT|PARCEL_MEDIA_COMMAND_AUTO_ALIGN|PARCEL_MEDIA_COMMAND_DESC|PARCEL_MEDIA_COMMAND_LOOP|PARCEL_MEDIA_COMMAND_LOOP_SET|PARCEL_MEDIA_COMMAND_PAUSE|PARCEL_MEDIA_COMMAND_PLAY|PARCEL_MEDIA_COMMAND_SIZE|PARCEL_MEDIA_COMMAND_STOP|PARCEL_MEDIA_COMMAND_TEXTURE|PARCEL_MEDIA_COMMAND_TIME|PARCEL_MEDIA_COMMAND_TYPE|PARCEL_MEDIA_COMMAND_UNLOAD|PARCEL_MEDIA_COMMAND_URL|PASSIVE|PATROL_PAUSE_AT_WAYPOINTS|PAYMENT_INFO_ON_FILE|PAYMENT_INFO_USED|PAY_DEFAULT|PAY_HIDE|PERMISSION_ATTACH|PERMISSION_CHANGE_LINKS|PERMISSION_CONTROL_CAMERA|PERMISSION_DEBIT|PERMISSION_OVERRIDE_ANIMATIONS|PERMISSION_RETURN_OBJECTS|PERMISSION_SILENT_ESTATE_MANAGEMENT|PERMISSION_TAKE_CONTROLS|PERMISSION_TELEPORT|PERMISSION_TRACK_CAMERA|PERMISSION_TRIGGER_ANIMATION|PERM_ALL|PERM_COPY|PERM_MODIFY|PERM_MOVE|PERM_TRANSFER|PING_PONG|PRIM_ALPHA_MODE|PRIM_ALPHA_MODE_BLEND|PRIM_ALPHA_MODE_EMISSIVE|PRIM_ALPHA_MODE_MASK|PRIM_ALPHA_MODE_NONE|PRIM_BUMP_BARK|PRIM_BUMP_BLOBS|PRIM_BUMP_BRICKS|PRIM_BUMP_BRIGHT|PRIM_BUMP_CHECKER|PRIM_BUMP_CONCRETE|PRIM_BUMP_DARK|PRIM_BUMP_DISKS|PRIM_BUMP_GRAVEL|PRIM_BUMP_LARGETILE|PRIM_BUMP_NONE|PRIM_BUMP_SHINY|PRIM_BUMP_SIDING|PRIM_BUMP_STONE|PRIM_BUMP_STUCCO|PRIM_BUMP_SUCTION|PRIM_BUMP_TILE|PRIM_BUMP_WEAVE|PRIM_BUMP_WOOD|PRIM_COLOR|PRIM_DESC|PRIM_FLEXIBLE|PRIM_FULLBRIGHT|PRIM_GLOW|PRIM_HOLE_CIRCLE|PRIM_HOLE_DEFAULT|PRIM_HOLE_SQUARE|PRIM_HOLE_TRIANGLE|PRIM_LINK_TARGET|PRIM_MATERIAL|PRIM_MATERIAL_FLESH|PRIM_MATERIAL_GLASS|PRIM_MATERIAL_METAL|PRIM_MATERIAL_PLASTIC|PRIM_MATERIAL_RUBBER|PRIM_MATERIAL_STONE|PRIM_MATERIAL_WOOD|PRIM_MEDIA_ALT_IMAGE_ENABLE|PRIM_MEDIA_AUTO_LOOP|PRIM_MEDIA_AUTO_PLAY|PRIM_MEDIA_AUTO_SCALE|PRIM_MEDIA_AUTO_ZOOM|PRIM_MEDIA_CONTROLS|PRIM_MEDIA_CONTROLS_MINI|PRIM_MEDIA_CONTROLS_STANDARD|PRIM_MEDIA_CURRENT_URL|PRIM_MEDIA_FIRST_CLICK_INTERACT|PRIM_MEDIA_HEIGHT_PIXELS|PRIM_MEDIA_HOME_URL|PRIM_MEDIA_MAX_HEIGHT_PIXELS|PRIM_MEDIA_MAX_URL_LENGTH|PRIM_MEDIA_MAX_WHITELIST_COUNT|PRIM_MEDIA_MAX_WHITELIST_SIZE|PRIM_MEDIA_MAX_WIDTH_PIXELS|PRIM_MEDIA_PARAM_MAX|PRIM_MEDIA_PERMS_CONTROL|PRIM_MEDIA_PERMS_INTERACT|PRIM_MEDIA_PERM_ANYONE|PRIM_MEDIA_PERM_GROUP|PRIM_MEDIA_PERM_NONE|PRIM_MEDIA_PERM_OWNER|PRIM_MEDIA_WHITELIST|PRIM_MEDIA_WHITELIST_ENABLE|PRIM_MEDIA_WIDTH_PIXELS|PRIM_NAME|PRIM_NORMAL|PRIM_OMEGA|PRIM_PHANTOM|PRIM_PHYSICS|PRIM_PHYSICS_SHAPE_CONVEX|PRIM_PHYSICS_SHAPE_NONE|PRIM_PHYSICS_SHAPE_PRIM|PRIM_PHYSICS_SHAPE_TYPE|PRIM_POINT_LIGHT|PRIM_POSITION|PRIM_POS_LOCAL|PRIM_ROTATION|PRIM_ROT_LOCAL|PRIM_SCULPT_FLAG_INVERT|PRIM_SCULPT_FLAG_MIRROR|PRIM_SCULPT_TYPE_CYLINDER|PRIM_SCULPT_TYPE_MASK|PRIM_SCULPT_TYPE_PLANE|PRIM_SCULPT_TYPE_SPHERE|PRIM_SCULPT_TYPE_TORUS|PRIM_SHINY_HIGH|PRIM_SHINY_LOW|PRIM_SHINY_MEDIUM|PRIM_SHINY_NONE|PRIM_SIZE|PRIM_SLICE|PRIM_SPECULAR|PRIM_TEMP_ON_REZ|PRIM_TEXGEN|PRIM_TEXGEN_DEFAULT|PRIM_TEXGEN_PLANAR|PRIM_TEXT|PRIM_TEXTURE|PRIM_TYPE|PRIM_TYPE_BOX|PRIM_TYPE_CYLINDER|PRIM_TYPE_PRISM|PRIM_TYPE_RING|PRIM_TYPE_SCULPT|PRIM_TYPE_SPHERE|PRIM_TYPE_TORUS|PRIM_TYPE_TUBE|PROFILE_NONE|PROFILE_SCRIPT_MEMORY|PSYS_PART_BF_DEST_COLOR|PSYS_PART_BF_ONE|PSYS_PART_BF_ONE_MINUS_DEST_COLOR|PSYS_PART_BF_ONE_MINUS_SOURCE_ALPHA|PSYS_PART_BF_ONE_MINUS_SOURCE_COLOR|PSYS_PART_BF_SOURCE_ALPHA|PSYS_PART_BF_SOURCE_COLOR|PSYS_PART_BF_ZERO|PSYS_PART_BLEND_FUNC_DEST|PSYS_PART_BLEND_FUNC_SOURCE|PSYS_PART_BOUNCE_MASK|PSYS_PART_EMISSIVE_MASK|PSYS_PART_END_ALPHA|PSYS_PART_END_COLOR|PSYS_PART_END_GLOW|PSYS_PART_END_SCALE|PSYS_PART_FLAGS|PSYS_PART_FOLLOW_SRC_MASK|PSYS_PART_FOLLOW_VELOCITY_MASK|PSYS_PART_INTERP_COLOR_MASK|PSYS_PART_INTERP_SCALE_MASK|PSYS_PART_MAX_AGE|PSYS_PART_RIBBON_MASK|PSYS_PART_START_ALPHA|PSYS_PART_START_COLOR|PSYS_PART_START_GLOW|PSYS_PART_START_SCALE|PSYS_PART_TARGET_LINEAR_MASK|PSYS_PART_TARGET_POS_MASK|PSYS_PART_WIND_MASK|PSYS_SRC_ACCEL|PSYS_SRC_ANGLE_BEGIN|PSYS_SRC_ANGLE_END|PSYS_SRC_BURST_PART_COUNT|PSYS_SRC_BURST_RADIUS|PSYS_SRC_BURST_RATE|PSYS_SRC_BURST_SPEED_MAX|PSYS_SRC_BURST_SPEED_MIN|PSYS_SRC_MAX_AGE|PSYS_SRC_OMEGA|PSYS_SRC_PATTERN|PSYS_SRC_PATTERN_ANGLE|PSYS_SRC_PATTERN_ANGLE_CONE|PSYS_SRC_PATTERN_ANGLE_CONE_EMPTY|PSYS_SRC_PATTERN_DROP|PSYS_SRC_PATTERN_EXPLODE|PSYS_SRC_TARGET_KEY|PSYS_SRC_TEXTURE|PUBLIC_CHANNEL|PURSUIT_FUZZ_FACTOR|PURSUIT_GOAL_TOLERANCE|PURSUIT_INTERCEPT|PURSUIT_OFFSET|PU_EVADE_HIDDEN|PU_EVADE_SPOTTED|PU_FAILURE_DYNAMIC_PATHFINDING_DISABLED|PU_FAILURE_INVALID_GOAL|PU_FAILURE_INVALID_START|PU_FAILURE_NO_NAVMESH|PU_FAILURE_NO_VALID_DESTINATION|PU_FAILURE_OTHER|PU_FAILURE_PARCEL_UNREACHABLE|PU_FAILURE_TARGET_GONE|PU_FAILURE_UNREACHABLE|PU_GOAL_REACHED|PU_SLOWDOWN_DISTANCE_REACHED|RCERR_CAST_TIME_EXCEEDED|RCERR_SIM_PERF_LOW|RCERR_UNKNOWN|RC_DATA_FLAGS|RC_DETECT_PHANTOM|RC_GET_LINK_NUM|RC_GET_NORMAL|RC_GET_ROOT_KEY|RC_MAX_HITS|RC_REJECT_AGENTS|RC_REJECT_LAND|RC_REJECT_NONPHYSICAL|RC_REJECT_PHYSICAL|RC_REJECT_TYPES|REGION_FLAG_ALLOW_DAMAGE|REGION_FLAG_ALLOW_DIRECT_TELEPORT|REGION_FLAG_BLOCK_FLY|REGION_FLAG_BLOCK_TERRAFORM|REGION_FLAG_DISABLE_COLLISIONS|REGION_FLAG_DISABLE_PHYSICS|REGION_FLAG_FIXED_SUN|REGION_FLAG_RESTRICT_PUSHOBJECT|REGION_FLAG_SANDBOX|REMOTE_DATA_CHANNEL|REMOTE_DATA_REPLY|REMOTE_DATA_REQUEST|REQUIRE_LINE_OF_SIGHT|RESTITUTION|REVERSE|ROTATE|SCALE|SCRIPTED|SIM_STAT_PCT_CHARS_STEPPED|SMOOTH|STATUS_BLOCK_GRAB|STATUS_BLOCK_GRAB_OBJECT|STATUS_BOUNDS_ERROR|STATUS_CAST_SHADOWS|STATUS_DIE_AT_EDGE|STATUS_INTERNAL_ERROR|STATUS_MALFORMED_PARAMS|STATUS_NOT_FOUND|STATUS_NOT_SUPPORTED|STATUS_OK|STATUS_PHANTOM|STATUS_PHYSICS|STATUS_RETURN_AT_EDGE|STATUS_ROTATE_X|STATUS_ROTATE_Y|STATUS_ROTATE_Z|STATUS_SANDBOX|STATUS_TYPE_MISMATCH|STATUS_WHITELIST_FAILED|STRING_TRIM|STRING_TRIM_HEAD|STRING_TRIM_TAIL|TOUCH_INVALID_FACE|TRAVERSAL_TYPE|TRAVERSAL_TYPE_FAST|TRAVERSAL_TYPE_NONE|TRAVERSAL_TYPE_SLOW|TRUE|TYPE_FLOAT|TYPE_INTEGER|TYPE_INVALID|TYPE_KEY|TYPE_ROTATION|TYPE_STRING|TYPE_VECTOR|VEHICLE_ANGULAR_DEFLECTION_EFFICIENCY|VEHICLE_ANGULAR_DEFLECTION_TIMESCALE|VEHICLE_ANGULAR_FRICTION_TIMESCALE|VEHICLE_ANGULAR_MOTOR_DECAY_TIMESCALE|VEHICLE_ANGULAR_MOTOR_DIRECTION|VEHICLE_ANGULAR_MOTOR_TIMESCALE|VEHICLE_BANKING_EFFICIENCY|VEHICLE_BANKING_MIX|VEHICLE_BANKING_TIMESCALE|VEHICLE_BUOYANCY|VEHICLE_FLAG_CAMERA_DECOUPLED|VEHICLE_FLAG_HOVER_GLOBAL_HEIGHT|VEHICLE_FLAG_HOVER_TERRAIN_ONLY|VEHICLE_FLAG_HOVER_UP_ONLY|VEHICLE_FLAG_HOVER_WATER_ONLY|VEHICLE_FLAG_LIMIT_MOTOR_UP|VEHICLE_FLAG_LIMIT_ROLL_ONLY|VEHICLE_FLAG_MOUSELOOK_BANK|VEHICLE_FLAG_MOUSELOOK_STEER|VEHICLE_FLAG_NO_DEFLECTION_UP|VEHICLE_HOVER_EFFICIENCY|VEHICLE_HOVER_HEIGHT|VEHICLE_HOVER_TIMESCALE|VEHICLE_LINEAR_DEFLECTION_EFFICIENCY|VEHICLE_LINEAR_DEFLECTION_TIMESCALE|VEHICLE_LINEAR_FRICTION_TIMESCALE|VEHICLE_LINEAR_MOTOR_DECAY_TIMESCALE|VEHICLE_LINEAR_MOTOR_DIRECTION|VEHICLE_LINEAR_MOTOR_OFFSET|VEHICLE_LINEAR_MOTOR_TIMESCALE|VEHICLE_REFERENCE_FRAME|VEHICLE_TYPE_AIRPLANE|VEHICLE_TYPE_BALLOON|VEHICLE_TYPE_BOAT|VEHICLE_TYPE_CAR|VEHICLE_TYPE_NONE|VEHICLE_TYPE_SLED|VEHICLE_VERTICAL_ATTRACTION_EFFICIENCY|VEHICLE_VERTICAL_ATTRACTION_TIMESCALE|VERTICAL|WANDER_PAUSE_AT_WAYPOINTS|XP_ERROR_EXPERIENCES_DISABLED|XP_ERROR_EXPERIENCE_DISABLED|XP_ERROR_EXPERIENCE_SUSPENDED|XP_ERROR_INVALID_EXPERIENCE|XP_ERROR_INVALID_PARAMETERS|XP_ERROR_KEY_NOT_FOUND|XP_ERROR_MATURITY_EXCEEDED|XP_ERROR_NONE|XP_ERROR_NOT_FOUND|XP_ERROR_NOT_PERMITTED|XP_ERROR_NO_EXPERIENCE|XP_ERROR_QUOTA_EXCEEDED|XP_ERROR_RETRY_UPDATE|XP_ERROR_STORAGE_EXCEPTION|XP_ERROR_STORE_DISABLED|XP_ERROR_THROTTLED|XP_ERROR_UNKNOWN_ERROR","constant.language.integer.boolean.lsl":"FALSE|TRUE","constant.language.quaternion.lsl":"ZERO_ROTATION","constant.language.string.lsl":"EOF|JSON_ARRAY|JSON_DELETE|JSON_FALSE|JSON_INVALID|JSON_NULL|JSON_NUMBER|JSON_OBJECT|JSON_STRING|JSON_TRUE|NULL_KEY|TEXTURE_BLANK|TEXTURE_DEFAULT|TEXTURE_MEDIA|TEXTURE_PLYWOOD|TEXTURE_TRANSPARENT|URL_REQUEST_DENIED|URL_REQUEST_GRANTED","constant.language.vector.lsl":"TOUCH_INVALID_TEXCOORD|TOUCH_INVALID_VECTOR|ZERO_VECTOR","invalid.broken.lsl":"LAND_LARGE_BRUSH|LAND_MEDIUM_BRUSH|LAND_SMALL_BRUSH","invalid.deprecated.lsl":"ATTACH_LPEC|ATTACH_RPEC|DATA_RATING|OBJECT_ATTACHMENT_GEOMETRY_BYTES|OBJECT_ATTACHMENT_SURFACE_AREA|PRIM_CAST_SHADOWS|PRIM_MATERIAL_LIGHT|PRIM_TYPE_LEGACY|PSYS_SRC_INNERANGLE|PSYS_SRC_OUTERANGLE|VEHICLE_FLAG_NO_FLY_UP|llClearExperiencePermissions|llCloud|llGetExperienceList|llMakeExplosion|llMakeFire|llMakeFountain|llMakeSmoke|llRemoteDataSetRegion|llSound|llSoundPreload|llXorBase64Strings|llXorBase64StringsCorrect","invalid.illegal.lsl":"event","invalid.unimplemented.lsl":"CHARACTER_MAX_ANGULAR_ACCEL|CHARACTER_MAX_ANGULAR_SPEED|CHARACTER_TURN_SPEED_MULTIPLIER|PERMISSION_CHANGE_JOINTS|PERMISSION_CHANGE_PERMISSIONS|PERMISSION_RELEASE_OWNERSHIP|PERMISSION_REMAP_CONTROLS|PRIM_PHYSICS_MATERIAL|PSYS_SRC_OBJ_REL_MASK|llCollisionSprite|llPointAt|llRefreshPrimURL|llReleaseCamera|llRemoteLoadScript|llSetPrimURL|llStopPointAt|llTakeCamera","reserved.godmode.lsl":"llGodLikeRezObject|llSetInventoryPermMask|llSetObjectPermMask","reserved.log.lsl":"print","keyword.control.lsl":"do|else|for|if|jump|return|while","storage.type.lsl":"float|integer|key|list|quaternion|rotation|string|vector","support.function.lsl":"llAbs|llAcos|llAddToLandBanList|llAddToLandPassList|llAdjustSoundVolume|llAgentInExperience|llAllowInventoryDrop|llAngleBetween|llApplyImpulse|llApplyRotationalImpulse|llAsin|llAtan2|llAttachToAvatar|llAttachToAvatarTemp|llAvatarOnLinkSitTarget|llAvatarOnSitTarget|llAxes2Rot|llAxisAngle2Rot|llBase64ToInteger|llBase64ToString|llBreakAllLinks|llBreakLink|llCSV2List|llCastRay|llCeil|llClearCameraParams|llClearLinkMedia|llClearPrimMedia|llCloseRemoteDataChannel|llCollisionFilter|llCollisionSound|llCos|llCreateCharacter|llCreateKeyValue|llCreateLink|llDataSizeKeyValue|llDeleteCharacter|llDeleteKeyValue|llDeleteSubList|llDeleteSubString|llDetachFromAvatar|llDetectedGrab|llDetectedGroup|llDetectedKey|llDetectedLinkNumber|llDetectedName|llDetectedOwner|llDetectedPos|llDetectedRot|llDetectedTouchBinormal|llDetectedTouchFace|llDetectedTouchNormal|llDetectedTouchPos|llDetectedTouchST|llDetectedTouchUV|llDetectedType|llDetectedVel|llDialog|llDie|llDumpList2String|llEdgeOfWorld|llEjectFromLand|llEmail|llEscapeURL|llEuler2Rot|llEvade|llExecCharacterCmd|llFabs|llFleeFrom|llFloor|llForceMouselook|llFrand|llGenerateKey|llGetAccel|llGetAgentInfo|llGetAgentLanguage|llGetAgentList|llGetAgentSize|llGetAlpha|llGetAndResetTime|llGetAnimation|llGetAnimationList|llGetAnimationOverride|llGetAttached|llGetBoundingBox|llGetCameraPos|llGetCameraRot|llGetCenterOfMass|llGetClosestNavPoint|llGetColor|llGetCreator|llGetDate|llGetDisplayName|llGetEnergy|llGetEnv|llGetExperienceDetails|llGetExperienceErrorMessage|llGetForce|llGetFreeMemory|llGetFreeURLs|llGetGMTclock|llGetGeometricCenter|llGetHTTPHeader|llGetInventoryCreator|llGetInventoryKey|llGetInventoryName|llGetInventoryNumber|llGetInventoryPermMask|llGetInventoryType|llGetKey|llGetLandOwnerAt|llGetLinkKey|llGetLinkMedia|llGetLinkName|llGetLinkNumber|llGetLinkNumberOfSides|llGetLinkPrimitiveParams|llGetListEntryType|llGetListLength|llGetLocalPos|llGetLocalRot|llGetMass|llGetMassMKS|llGetMaxScaleFactor|llGetMemoryLimit|llGetMinScaleFactor|llGetNextEmail|llGetNotecardLine|llGetNumberOfNotecardLines|llGetNumberOfPrims|llGetNumberOfSides|llGetObjectDesc|llGetObjectDetails|llGetObjectMass|llGetObjectName|llGetObjectPermMask|llGetObjectPrimCount|llGetOmega|llGetOwner|llGetOwnerKey|llGetParcelDetails|llGetParcelFlags|llGetParcelMaxPrims|llGetParcelMusicURL|llGetParcelPrimCount|llGetParcelPrimOwners|llGetPermissions|llGetPermissionsKey|llGetPhysicsMaterial|llGetPos|llGetPrimMediaParams|llGetPrimitiveParams|llGetRegionAgentCount|llGetRegionCorner|llGetRegionFPS|llGetRegionFlags|llGetRegionName|llGetRegionTimeDilation|llGetRootPosition|llGetRootRotation|llGetRot|llGetSPMaxMemory|llGetScale|llGetScriptName|llGetScriptState|llGetSimStats|llGetSimulatorHostname|llGetStartParameter|llGetStaticPath|llGetStatus|llGetSubString|llGetSunDirection|llGetTexture|llGetTextureOffset|llGetTextureRot|llGetTextureScale|llGetTime|llGetTimeOfDay|llGetTimestamp|llGetTorque|llGetUnixTime|llGetUsedMemory|llGetUsername|llGetVel|llGetWallclock|llGiveInventory|llGiveInventoryList|llGiveMoney|llGround|llGroundContour|llGroundNormal|llGroundRepel|llGroundSlope|llHTTPRequest|llHTTPResponse|llInsertString|llInstantMessage|llIntegerToBase64|llJson2List|llJsonGetValue|llJsonSetValue|llJsonValueType|llKey2Name|llKeyCountKeyValue|llKeysKeyValue|llLinkParticleSystem|llLinkSitTarget|llList2CSV|llList2Float|llList2Integer|llList2Json|llList2Key|llList2List|llList2ListStrided|llList2Rot|llList2String|llList2Vector|llListFindList|llListInsertList|llListRandomize|llListReplaceList|llListSort|llListStatistics|llListen|llListenControl|llListenRemove|llLoadURL|llLog|llLog10|llLookAt|llLoopSound|llLoopSoundMaster|llLoopSoundSlave|llMD5String|llManageEstateAccess|llMapDestination|llMessageLinked|llMinEventDelay|llModPow|llModifyLand|llMoveToTarget|llNavigateTo|llOffsetTexture|llOpenRemoteDataChannel|llOverMyLand|llOwnerSay|llParcelMediaCommandList|llParcelMediaQuery|llParseString2List|llParseStringKeepNulls|llParticleSystem|llPassCollisions|llPassTouches|llPatrolPoints|llPlaySound|llPlaySoundSlave|llPow|llPreloadSound|llPursue|llPushObject|llReadKeyValue|llRegionSay|llRegionSayTo|llReleaseControls|llReleaseURL|llRemoteDataReply|llRemoteLoadScriptPin|llRemoveFromLandBanList|llRemoveFromLandPassList|llRemoveInventory|llRemoveVehicleFlags|llRequestAgentData|llRequestDisplayName|llRequestExperiencePermissions|llRequestInventoryData|llRequestPermissions|llRequestSecureURL|llRequestSimulatorData|llRequestURL|llRequestUsername|llResetAnimationOverride|llResetLandBanList|llResetLandPassList|llResetOtherScript|llResetScript|llResetTime|llReturnObjectsByID|llReturnObjectsByOwner|llRezAtRoot|llRezObject|llRot2Angle|llRot2Axis|llRot2Euler|llRot2Fwd|llRot2Left|llRot2Up|llRotBetween|llRotLookAt|llRotTarget|llRotTargetRemove|llRotateTexture|llRound|llSHA1String|llSameGroup|llSay|llScaleByFactor|llScaleTexture|llScriptDanger|llScriptProfiler|llSendRemoteData|llSensor|llSensorRemove|llSensorRepeat|llSetAlpha|llSetAngularVelocity|llSetAnimationOverride|llSetBuoyancy|llSetCameraAtOffset|llSetCameraEyeOffset|llSetCameraParams|llSetClickAction|llSetColor|llSetContentType|llSetDamage|llSetForce|llSetForceAndTorque|llSetHoverHeight|llSetKeyframedMotion|llSetLinkAlpha|llSetLinkCamera|llSetLinkColor|llSetLinkMedia|llSetLinkPrimitiveParams|llSetLinkPrimitiveParamsFast|llSetLinkTexture|llSetLinkTextureAnim|llSetLocalRot|llSetMemoryLimit|llSetObjectDesc|llSetObjectName|llSetParcelMusicURL|llSetPayPrice|llSetPhysicsMaterial|llSetPos|llSetPrimMediaParams|llSetPrimitiveParams|llSetRegionPos|llSetRemoteScriptAccessPin|llSetRot|llSetScale|llSetScriptState|llSetSitText|llSetSoundQueueing|llSetSoundRadius|llSetStatus|llSetText|llSetTexture|llSetTextureAnim|llSetTimerEvent|llSetTorque|llSetTouchText|llSetVehicleFlags|llSetVehicleFloatParam|llSetVehicleRotationParam|llSetVehicleType|llSetVehicleVectorParam|llSetVelocity|llShout|llSin|llSitTarget|llSleep|llSqrt|llStartAnimation|llStopAnimation|llStopHover|llStopLookAt|llStopMoveToTarget|llStopSound|llStringLength|llStringToBase64|llStringTrim|llSubStringIndex|llTakeControls|llTan|llTarget|llTargetOmega|llTargetRemove|llTeleportAgent|llTeleportAgentGlobalCoords|llTeleportAgentHome|llTextBox|llToLower|llToUpper|llTransferLindenDollars|llTriggerSound|llTriggerSoundLimited|llUnSit|llUnescapeURL|llUpdateCharacter|llUpdateKeyValue|llVecDist|llVecMag|llVecNorm|llVolumeDetect|llWanderWithin|llWater|llWhisper|llWind|llXorBase64","support.function.event.lsl":"at_rot_target|at_target|attach|changed|collision|collision_end|collision_start|control|dataserver|email|experience_permissions|experience_permissions_denied|http_request|http_response|land_collision|land_collision_end|land_collision_start|link_message|listen|money|moving_end|moving_start|no_sensor|not_at_rot_target|not_at_target|object_rez|on_rez|path_update|remote_data|run_time_permissions|sensor|state_entry|state_exit|timer|touch|touch_end|touch_start|transaction_result"},"identifier");this.$rules={start:[{token:"comment.line.double-slash.lsl",regex:"\\/\\/.*$"},{token:"comment.block.begin.lsl",regex:"\\/\\*",next:"comment"},{token:"string.quoted.double.lsl",start:'"',end:'"',next:[{token:"constant.character.escape.lsl",regex:/\\[tn"\\]/}]},{token:"constant.numeric.lsl",regex:"(0[xX][0-9a-fA-F]+|[+-]?[0-9]+(?:(?:\\.[0-9]*)?(?:[eE][+-]?[0-9]+)?)?)\\b"},{token:"entity.name.state.lsl",regex:"\\b((state)\\s+[A-Za-z_]\\w*|default)\\b"},{token:e,regex:"\\b[a-zA-Z_][a-zA-Z0-9_]*\\b"},{token:"support.function.user-defined.lsl",regex:/\b([a-zA-Z_]\w*)(?=\(.*?\))/},{token:"keyword.operator.lsl",regex:"\\+\\+|\\-\\-|<<|>>|&&?|\\|\\|?|\\^|~|[!%<>=*+\\-\\/]=?"},{token:"invalid.illegal.keyword.operator.lsl",regex:":=?"},{token:"punctuation.operator.lsl",regex:"\\,|\\;"},{token:"paren.lparen.lsl",regex:"[\\[\\(\\{]"},{token:"paren.rparen.lsl",regex:"[\\]\\)\\}]"},{token:"text.lsl",regex:"\\s+"}],comment:[{token:"comment.block.end.lsl",regex:"\\*\\/",next:"start"},{token:"comment.block.lsl",regex:".+"}]},this.normalizeRules()}var r=e("../lib/oop"),i=e("./text_highlight_rules").TextHighlightRules;r.inherits(s,i),t.LSLHighlightRules=s}),ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(e,t,n){"use strict";var r=e("../range").Range,i=function(){};(function(){this.checkOutdent=function(e,t){return/^\s+$/.test(e)?/^\s*\}/.test(t):!1},this.autoOutdent=function(e,t){var n=e.getLine(t),i=n.match(/^(\s*\})/);if(!i)return 0;var s=i[1].length,o=e.findMatchingBracket({row:t,column:s});if(!o||o.row==t)return 0;var u=this.$getIndent(e.getLine(o.row));e.replace(new r(t,0,t,s-1),u)},this.$getIndent=function(e){return e.match(/^\s*/)[0]}}).call(i.prototype),t.MatchingBraceOutdent=i}),ace.define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"],function(e,t,n){"use strict";var r=e("../../lib/oop"),i=e("../behaviour").Behaviour,s=e("../../token_iterator").TokenIterator,o=e("../../lib/lang"),u=["text","paren.rparen","punctuation.operator"],a=["text","paren.rparen","punctuation.operator","comment"],f,l={},c=function(e){var t=-1;e.multiSelect&&(t=e.selection.id,l.rangeCount!=e.multiSelect.rangeCount&&(l={rangeCount:e.multiSelect.rangeCount}));if(l[t])return f=l[t];f=l[t]={autoInsertedBrackets:0,autoInsertedRow:-1,autoInsertedLineEnd:"",maybeInsertedBrackets:0,maybeInsertedRow:-1,maybeInsertedLineStart:"",maybeInsertedLineEnd:""}},h=function(){this.add("braces","insertion",function(e,t,n,r,i){var s=n.getCursorPosition(),u=r.doc.getLine(s.row);if(i=="{"){c(n);var a=n.getSelectionRange(),l=r.doc.getTextRange(a);if(l!==""&&l!=="{"&&n.getWrapBehavioursEnabled())return{text:"{"+l+"}",selection:!1};if(h.isSaneInsertion(n,r))return/[\]\}\)]/.test(u[s.column])||n.inMultiSelectMode?(h.recordAutoInsert(n,r,"}"),{text:"{}",selection:[1,1]}):(h.recordMaybeInsert(n,r,"{"),{text:"{",selection:[1,1]})}else if(i=="}"){c(n);var p=u.substring(s.column,s.column+1);if(p=="}"){var d=r.$findOpeningBracket("}",{column:s.column+1,row:s.row});if(d!==null&&h.isAutoInsertedClosing(s,u,i))return h.popAutoInsertedClosing(),{text:"",selection:[1,1]}}}else{if(i=="\n"||i=="\r\n"){c(n);var v="";h.isMaybeInsertedClosing(s,u)&&(v=o.stringRepeat("}",f.maybeInsertedBrackets),h.clearMaybeInsertedClosing());var p=u.substring(s.column,s.column+1);if(p==="}"){var m=r.findMatchingBracket({row:s.row,column:s.column+1},"}");if(!m)return null;var g=this.$getIndent(r.getLine(m.row))}else{if(!v){h.clearMaybeInsertedClosing();return}var g=this.$getIndent(u)}var y=g+r.getTabString();return{text:"\n"+y+"\n"+g+v,selection:[1,y.length,1,y.length]}}h.clearMaybeInsertedClosing()}}),this.add("braces","deletion",function(e,t,n,r,i){var s=r.doc.getTextRange(i);if(!i.isMultiLine()&&s=="{"){c(n);var o=r.doc.getLine(i.start.row),u=o.substring(i.end.column,i.end.column+1);if(u=="}")return i.end.column++,i;f.maybeInsertedBrackets--}}),this.add("parens","insertion",function(e,t,n,r,i){if(i=="("){c(n);var s=n.getSelectionRange(),o=r.doc.getTextRange(s);if(o!==""&&n.getWrapBehavioursEnabled())return{text:"("+o+")",selection:!1};if(h.isSaneInsertion(n,r))return h.recordAutoInsert(n,r,")"),{text:"()",selection:[1,1]}}else if(i==")"){c(n);var u=n.getCursorPosition(),a=r.doc.getLine(u.row),f=a.substring(u.column,u.column+1);if(f==")"){var l=r.$findOpeningBracket(")",{column:u.column+1,row:u.row});if(l!==null&&h.isAutoInsertedClosing(u,a,i))return h.popAutoInsertedClosing(),{text:"",selection:[1,1]}}}}),this.add("parens","deletion",function(e,t,n,r,i){var s=r.doc.getTextRange(i);if(!i.isMultiLine()&&s=="("){c(n);var o=r.doc.getLine(i.start.row),u=o.substring(i.start.column+1,i.start.column+2);if(u==")")return i.end.column++,i}}),this.add("brackets","insertion",function(e,t,n,r,i){if(i=="["){c(n);var s=n.getSelectionRange(),o=r.doc.getTextRange(s);if(o!==""&&n.getWrapBehavioursEnabled())return{text:"["+o+"]",selection:!1};if(h.isSaneInsertion(n,r))return h.recordAutoInsert(n,r,"]"),{text:"[]",selection:[1,1]}}else if(i=="]"){c(n);var u=n.getCursorPosition(),a=r.doc.getLine(u.row),f=a.substring(u.column,u.column+1);if(f=="]"){var l=r.$findOpeningBracket("]",{column:u.column+1,row:u.row});if(l!==null&&h.isAutoInsertedClosing(u,a,i))return h.popAutoInsertedClosing(),{text:"",selection:[1,1]}}}}),this.add("brackets","deletion",function(e,t,n,r,i){var s=r.doc.getTextRange(i);if(!i.isMultiLine()&&s=="["){c(n);var o=r.doc.getLine(i.start.row),u=o.substring(i.start.column+1,i.start.column+2);if(u=="]")return i.end.column++,i}}),this.add("string_dquotes","insertion",function(e,t,n,r,i){if(i=='"'||i=="'"){c(n);var s=i,o=n.getSelectionRange(),u=r.doc.getTextRange(o);if(u!==""&&u!=="'"&&u!='"'&&n.getWrapBehavioursEnabled())return{text:s+u+s,selection:!1};var a=n.getCursorPosition(),f=r.doc.getLine(a.row),l=f.substring(a.column-1,a.column);if(l=="\\")return null;var p=r.getTokens(o.start.row),d=0,v,m=-1;for(var g=0;g<p.length;g++){v=p[g],v.type=="string"?m=-1:m<0&&(m=v.value.indexOf(s));if(v.value.length+d>o.start.column)break;d+=p[g].value.length}if(!v||m<0&&v.type!=="comment"&&(v.type!=="string"||o.start.column!==v.value.length+d-1&&v.value.lastIndexOf(s)===v.value.length-1)){if(!h.isSaneInsertion(n,r))return;return{text:s+s,selection:[1,1]}}if(v&&v.type==="string"){var y=f.substring(a.column,a.column+1);if(y==s)return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(e,t,n,r,i){var s=r.doc.getTextRange(i);if(!i.isMultiLine()&&(s=='"'||s=="'")){c(n);var o=r.doc.getLine(i.start.row),u=o.substring(i.start.column+1,i.start.column+2);if(u==s)return i.end.column++,i}})};h.isSaneInsertion=function(e,t){var n=e.getCursorPosition(),r=new s(t,n.row,n.column);if(!this.$matchTokenType(r.getCurrentToken()||"text",u)){var i=new s(t,n.row,n.column+1);if(!this.$matchTokenType(i.getCurrentToken()||"text",u))return!1}return r.stepForward(),r.getCurrentTokenRow()!==n.row||this.$matchTokenType(r.getCurrentToken()||"text",a)},h.$matchTokenType=function(e,t){return t.indexOf(e.type||e)>-1},h.recordAutoInsert=function(e,t,n){var r=e.getCursorPosition(),i=t.doc.getLine(r.row);this.isAutoInsertedClosing(r,i,f.autoInsertedLineEnd[0])||(f.autoInsertedBrackets=0),f.autoInsertedRow=r.row,f.autoInsertedLineEnd=n+i.substr(r.column),f.autoInsertedBrackets++},h.recordMaybeInsert=function(e,t,n){var r=e.getCursorPosition(),i=t.doc.getLine(r.row);this.isMaybeInsertedClosing(r,i)||(f.maybeInsertedBrackets=0),f.maybeInsertedRow=r.row,f.maybeInsertedLineStart=i.substr(0,r.column)+n,f.maybeInsertedLineEnd=i.substr(r.column),f.maybeInsertedBrackets++},h.isAutoInsertedClosing=function(e,t,n){return f.autoInsertedBrackets>0&&e.row===f.autoInsertedRow&&n===f.autoInsertedLineEnd[0]&&t.substr(e.column)===f.autoInsertedLineEnd},h.isMaybeInsertedClosing=function(e,t){return f.maybeInsertedBrackets>0&&e.row===f.maybeInsertedRow&&t.substr(e.column)===f.maybeInsertedLineEnd&&t.substr(0,e.column)==f.maybeInsertedLineStart},h.popAutoInsertedClosing=function(){f.autoInsertedLineEnd=f.autoInsertedLineEnd.substr(1),f.autoInsertedBrackets--},h.clearMaybeInsertedClosing=function(){f&&(f.maybeInsertedBrackets=0,f.maybeInsertedRow=-1)},r.inherits(h,i),t.CstyleBehaviour=h}),ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(e,t,n){"use strict";var r=e("../../lib/oop"),i=e("../../range").Range,s=e("./fold_mode").FoldMode,o=t.FoldMode=function(e){e&&(this.foldingStartMarker=new RegExp(this.foldingStartMarker.source.replace(/\|[^|]*?$/,"|"+e.start)),this.foldingStopMarker=new RegExp(this.foldingStopMarker.source.replace(/\|[^|]*?$/,"|"+e.end)))};r.inherits(o,s),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(e,t,n,r){var i=e.getLine(n),s=i.match(this.foldingStartMarker);if(s){var o=s.index;if(s[1])return this.openingBracketBlock(e,s[1],n,o);var u=e.getCommentFoldRange(n,o+s[0].length,1);return u&&!u.isMultiLine()&&(r?u=this.getSectionRange(e,n):t!="all"&&(u=null)),u}if(t==="markbegin")return;var s=i.match(this.foldingStopMarker);if(s){var o=s.index+s[0].length;return s[1]?this.closingBracketBlock(e,s[1],n,o):e.getCommentFoldRange(n,o,-1)}},this.getSectionRange=function(e,t){var n=e.getLine(t),r=n.search(/\S/),s=t,o=n.length;t+=1;var u=t,a=e.getLength();while(++t<a){n=e.getLine(t);var f=n.search(/\S/);if(f===-1)continue;if(r>f)break;var l=this.getFoldWidgetRange(e,"all",t);if(l){if(l.start.row<=s)break;if(l.isMultiLine())t=l.end.row;else if(r==f)break}u=t}return new i(s,o,u,e.getLine(u).length)}}.call(o.prototype)}),ace.define("ace/mode/lsl",["require","exports","module","ace/mode/lsl_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/mode/text","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle","ace/lib/oop"],function(e,t,n){"use strict";var r=e("./lsl_highlight_rules").LSLHighlightRules,i=e("./matching_brace_outdent").MatchingBraceOutdent,s=e("../range").Range,o=e("./text").Mode,u=e("./behaviour/cstyle").CstyleBehaviour,a=e("./folding/cstyle").FoldMode,f=e("../lib/oop"),l=function(){this.HighlightRules=r,this.$outdent=new i,this.$behaviour=new u,this.foldingRules=new a};f.inherits(l,o),function(){this.lineCommentStart=["//"],this.blockComment={start:"/*",end:"*/"},this.getNextLineIndent=function(e,t,n){var r=this.$getIndent(t),i=this.getTokenizer().getLineTokens(t,e),s=i.tokens,o=i.state;if(s.length&&s[s.length-1].type==="comment.block.lsl")return r;if(e==="start"){var u=t.match(/^.*[\{\(\[]\s*$/);u&&(r+=n)}return r},this.checkOutdent=function(e,t,n){return this.$outdent.checkOutdent(t,n)},this.autoOutdent=function(e,t,n){this.$outdent.autoOutdent(t,n)},this.$id="ace/mode/lsl"}.call(l.prototype),t.Mode=l}) | 412 | 0.916391 | 1 | 0.916391 | game-dev | MEDIA | 0.848894 | game-dev | 0.539479 | 1 | 0.539479 |
benjames-171/defold-games | 1,094 | Crystal Caverns 2/game/enemy/eyestalk.script | local data = require "main.data"
local SHOTFREQ = 3
function init(self)
self.time = math.random (0, (SHOTFREQ * 100) / 100)
local pos = data.world2tile(go.get_position())
local t = tilemap.get_tile("/level#tilemap", "world", pos.x, pos.y+1)
if t > 0 then sprite.set_vflip("#sprite", true) end
end
function update(self, dt)
local pos = go.get_position()
if data.onscreen(pos, 0) then
self.time = self.time + dt
if self.time > SHOTFREQ then
local cast = physics.raycast(pos, data.playerpos, {hash("world")})
if cast == nil then
self.time = 0
local move = data.playerpos - pos
move = vmath.normalize(move)
factory.create("#bullet-factory", pos, nil, {move = move})
if pos.x > data.playerpos.x then sprite.set_hflip("#sprite", false)
else sprite.set_hflip("#sprite", true)
end
end
end
end
end
function on_message(self, message_id, message, sender)
if message_id == hash("collision_response") then
if message.other_group == hash("boom") then
msg.post("/common/effect", "explode", {pos = go.get_position()})
go.delete()
end
end
end
| 412 | 0.61965 | 1 | 0.61965 | game-dev | MEDIA | 0.966552 | game-dev | 0.815891 | 1 | 0.815891 |
turkraft/springfilter | 1,259 | mongo/src/main/java/com/turkraft/springfilter/transformer/processor/AndOperationJsonNodeProcessor.java | package com.turkraft.springfilter.transformer.processor;
import com.fasterxml.jackson.databind.JsonNode;
import com.turkraft.springfilter.helper.JsonNodeHelper;
import com.turkraft.springfilter.language.AndOperator;
import com.turkraft.springfilter.parser.node.InfixOperationNode;
import com.turkraft.springfilter.transformer.FilterJsonNodeTransformer;
import org.springframework.stereotype.Component;
@Component
public class AndOperationJsonNodeProcessor extends InfixOperationJsonNodeProcessor {
public AndOperationJsonNodeProcessor(JsonNodeHelper jsonNodeHelper) {
super(jsonNodeHelper);
}
@Override
public Class<FilterJsonNodeTransformer> getTransformerType() {
return FilterJsonNodeTransformer.class;
}
@Override
public Class<AndOperator> getDefinitionType() {
return AndOperator.class;
}
@Override
public String getMongoOperator() {
return "$and";
}
@Override
public JsonNode process(FilterJsonNodeTransformer transformer, InfixOperationNode source) {
transformer.registerTargetType(source, Boolean.class);
transformer.registerTargetType(source.getLeft(), Boolean.class);
transformer.registerTargetType(source.getRight(), Boolean.class);
return super.process(transformer, source);
}
}
| 412 | 0.773097 | 1 | 0.773097 | game-dev | MEDIA | 0.267898 | game-dev | 0.721637 | 1 | 0.721637 |
mikrima/UnityAccessibilityPlugin | 1,507 | Assets/UAP/Examples/Match 3 Game Example/Scripts/mainmenu.cs | using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class mainmenu : MonoBehaviour
{
public Dropdown m_DifficultyDropdown = null;
//////////////////////////////////////////////////////////////////////////
void Start()
{
gameplay.DifficultyLevel = PlayerPrefs.GetInt("Difficulty", 0);
m_DifficultyDropdown.value = gameplay.DifficultyLevel;
}
//////////////////////////////////////////////////////////////////////////
public void OnInstructionsButtonPressed()
{
if (UAP_AccessibilityManager.IsEnabled())
Instantiate(Resources.Load("Instructions"));
else
Instantiate(Resources.Load("Instructions Sighted"));
DestroyImmediate(gameObject);
}
//////////////////////////////////////////////////////////////////////////
public void OnQuitButtonPressed()
{
UAP_AccessibilityManager.Say("Goodbye");
Application.Quit();
}
//////////////////////////////////////////////////////////////////////////
public void OnPlayButtonPressed()
{
gameplay.DifficultyLevel = m_DifficultyDropdown.value;
PlayerPrefs.SetInt("Difficulty", gameplay.DifficultyLevel);
PlayerPrefs.Save();
Instantiate(Resources.Load("Match3"));
DestroyImmediate(gameObject);
}
//////////////////////////////////////////////////////////////////////////
public void OnAccessibilityButtonPressed()
{
Instantiate(Resources.Load("Accessibility Settings"));
}
//////////////////////////////////////////////////////////////////////////
}
| 412 | 0.590038 | 1 | 0.590038 | game-dev | MEDIA | 0.965639 | game-dev | 0.739295 | 1 | 0.739295 |
anyproto/anytype-kotlin | 1,040 | presentation/src/test/java/com/anytypeio/anytype/presentation/home/UserPermissionProviderStub.kt | package com.anytypeio.anytype.presentation.home
import com.anytypeio.anytype.core_models.Id
import com.anytypeio.anytype.core_models.multiplayer.SpaceMemberPermissions
import com.anytypeio.anytype.core_models.primitives.SpaceId
import com.anytypeio.anytype.domain.multiplayer.UserPermissionProvider
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
class UserPermissionProviderStub : UserPermissionProvider {
private var permission: SpaceMemberPermissions? = null
private var spaceId: SpaceId? = null
override fun start() {}
override fun stop() {}
override fun get(space: SpaceId): SpaceMemberPermissions? {
return permission
}
override fun observe(space: SpaceId): Flow<SpaceMemberPermissions?> = flowOf(permission)
fun stubObserve(spaceId: SpaceId, permission: SpaceMemberPermissions) {
this.spaceId = spaceId
this.permission = permission
}
override fun all(): Flow<Map<Id, SpaceMemberPermissions>> {
return flowOf(emptyMap())
}
}
| 412 | 0.654198 | 1 | 0.654198 | game-dev | MEDIA | 0.206952 | game-dev | 0.626372 | 1 | 0.626372 |
awgil/ffxiv_bossmod | 2,301 | BossMod/Modules/Endwalker/Savage/P8S1Hephaistos/NFlare.cs | namespace BossMod.Endwalker.Savage.P8S1Hephaistos;
// component dealing with tetra/octaflare mechanics (conceptual or not)
class TetraOctaFlareCommon(BossModule module) : Components.UniformStackSpread(module, 3, 6, 2, 2)
{
public enum Concept { None, Tetra, Octa }
public override void OnEventCast(Actor caster, ActorCastEvent spell)
{
if ((AID)spell.Action.ID is AID.EmergentOctaflare or AID.EmergentTetraflare)
{
Stacks.Clear();
Spreads.Clear();
}
}
protected void SetupMasks(Concept concept)
{
switch (concept)
{
case Concept.Tetra:
// note that targets are either all dps or all tanks/healers, it seems to be unknown until actual cast, so for simplicity assume it will target tanks/healers (not that it matters much in practice)
AddStacks(Raid.WithoutSlot().Where(a => a.Role is Role.Tank or Role.Healer));
break;
case Concept.Octa:
AddSpreads(Raid.WithoutSlot());
break;
}
}
}
class TetraOctaFlareImmediate(BossModule module) : TetraOctaFlareCommon(module)
{
public override void OnCastStarted(Actor caster, ActorCastInfo spell)
{
switch ((AID)spell.Action.ID)
{
case AID.Octaflare:
SetupMasks(Concept.Octa);
break;
case AID.Tetraflare:
SetupMasks(Concept.Tetra);
break;
}
}
}
class TetraOctaFlareConceptual(BossModule module) : TetraOctaFlareCommon(module)
{
private Concept _concept;
public override void AddGlobalHints(GlobalHints hints)
{
if (_concept != Concept.None)
hints.Add(_concept == Concept.Tetra ? "Prepare to stack in pairs" : "Prepare to spread");
}
public void Show()
{
SetupMasks(_concept);
_concept = Concept.None;
}
public override void OnCastStarted(Actor caster, ActorCastInfo spell)
{
switch ((AID)spell.Action.ID)
{
case AID.ConceptualOctaflare:
_concept = Concept.Octa;
break;
case AID.ConceptualTetraflare:
_concept = Concept.Tetra;
break;
}
}
}
| 412 | 0.734894 | 1 | 0.734894 | game-dev | MEDIA | 0.977783 | game-dev | 0.926856 | 1 | 0.926856 |
ProjectEQ/projecteqquests | 1,212 | postorms/#Neffiken_Lord_of_Kelek-Vor.lua | local ADDS_TYPES = {
210248, -- a_restrained_ent (210248)
210259, -- a_manipulated_ent (210259)
210258, -- a_maligned_ent (210258)
};
local adds = 0;
function event_spawn(e)
eq.set_timer('depop', 3600 * 1000);
end
function event_combat(e)
if e.joined then
if(not eq.is_paused_timer('depop')) then
eq.pause_timer('depop');
end
eq.set_timer('adds', 30 * 1000);
else
eq.resume_timer('depop');
eq.stop_timer('adds');
end
end
function event_timer(e)
if (e.timer == 'depop') then
eq.unique_spawn(210176,0,0,-1971,1267,-439.5,256); --repop untargetable version
eq.depop();
elseif (e.timer == 'adds') then
if ( adds < 6 ) then
local x = e.self:GetX();
local y = e.self:GetY();
local z = e.self:GetZ() + 5;
local rng = math.random(4, 6);
local spawned = 0;
for i = adds+1, 6 do
eq.spawn2(eq.ChooseRandom(ADDS_TYPES[1], ADDS_TYPES[2], ADDS_TYPES[3]), 0, 0, x + math.random(-100, 100), y + math.random(-100, -50), z, 0);
spawned = spawned + 1;
if ( spawned == rng ) then
break;
end
end
adds = adds + spawned;
end
end
end
function event_death_complete(e)
eq.unique_spawn(210254,0,0,-1971,1267,-439.5,256); --Start Dolshak script
end
| 412 | 0.836263 | 1 | 0.836263 | game-dev | MEDIA | 0.976341 | game-dev | 0.920133 | 1 | 0.920133 |
racenis/tram-sdk | 13,710 | libraries/bullet/BulletDynamics/ConstraintSolver/btTypedConstraint.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2010 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_TYPED_CONSTRAINT_H
#define BT_TYPED_CONSTRAINT_H
#include "LinearMath/btScalar.h"
#include "btSolverConstraint.h"
#include "BulletDynamics/Dynamics/btRigidBody.h"
#ifdef BT_USE_DOUBLE_PRECISION
#define btTypedConstraintData2 btTypedConstraintDoubleData
#define btTypedConstraintDataName "btTypedConstraintDoubleData"
#else
#define btTypedConstraintData2 btTypedConstraintFloatData
#define btTypedConstraintDataName "btTypedConstraintFloatData"
#endif //BT_USE_DOUBLE_PRECISION
class btSerializer;
//Don't change any of the existing enum values, so add enum types at the end for serialization compatibility
enum btTypedConstraintType
{
POINT2POINT_CONSTRAINT_TYPE = 3,
HINGE_CONSTRAINT_TYPE,
CONETWIST_CONSTRAINT_TYPE,
D6_CONSTRAINT_TYPE,
SLIDER_CONSTRAINT_TYPE,
CONTACT_CONSTRAINT_TYPE,
D6_SPRING_CONSTRAINT_TYPE,
GEAR_CONSTRAINT_TYPE,
FIXED_CONSTRAINT_TYPE,
D6_SPRING_2_CONSTRAINT_TYPE,
MAX_CONSTRAINT_TYPE
};
enum btConstraintParams
{
BT_CONSTRAINT_ERP = 1,
BT_CONSTRAINT_STOP_ERP,
BT_CONSTRAINT_CFM,
BT_CONSTRAINT_STOP_CFM
};
#if 1
#define btAssertConstrParams(_par) btAssert(_par)
#else
#define btAssertConstrParams(_par)
#endif
ATTRIBUTE_ALIGNED16(struct)
btJointFeedback
{
BT_DECLARE_ALIGNED_ALLOCATOR();
btVector3 m_appliedForceBodyA;
btVector3 m_appliedTorqueBodyA;
btVector3 m_appliedForceBodyB;
btVector3 m_appliedTorqueBodyB;
};
///TypedConstraint is the baseclass for Bullet constraints and vehicles
ATTRIBUTE_ALIGNED16(class)
btTypedConstraint : public btTypedObject
{
int m_userConstraintType;
union {
int m_userConstraintId;
void* m_userConstraintPtr;
};
btScalar m_breakingImpulseThreshold;
bool m_isEnabled;
bool m_needsFeedback;
int m_overrideNumSolverIterations;
btTypedConstraint& operator=(btTypedConstraint& other)
{
btAssert(0);
(void)other;
return *this;
}
protected:
btRigidBody& m_rbA;
btRigidBody& m_rbB;
btScalar m_appliedImpulse;
btScalar m_dbgDrawSize;
btJointFeedback* m_jointFeedback;
///internal method used by the constraint solver, don't use them directly
btScalar getMotorFactor(btScalar pos, btScalar lowLim, btScalar uppLim, btScalar vel, btScalar timeFact);
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
virtual ~btTypedConstraint(){};
btTypedConstraint(btTypedConstraintType type, btRigidBody & rbA);
btTypedConstraint(btTypedConstraintType type, btRigidBody & rbA, btRigidBody & rbB);
struct btConstraintInfo1
{
int m_numConstraintRows, nub;
};
static btRigidBody& getFixedBody();
struct btConstraintInfo2
{
// integrator parameters: frames per second (1/stepsize), default error
// reduction parameter (0..1).
btScalar fps, erp;
// for the first and second body, pointers to two (linear and angular)
// n*3 jacobian sub matrices, stored by rows. these matrices will have
// been initialized to 0 on entry. if the second body is zero then the
// J2xx pointers may be 0.
btScalar *m_J1linearAxis, *m_J1angularAxis, *m_J2linearAxis, *m_J2angularAxis;
// elements to jump from one row to the next in J's
int rowskip;
// right hand sides of the equation J*v = c + cfm * lambda. cfm is the
// "constraint force mixing" vector. c is set to zero on entry, cfm is
// set to a constant value (typically very small or zero) value on entry.
btScalar *m_constraintError, *cfm;
// lo and hi limits for variables (set to -/+ infinity on entry).
btScalar *m_lowerLimit, *m_upperLimit;
// number of solver iterations
int m_numIterations;
//damping of the velocity
btScalar m_damping;
};
int getOverrideNumSolverIterations() const
{
return m_overrideNumSolverIterations;
}
///override the number of constraint solver iterations used to solve this constraint
///-1 will use the default number of iterations, as specified in SolverInfo.m_numIterations
void setOverrideNumSolverIterations(int overideNumIterations)
{
m_overrideNumSolverIterations = overideNumIterations;
}
///internal method used by the constraint solver, don't use them directly
virtual void buildJacobian(){};
///internal method used by the constraint solver, don't use them directly
virtual void setupSolverConstraint(btConstraintArray & ca, int solverBodyA, int solverBodyB, btScalar timeStep)
{
(void)ca;
(void)solverBodyA;
(void)solverBodyB;
(void)timeStep;
}
///internal method used by the constraint solver, don't use them directly
virtual void getInfo1(btConstraintInfo1 * info) = 0;
///internal method used by the constraint solver, don't use them directly
virtual void getInfo2(btConstraintInfo2 * info) = 0;
///internal method used by the constraint solver, don't use them directly
void internalSetAppliedImpulse(btScalar appliedImpulse)
{
m_appliedImpulse = appliedImpulse;
}
///internal method used by the constraint solver, don't use them directly
btScalar internalGetAppliedImpulse()
{
return m_appliedImpulse;
}
btScalar getBreakingImpulseThreshold() const
{
return m_breakingImpulseThreshold;
}
void setBreakingImpulseThreshold(btScalar threshold)
{
m_breakingImpulseThreshold = threshold;
}
bool isEnabled() const
{
return m_isEnabled;
}
void setEnabled(bool enabled)
{
m_isEnabled = enabled;
}
///internal method used by the constraint solver, don't use them directly
virtual void solveConstraintObsolete(btSolverBody& /*bodyA*/, btSolverBody& /*bodyB*/, btScalar /*timeStep*/){};
const btRigidBody& getRigidBodyA() const
{
return m_rbA;
}
const btRigidBody& getRigidBodyB() const
{
return m_rbB;
}
btRigidBody& getRigidBodyA()
{
return m_rbA;
}
btRigidBody& getRigidBodyB()
{
return m_rbB;
}
int getUserConstraintType() const
{
return m_userConstraintType;
}
void setUserConstraintType(int userConstraintType)
{
m_userConstraintType = userConstraintType;
};
void setUserConstraintId(int uid)
{
m_userConstraintId = uid;
}
int getUserConstraintId() const
{
return m_userConstraintId;
}
void setUserConstraintPtr(void* ptr)
{
m_userConstraintPtr = ptr;
}
void* getUserConstraintPtr()
{
return m_userConstraintPtr;
}
void setJointFeedback(btJointFeedback * jointFeedback)
{
m_jointFeedback = jointFeedback;
}
const btJointFeedback* getJointFeedback() const
{
return m_jointFeedback;
}
btJointFeedback* getJointFeedback()
{
return m_jointFeedback;
}
int getUid() const
{
return m_userConstraintId;
}
bool needsFeedback() const
{
return m_needsFeedback;
}
///enableFeedback will allow to read the applied linear and angular impulse
///use getAppliedImpulse, getAppliedLinearImpulse and getAppliedAngularImpulse to read feedback information
void enableFeedback(bool needsFeedback)
{
m_needsFeedback = needsFeedback;
}
///getAppliedImpulse is an estimated total applied impulse.
///This feedback could be used to determine breaking constraints or playing sounds.
btScalar getAppliedImpulse() const
{
btAssert(m_needsFeedback);
return m_appliedImpulse;
}
btTypedConstraintType getConstraintType() const
{
return btTypedConstraintType(m_objectType);
}
void setDbgDrawSize(btScalar dbgDrawSize)
{
m_dbgDrawSize = dbgDrawSize;
}
btScalar getDbgDrawSize()
{
return m_dbgDrawSize;
}
///override the default global value of a parameter (such as ERP or CFM), optionally provide the axis (0..5).
///If no axis is provided, it uses the default axis for this constraint.
virtual void setParam(int num, btScalar value, int axis = -1) = 0;
///return the local value of parameter
virtual btScalar getParam(int num, int axis = -1) const = 0;
virtual int calculateSerializeBufferSize() const;
///fills the dataBuffer and returns the struct name (and 0 on failure)
virtual const char* serialize(void* dataBuffer, btSerializer* serializer) const;
};
// returns angle in range [-SIMD_2_PI, SIMD_2_PI], closest to one of the limits
// all arguments should be normalized angles (i.e. in range [-SIMD_PI, SIMD_PI])
SIMD_FORCE_INLINE btScalar btAdjustAngleToLimits(btScalar angleInRadians, btScalar angleLowerLimitInRadians, btScalar angleUpperLimitInRadians)
{
if (angleLowerLimitInRadians >= angleUpperLimitInRadians)
{
return angleInRadians;
}
else if (angleInRadians < angleLowerLimitInRadians)
{
btScalar diffLo = btFabs(btNormalizeAngle(angleLowerLimitInRadians - angleInRadians));
btScalar diffHi = btFabs(btNormalizeAngle(angleUpperLimitInRadians - angleInRadians));
return (diffLo < diffHi) ? angleInRadians : (angleInRadians + SIMD_2_PI);
}
else if (angleInRadians > angleUpperLimitInRadians)
{
btScalar diffHi = btFabs(btNormalizeAngle(angleInRadians - angleUpperLimitInRadians));
btScalar diffLo = btFabs(btNormalizeAngle(angleInRadians - angleLowerLimitInRadians));
return (diffLo < diffHi) ? (angleInRadians - SIMD_2_PI) : angleInRadians;
}
else
{
return angleInRadians;
}
}
// clang-format off
///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
struct btTypedConstraintFloatData
{
btRigidBodyFloatData *m_rbA;
btRigidBodyFloatData *m_rbB;
char *m_name;
int m_objectType;
int m_userConstraintType;
int m_userConstraintId;
int m_needsFeedback;
float m_appliedImpulse;
float m_dbgDrawSize;
int m_disableCollisionsBetweenLinkedBodies;
int m_overrideNumSolverIterations;
float m_breakingImpulseThreshold;
int m_isEnabled;
};
///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
#define BT_BACKWARDS_COMPATIBLE_SERIALIZATION
#ifdef BT_BACKWARDS_COMPATIBLE_SERIALIZATION
///this structure is not used, except for loading pre-2.82 .bullet files
struct btTypedConstraintData
{
btRigidBodyData *m_rbA;
btRigidBodyData *m_rbB;
char *m_name;
int m_objectType;
int m_userConstraintType;
int m_userConstraintId;
int m_needsFeedback;
float m_appliedImpulse;
float m_dbgDrawSize;
int m_disableCollisionsBetweenLinkedBodies;
int m_overrideNumSolverIterations;
float m_breakingImpulseThreshold;
int m_isEnabled;
};
#endif //BACKWARDS_COMPATIBLE
struct btTypedConstraintDoubleData
{
btRigidBodyDoubleData *m_rbA;
btRigidBodyDoubleData *m_rbB;
char *m_name;
int m_objectType;
int m_userConstraintType;
int m_userConstraintId;
int m_needsFeedback;
double m_appliedImpulse;
double m_dbgDrawSize;
int m_disableCollisionsBetweenLinkedBodies;
int m_overrideNumSolverIterations;
double m_breakingImpulseThreshold;
int m_isEnabled;
char padding[4];
};
// clang-format on
SIMD_FORCE_INLINE int btTypedConstraint::calculateSerializeBufferSize() const
{
return sizeof(btTypedConstraintData2);
}
class btAngularLimit
{
private:
btScalar
m_center,
m_halfRange,
m_softness,
m_biasFactor,
m_relaxationFactor,
m_correction,
m_sign;
bool
m_solveLimit;
public:
/// Default constructor initializes limit as inactive, allowing free constraint movement
btAngularLimit()
: m_center(0.0f),
m_halfRange(-1.0f),
m_softness(0.9f),
m_biasFactor(0.3f),
m_relaxationFactor(1.0f),
m_correction(0.0f),
m_sign(0.0f),
m_solveLimit(false)
{
}
/// Sets all limit's parameters.
/// When low > high limit becomes inactive.
/// When high - low > 2PI limit is ineffective too becouse no angle can exceed the limit
void set(btScalar low, btScalar high, btScalar _softness = 0.9f, btScalar _biasFactor = 0.3f, btScalar _relaxationFactor = 1.0f);
/// Checks conastaint angle against limit. If limit is active and the angle violates the limit
/// correction is calculated.
void test(const btScalar angle);
/// Returns limit's softness
inline btScalar getSoftness() const
{
return m_softness;
}
/// Returns limit's bias factor
inline btScalar getBiasFactor() const
{
return m_biasFactor;
}
/// Returns limit's relaxation factor
inline btScalar getRelaxationFactor() const
{
return m_relaxationFactor;
}
/// Returns correction value evaluated when test() was invoked
inline btScalar getCorrection() const
{
return m_correction;
}
/// Returns sign value evaluated when test() was invoked
inline btScalar getSign() const
{
return m_sign;
}
/// Gives half of the distance between min and max limit angle
inline btScalar getHalfRange() const
{
return m_halfRange;
}
/// Returns true when the last test() invocation recognized limit violation
inline bool isLimit() const
{
return m_solveLimit;
}
/// Checks given angle against limit. If limit is active and angle doesn't fit it, the angle
/// returned is modified so it equals to the limit closest to given angle.
void fit(btScalar& angle) const;
/// Returns correction value multiplied by sign value
btScalar getError() const;
btScalar getLow() const;
btScalar getHigh() const;
};
#endif //BT_TYPED_CONSTRAINT_H
| 412 | 0.870161 | 1 | 0.870161 | game-dev | MEDIA | 0.969754 | game-dev | 0.853291 | 1 | 0.853291 |
svg-net/SVG | 3,532 | Source/Document Structure/SvgUse.cs | using System;
using System.Collections.Generic;
namespace Svg
{
[SvgElement("use")]
public partial class SvgUse : SvgVisualElement
{
[SvgAttribute("href", SvgAttributeAttribute.XLinkNamespace)]
public virtual Uri ReferencedElement
{
get { return GetAttribute<Uri>("href", false); }
set { Attributes["href"] = value; }
}
private bool ElementReferencesUri(SvgElement element, List<Uri> elementUris)
{
var useElement = element as SvgUse;
if (useElement != null)
{
if (elementUris.Contains(useElement.ReferencedElement))
{
return true;
}
// also detect cycles in referenced elements
var refElement = this.OwnerDocument.IdManager.GetElementById(useElement.ReferencedElement);
if (refElement is SvgUse)
{
elementUris.Add(useElement.ReferencedElement);
}
return useElement.ReferencedElementReferencesUri(elementUris);
}
var groupElement = element as SvgGroup;
if (groupElement != null)
{
foreach (var child in groupElement.Children)
{
if (ElementReferencesUri(child, elementUris))
{
return true;
}
}
}
return false;
}
private bool ReferencedElementReferencesUri(List<Uri> elementUris)
{
var refElement = this.OwnerDocument.IdManager.GetElementById(ReferencedElement);
return ElementReferencesUri(refElement, elementUris);
}
/// <summary>
/// Checks for any direct or indirect recursions in referenced elements,
/// including recursions via groups.
/// </summary>
/// <returns>True if any recursions are found.</returns>
private bool HasRecursiveReference()
{
var refElement = this.OwnerDocument.IdManager.GetElementById(ReferencedElement);
var uris = new List<Uri>() { ReferencedElement };
return ElementReferencesUri(refElement, uris);
}
[SvgAttribute("x")]
public virtual SvgUnit X
{
get { return GetAttribute<SvgUnit>("x", false, 0f); }
set { Attributes["x"] = value; }
}
[SvgAttribute("y")]
public virtual SvgUnit Y
{
get { return GetAttribute<SvgUnit>("y", false, 0f); }
set { Attributes["y"] = value; }
}
[SvgAttribute("width")]
public virtual SvgUnit Width
{
get { return GetAttribute<SvgUnit>("width", false, 0f); }
set { Attributes["width"] = value; }
}
[SvgAttribute("height")]
public virtual SvgUnit Height
{
get { return GetAttribute<SvgUnit>("height", false, 0f); }
set { Attributes["height"] = value; }
}
/// <summary>
/// Gets an <see cref="SvgPoint"/> representing the top left point of the rectangle.
/// </summary>
public SvgPoint Location
{
get { return new SvgPoint(X, Y); }
}
protected override bool Renderable { get { return false; } }
public override SvgElement DeepCopy()
{
return DeepCopy<SvgUse>();
}
}
}
| 412 | 0.742846 | 1 | 0.742846 | game-dev | MEDIA | 0.317355 | game-dev | 0.87949 | 1 | 0.87949 |
Secrets-of-Sosaria/World | 1,220 | Data/Scripts/Items/Armor/Helmets/CloseHelm.cs | using System;
using Server;
namespace Server.Items
{
public class CloseHelm : BaseArmor
{
public override int BasePhysicalResistance{ get{ return 3; } }
public override int BaseFireResistance{ get{ return 3; } }
public override int BaseColdResistance{ get{ return 3; } }
public override int BasePoisonResistance{ get{ return 3; } }
public override int BaseEnergyResistance{ get{ return 3; } }
public override int InitMinHits{ get{ return 45; } }
public override int InitMaxHits{ get{ return 60; } }
public override int AosStrReq{ get{ return 55; } }
public override int OldStrReq{ get{ return 40; } }
public override int ArmorBase{ get{ return 30; } }
public override ArmorMaterialType MaterialType{ get{ return ArmorMaterialType.Plate; } }
[Constructable]
public CloseHelm() : base( 0x1408 )
{
Weight = 5.0;
}
public CloseHelm( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 );
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize( reader );
int version = reader.ReadInt();
if ( Weight == 1.0 )
Weight = 5.0;
}
}
} | 412 | 0.815706 | 1 | 0.815706 | game-dev | MEDIA | 0.304751 | game-dev | 0.897677 | 1 | 0.897677 |
Fluorohydride/ygopro-scripts | 3,085 | c41348446.lua | --デトネーション・コード
function c41348446.initial_effect(c)
--activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--spsummon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(41348446,0))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_QUICK_O)
e2:SetCode(EVENT_FREE_CHAIN)
e2:SetRange(LOCATION_SZONE)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetHintTiming(0,TIMING_END_PHASE)
e2:SetCountLimit(1,41348446)
e2:SetCondition(c41348446.spcon)
e2:SetTarget(c41348446.sptg)
e2:SetOperation(c41348446.spop)
c:RegisterEffect(e2)
--set
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e3:SetCode(EVENT_REMOVE)
e3:SetOperation(c41348446.spreg)
c:RegisterEffect(e3)
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(41348446,1))
e4:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e4:SetRange(LOCATION_REMOVED)
e4:SetCode(EVENT_PHASE+PHASE_STANDBY)
e4:SetCountLimit(1,41348447)
e4:SetCondition(c41348446.setcon)
e4:SetTarget(c41348446.settg)
e4:SetOperation(c41348446.setop)
e4:SetLabelObject(e3)
c:RegisterEffect(e4)
end
function c41348446.cfilter(c)
return c:IsFaceup() and c:IsType(TYPE_LINK) and c:IsSetCard(0x16e)
end
function c41348446.spcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsExistingMatchingCard(c41348446.cfilter,tp,LOCATION_MZONE,0,1,nil)
end
function c41348446.spfilter(c,e,tp)
return c:IsRace(RACE_DRAGON+RACE_MACHINE+RACE_CYBERSE) and c:IsAttribute(ATTRIBUTE_DARK)
and not c:IsType(TYPE_LINK) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c41348446.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c41348446.spfilter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c41348446.spfilter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c41348446.spfilter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c41348446.spop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
end
end
function c41348446.spreg(e,tp,eg,ep,ev,re,r,rp)
if e:GetHandler():IsPreviousLocation(LOCATION_SZONE) then
e:SetLabel(Duel.GetTurnCount()+1)
e:GetHandler():RegisterFlagEffect(41348446,RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END,0,2)
end
end
function c41348446.setcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetLabelObject():GetLabel()==Duel.GetTurnCount() and e:GetHandler():GetFlagEffect(41348446)>0
end
function c41348446.settg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsSSetable() end
Duel.SetOperationInfo(0,CATEGORY_LEAVE_GRAVE,e:GetHandler(),1,0,0)
end
function c41348446.setop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
Duel.SSet(tp,c)
end
end
| 412 | 0.883417 | 1 | 0.883417 | game-dev | MEDIA | 0.976094 | game-dev | 0.949034 | 1 | 0.949034 |
Talberon/solstandard | 2,749 | SolStandard/Containers/Scenario/Objective.cs | using Microsoft.Xna.Framework;
using SolStandard.Containers.Components.Global;
using SolStandard.HUD.Window.Content;
using SolStandard.Utility;
using SolStandard.Utility.Assets;
using SolStandard.Utility.Monogame;
namespace SolStandard.Containers.Scenario
{
public enum VictoryConditions
{
Assassinate,
RoutArmy,
Seize,
Taxes,
Surrender,
Escape,
SoloDefeatBoss,
CollectTheRelicsVS,
CollectTheRelicsCoOp
}
public abstract class Objective
{
protected abstract IRenderable VictoryLabelContent { get; }
protected static Color ObjectiveWindowColor = new Color(30, 30, 30, 180);
protected bool BlueTeamWins;
protected bool RedTeamWins;
protected bool GameIsADraw;
protected bool CoOpVictory;
protected bool AllPlayersLose;
public virtual IRenderable ObjectiveInfo => RenderBlank.Blank;
public abstract bool ConditionsMet { get; }
public void EndGame()
{
GlobalContext.StatusScreenHUD.ResultLabelContent = VictoryLabelContent;
if (RedTeamWins)
{
GlobalContext.StatusScreenHUD.RedTeamResultText = "RED TEAM WINS!";
GlobalContext.StatusScreenHUD.BlueTeamResultText = "BLUE TEAM IS DEFEATED...";
TransferToResultsScreen();
}
if (BlueTeamWins)
{
GlobalContext.StatusScreenHUD.BlueTeamResultText = "BLUE TEAM WINS!";
GlobalContext.StatusScreenHUD.RedTeamResultText = "RED TEAM IS DEFEATED...";
TransferToResultsScreen();
}
if (GameIsADraw)
{
GlobalContext.StatusScreenHUD.BlueTeamResultText = "DRAW...";
GlobalContext.StatusScreenHUD.RedTeamResultText = "DRAW...";
TransferToResultsScreen();
}
if (CoOpVictory)
{
GlobalContext.StatusScreenHUD.BlueTeamResultText = "CO-OP VICTORY!";
GlobalContext.StatusScreenHUD.RedTeamResultText = "CO-OP VICTORY!";
TransferToResultsScreen();
}
if (AllPlayersLose)
{
GlobalContext.StatusScreenHUD.BlueTeamResultText = "YOU LOSE...";
GlobalContext.StatusScreenHUD.RedTeamResultText = "YOU LOSE...";
TransferToResultsScreen();
}
}
private static void TransferToResultsScreen()
{
GlobalContext.CurrentGameState = GlobalContext.GameState.Results;
MusicBox.PlayOnce(AssetManager.MusicTracks.Find(song => song.Name.EndsWith("VictoryJingle")));
}
}
} | 412 | 0.77695 | 1 | 0.77695 | game-dev | MEDIA | 0.401462 | game-dev,desktop-app | 0.800651 | 1 | 0.800651 |
50C4L/portal-cpp-opengl | 3,337 | thirdparty/include/bullet/BulletDynamics/ConstraintSolver/btSolve2LinearConstraint.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_SOLVE_2LINEAR_CONSTRAINT_H
#define BT_SOLVE_2LINEAR_CONSTRAINT_H
#include "LinearMath/btMatrix3x3.h"
#include "LinearMath/btVector3.h"
class btRigidBody;
/// constraint class used for lateral tyre friction.
class btSolve2LinearConstraint
{
btScalar m_tau;
btScalar m_damping;
public:
btSolve2LinearConstraint(btScalar tau, btScalar damping)
{
m_tau = tau;
m_damping = damping;
}
//
// solve unilateral constraint (equality, direct method)
//
void resolveUnilateralPairConstraint(
btRigidBody* body0,
btRigidBody* body1,
const btMatrix3x3& world2A,
const btMatrix3x3& world2B,
const btVector3& invInertiaADiag,
const btScalar invMassA,
const btVector3& linvelA, const btVector3& angvelA,
const btVector3& rel_posA1,
const btVector3& invInertiaBDiag,
const btScalar invMassB,
const btVector3& linvelB, const btVector3& angvelB,
const btVector3& rel_posA2,
btScalar depthA, const btVector3& normalA,
const btVector3& rel_posB1, const btVector3& rel_posB2,
btScalar depthB, const btVector3& normalB,
btScalar& imp0, btScalar& imp1);
//
// solving 2x2 lcp problem (inequality, direct solution )
//
void resolveBilateralPairConstraint(
btRigidBody* body0,
btRigidBody* body1,
const btMatrix3x3& world2A,
const btMatrix3x3& world2B,
const btVector3& invInertiaADiag,
const btScalar invMassA,
const btVector3& linvelA, const btVector3& angvelA,
const btVector3& rel_posA1,
const btVector3& invInertiaBDiag,
const btScalar invMassB,
const btVector3& linvelB, const btVector3& angvelB,
const btVector3& rel_posA2,
btScalar depthA, const btVector3& normalA,
const btVector3& rel_posB1, const btVector3& rel_posB2,
btScalar depthB, const btVector3& normalB,
btScalar& imp0, btScalar& imp1);
/*
void resolveAngularConstraint( const btMatrix3x3& invInertiaAWS,
const btScalar invMassA,
const btVector3& linvelA,const btVector3& angvelA,
const btVector3& rel_posA1,
const btMatrix3x3& invInertiaBWS,
const btScalar invMassB,
const btVector3& linvelB,const btVector3& angvelB,
const btVector3& rel_posA2,
btScalar depthA, const btVector3& normalA,
const btVector3& rel_posB1,const btVector3& rel_posB2,
btScalar depthB, const btVector3& normalB,
btScalar& imp0,btScalar& imp1);
*/
};
#endif //BT_SOLVE_2LINEAR_CONSTRAINT_H
| 412 | 0.820761 | 1 | 0.820761 | game-dev | MEDIA | 0.982718 | game-dev | 0.750167 | 1 | 0.750167 |
Refsa/pollus | 1,661 | src/Pollus.Benchmark/QueryLookupBenchmark.cs | namespace Pollus.Benchmark;
using BenchmarkDotNet.Attributes;
using Pollus.ECS;
[MemoryDiagnoser]
public class QueryLookupBenchmark
{
World oneComponentWorld;
public QueryLookupBenchmark()
{
oneComponentWorld = new();
for (int i = 0; i < 1_000; i++)
{
Entity.With(new Component1()).Spawn(oneComponentWorld);
}
}
~QueryLookupBenchmark()
{
oneComponentWorld.Dispose();
}
[Benchmark]
public void Query_TryGet()
{
var query = new Query(oneComponentWorld);
query.ForEach(query, static (in Query query, in Entity entity) =>
{
ref var component1 = ref query.TryGet<Component1>(entity, out var hasComponent);
if (hasComponent)
{
component1.First++;
}
});
}
[Benchmark]
public void Query_HasGet()
{
var query = new Query(oneComponentWorld);
query.ForEach(query, static (in Query query, in Entity entity) =>
{
if (query.Has<Component1>(entity))
{
ref var component1 = ref query.Get<Component1>(entity);
component1.First++;
}
});
}
[Benchmark]
public void Query_HasGet_EntityInfo()
{
var query = new Query(oneComponentWorld);
query.ForEach(query, static (in Query query, in Entity entity) =>
{
if (query.Has<Component1>(entity, out var entityInfo))
{
ref var component1 = ref query.Get<Component1>(entityInfo);
component1.First++;
}
});
}
}
| 412 | 0.797515 | 1 | 0.797515 | game-dev | MEDIA | 0.714386 | game-dev,databases | 0.592621 | 1 | 0.592621 |
11011010/BFA-Frankenstein-Core | 3,130 | src/server/scripts/Pandaria/GateSettingSun/gate_setting_sun.h | /*
* Copyright (C) 2020 BfaCore
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GATE_SETTING_SUN_H_
#define GATE_SETTING_SUN_H_
#include "SpellScript.h"
#include "Map.h"
#include "Creature.h"
#include "CreatureAIImpl.h"
uint32 const EncounterCount = 4;
enum DataTypes
{
DATA_KIPTILAK = 0,
DATA_GADOK = 1,
DATA_RIMOK = 2,
DATA_RAIGONN = 3,
DATA_IN_FIGHT = 4,
DATA_OPEN_FIRST_DOOR = 5,
DATA_BRASIER_CLICKED = 6,
DATA_RANDOM_BOMBARDER = 7,
DATA_RANDOM_BOMB_STALKER = 8,
MAX_DATA
};
enum CreaturesIds
{
NPC_KIPTILAK = 56906,
NPC_GADOK = 56589,
NPC_RIMOK = 56636,
NPC_RAIGONN = 56877,
NPC_KRITHUK_BOMBARDER = 56706,
NPC_BOMB_STALKER = 56709,
// Kip'Tilak
NPC_STABLE_MUNITION = 56917,
NPC_EXPLOSION_BUNNY_N_M = 56911,
NPC_EXPLOSION_BUNNY_S_M = 56918,
NPC_EXPLOSION_BUNNY_E_M = 56919,
NPC_EXPLOSION_BUNNY_W_M = 56920,
NPC_EXPLOSION_BUNNY_N_P = 59205,
NPC_EXPLOSION_BUNNY_S_P = 59206,
NPC_EXPLOSION_BUNNY_E_P = 59207,
NPC_EXPLOSION_BUNNY_W_P = 59208,
// Gadok
NPC_STALKER_NORTH_SOUTH = 56932,
NPC_STALKER_WEST_EAST = 56913,
NPC_KRIKTHIK_STRIKER = 59778, // Appear on Gadok bombardment
NPC_KRIKTHIK_DISRUPTOR = 59794, // Bombard tower when Gadok is in fight
// Rimok
NPC_ADD_GENERATOR = 59834,
NPC_KRIKTHIK_SWARMER = 59835,
NPC_KRIKTHIK_SABOTEUR = 60447,
// Raingonn
NPC_WEAK_SPOT = 56895,
NPC_KRIKTHIK_PROTECTORAT = 56929,
NPC_KRIKTHIK_ENGULFER = 56912,
NPC_KRIKTHIK_SWARM_BRINGER = 56930,
NPC_ARTILLERY = 59819
};
enum ObjectsIds
{
GO_KIPTILAK_ENTRANCE_DOOR = 212982,
GO_KIPTILAK_WALLS = 214629,
GO_KIPTILAK_MANTID_BOMBS = 215757,
GO_KIPTILAK_EXIT_DOOR = 212983,
GO_SIGNAL_FIRE = 213507,
GO_RIMAK_AFTER_DOOR = 212985,
GO_RAIGONN_DOOR = 212986,
GO_RAIGONN_AFTER_DOOR = 214261,
GO_GREATDOOR_SECOND_DOOR = 214888,
GO_WALL_C = 213198,
GO_PORTAL_TEMP_CORDE = 400001,
GO_PORTAL_TEMP_GADOK = 400002
};
enum eSettingSun
{
CINEMATIC_SETTING_SUN = 265
};
#endif // GATE_SETTING_SUN_H_
| 412 | 0.894352 | 1 | 0.894352 | game-dev | MEDIA | 0.981197 | game-dev | 0.819074 | 1 | 0.819074 |
huppertt/nirs-toolbox | 2,151 | external/fieldtrip/realtime/src/buffer/java/bufferserver/data/EventRingBuffer.java | package nl.fcdonders.fieldtrip.bufferserver.data;
public class EventRingBuffer {
private final Event[] ring;
private final int capacity;
private int eventCount = 0;
private int newPos = 0;
/**
* Constructor
*
* @param size
* size of the ring
*/
public EventRingBuffer(int size) {
ring = new Event[size];
capacity = size;
}
/**
* Adds an item to the buffer.
*
* @param item
*/
public synchronized void add(Event item) {
eventCount++;
ring[newPos++] = item;
// If newPos has reached capacity wrap the ring around.
if (newPos == capacity) {
newPos = 0;
}
}
/**
* Resets the buffer.
*/
public synchronized void clear() {
eventCount = 0;
newPos = 0;
}
/**
* Used to get an item from the ring.
*
* @param index
* Index ranges from 0 to the number of items added in the ring
* -1.
* @return the value at index
*/
public synchronized Event get(int index) throws IndexOutOfBoundsException {
if (index < 0) {
throw new IndexOutOfBoundsException("Index < 0.");
}
if (index < eventCount - capacity) {
throw new IndexOutOfBoundsException(
"Index < index of oldest item in buffer.");
}
if (index >= eventCount) {
throw new IndexOutOfBoundsException("Index >= size.");
}
if (eventCount < capacity) {
// Ring hasn't wrapped yet.
return ring[index];
} else {
// Ring has wrapped.
index -= eventCount - capacity; // Subtract the index of the oldest item
// still in the ring.
index += newPos; // Add ring-index of the oldest item still in the
// ring.
// Check if index should be wrapped around.
if (index >= capacity) {
return ring[index - capacity];
} else {
return ring[index];
}
}
}
/**
* Returns the index of the oldest item.
*
* @return
*/
public synchronized int indexOfOldest() {
if (eventCount <= capacity) {
return 0;
} else {
return eventCount - capacity;
}
}
/**
* Returns the total number of items that have been added to the ring.
*
* @return
*/
public synchronized int eventCount() {
return eventCount;
}
}
| 412 | 0.801422 | 1 | 0.801422 | game-dev | MEDIA | 0.524331 | game-dev | 0.9589 | 1 | 0.9589 |
KangLin/RabbitIm | 1,225 | Plugin/App/Lbs/PluginAppMotion.cpp | #include "PluginAppMotion.h"
#include <QMessageBox>
#include "RabbitCommonLog.h"
CPluginAppMotion::CPluginAppMotion(QObject *parent) : QObject(parent), CPluginApp()
{
}
CPluginAppMotion::~CPluginAppMotion()
{
LOG_MODEL_DEBUG("CPluginAppMotion", "CPluginAppMotion::~CPluginAppMotion");
}
int CPluginAppMotion::Init(const QString &szId)
{
Q_UNUSED(szId);
return 0;
}
int CPluginAppMotion::Clean()
{
if(!m_Main.isNull())
{
m_Main->close();
m_Main.clear();
}
return 0;
}
int CPluginAppMotion::Open(void *pPara, QWidget *parent)
{
Q_UNUSED(parent);
if(m_Main.isNull())
m_Main = QSharedPointer<CFrmLbsMain>(new CFrmLbsMain());
if(!m_Main.isNull())
{
m_Main->show();
m_Main->activateWindow();
}
return 0;
}
int CPluginAppMotion::Close()
{
if(!m_Main.isNull())
{
m_Main->close();
m_Main.clear();
}
return 0;
}
QString CPluginAppMotion::ID()
{
return "Lbs";
}
QString CPluginAppMotion::Name()
{
return tr("Motion");
}
QSet<QString> CPluginAppMotion::Group()
{
return QSet<QString>() << tr("Motion") << tr("Lbs");
}
QIcon CPluginAppMotion::Icon()
{
return QIcon(":/png/motion");
}
| 412 | 0.590319 | 1 | 0.590319 | game-dev | MEDIA | 0.269542 | game-dev | 0.936352 | 1 | 0.936352 |
qnpiiz/rich-2.0 | 3,698 | src/main/java/net/minecraft/client/renderer/entity/model/DrownedModel.java | package net.minecraft.client.renderer.entity.model;
import net.minecraft.client.renderer.model.ModelRenderer;
import net.minecraft.entity.monster.ZombieEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.util.Hand;
import net.minecraft.util.HandSide;
import net.minecraft.util.math.MathHelper;
public class DrownedModel<T extends ZombieEntity> extends ZombieModel<T>
{
public DrownedModel(float p_i48915_1_, float p_i48915_2_, int p_i48915_3_, int p_i48915_4_)
{
super(p_i48915_1_, p_i48915_2_, p_i48915_3_, p_i48915_4_);
this.bipedRightArm = new ModelRenderer(this, 32, 48);
this.bipedRightArm.addBox(-3.0F, -2.0F, -2.0F, 4.0F, 12.0F, 4.0F, p_i48915_1_);
this.bipedRightArm.setRotationPoint(-5.0F, 2.0F + p_i48915_2_, 0.0F);
this.bipedRightLeg = new ModelRenderer(this, 16, 48);
this.bipedRightLeg.addBox(-2.0F, 0.0F, -2.0F, 4.0F, 12.0F, 4.0F, p_i48915_1_);
this.bipedRightLeg.setRotationPoint(-1.9F, 12.0F + p_i48915_2_, 0.0F);
}
public DrownedModel(float p_i49398_1_, boolean p_i49398_2_)
{
super(p_i49398_1_, 0.0F, 64, p_i49398_2_ ? 32 : 64);
}
public void setLivingAnimations(T entityIn, float limbSwing, float limbSwingAmount, float partialTick)
{
this.rightArmPose = BipedModel.ArmPose.EMPTY;
this.leftArmPose = BipedModel.ArmPose.EMPTY;
ItemStack itemstack = entityIn.getHeldItem(Hand.MAIN_HAND);
if (itemstack.getItem() == Items.TRIDENT && entityIn.isAggressive())
{
if (entityIn.getPrimaryHand() == HandSide.RIGHT)
{
this.rightArmPose = BipedModel.ArmPose.THROW_SPEAR;
}
else
{
this.leftArmPose = BipedModel.ArmPose.THROW_SPEAR;
}
}
super.setLivingAnimations(entityIn, limbSwing, limbSwingAmount, partialTick);
}
/**
* Sets this entity's model rotation angles
*/
public void setRotationAngles(T entityIn, float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch)
{
super.setRotationAngles(entityIn, limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch);
if (this.leftArmPose == BipedModel.ArmPose.THROW_SPEAR)
{
this.bipedLeftArm.rotateAngleX = this.bipedLeftArm.rotateAngleX * 0.5F - (float)Math.PI;
this.bipedLeftArm.rotateAngleY = 0.0F;
}
if (this.rightArmPose == BipedModel.ArmPose.THROW_SPEAR)
{
this.bipedRightArm.rotateAngleX = this.bipedRightArm.rotateAngleX * 0.5F - (float)Math.PI;
this.bipedRightArm.rotateAngleY = 0.0F;
}
if (this.swimAnimation > 0.0F)
{
this.bipedRightArm.rotateAngleX = this.rotLerpRad(this.swimAnimation, this.bipedRightArm.rotateAngleX, -2.5132742F) + this.swimAnimation * 0.35F * MathHelper.sin(0.1F * ageInTicks);
this.bipedLeftArm.rotateAngleX = this.rotLerpRad(this.swimAnimation, this.bipedLeftArm.rotateAngleX, -2.5132742F) - this.swimAnimation * 0.35F * MathHelper.sin(0.1F * ageInTicks);
this.bipedRightArm.rotateAngleZ = this.rotLerpRad(this.swimAnimation, this.bipedRightArm.rotateAngleZ, -0.15F);
this.bipedLeftArm.rotateAngleZ = this.rotLerpRad(this.swimAnimation, this.bipedLeftArm.rotateAngleZ, 0.15F);
this.bipedLeftLeg.rotateAngleX -= this.swimAnimation * 0.55F * MathHelper.sin(0.1F * ageInTicks);
this.bipedRightLeg.rotateAngleX += this.swimAnimation * 0.55F * MathHelper.sin(0.1F * ageInTicks);
this.bipedHead.rotateAngleX = 0.0F;
}
}
}
| 412 | 0.811285 | 1 | 0.811285 | game-dev | MEDIA | 0.817985 | game-dev | 0.993182 | 1 | 0.993182 |
Jannyboy11/InvSee-plus-plus | 2,705 | InvSee++_Platforms/Impl_1_21_1_R1/src/main/java/com/janboerman/invsee/spigot/impl_1_21_1_R1/EnderBukkitInventoryView.java | package com.janboerman.invsee.spigot.impl_1_21_1_R1;
import com.janboerman.invsee.spigot.api.EnderSpectatorInventory;
import com.janboerman.invsee.spigot.api.EnderSpectatorInventoryView;
import com.janboerman.invsee.spigot.api.logging.Difference;
import com.janboerman.invsee.spigot.api.logging.DifferenceTracker;
import com.janboerman.invsee.spigot.api.template.EnderChestSlot;
import org.bukkit.craftbukkit.v1_21_R1.inventory.CraftInventoryView;
import org.bukkit.craftbukkit.v1_21_R1.inventory.CraftItemStack;
import org.bukkit.entity.HumanEntity;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import javax.annotation.Nullable;
class EnderBukkitInventoryView extends BukkitInventoryView<EnderChestSlot> implements EnderSpectatorInventoryView {
final EnderNmsContainer nms;
EnderBukkitInventoryView(EnderNmsContainer nms) {
super(nms.creationOptions);
this.nms = nms;
}
@Override
public EnderSpectatorInventory getTopInventory() {
return nms.top.bukkit();
}
@Override
public PlayerInventory getBottomInventory() {
return nms.player.getBukkitEntity().getInventory();
}
@Override
public HumanEntity getPlayer() {
return nms.player.getBukkitEntity();
}
@Override
public InventoryType getType() {
return InventoryType.CHEST;
}
@Override
public String getTitle() {
return nms.title();
}
@Override
public String getOriginalTitle() {
return nms.originalTitle;
}
@Override
public void setTitle(String title) {
CraftInventoryView.sendInventoryTitleChange(this, title);
nms.title = title;
}
@Override
public void setItem(int slot, ItemStack item) {
net.minecraft.world.item.ItemStack stack = CraftItemStack.asNMSCopy(item);
if (slot >= 0) {
nms.getSlot(slot).set(stack);
} else {
nms.player.drop(stack, false);
}
}
@Override
public ItemStack getItem(int slot) {
if (slot < 0) {
return null;
} else {
net.minecraft.world.item.ItemStack nmsStack;
if (slot < nms.top.getContainerSize()) {
nmsStack = nms.top.getContents().get(slot);
} else {
nmsStack = nms.getSlot(slot).getItem();
}
return CraftItemStack.asCraftMirror(nmsStack);
}
}
@Override
public @Nullable Difference getTrackedDifference() {
DifferenceTracker tracker = nms.tracker;
return tracker == null ? null : tracker.getDifference();
}
}
| 412 | 0.899631 | 1 | 0.899631 | game-dev | MEDIA | 0.990959 | game-dev | 0.957497 | 1 | 0.957497 |
johnflynnjohnflynn/BalanceSPTeufelsbergReverb | 4,218 | JUCE/modules/juce_gui_basics/positioning/juce_RelativeCoordinate.cpp | /*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2015 - ROLI 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.
==============================================================================
*/
const String RelativeCoordinate::Strings::parent ("parent");
const String RelativeCoordinate::Strings::left ("left");
const String RelativeCoordinate::Strings::right ("right");
const String RelativeCoordinate::Strings::top ("top");
const String RelativeCoordinate::Strings::bottom ("bottom");
const String RelativeCoordinate::Strings::x ("x");
const String RelativeCoordinate::Strings::y ("y");
const String RelativeCoordinate::Strings::width ("width");
const String RelativeCoordinate::Strings::height ("height");
RelativeCoordinate::StandardStrings::Type RelativeCoordinate::StandardStrings::getTypeOf (const String& s) noexcept
{
if (s == Strings::left) return left;
if (s == Strings::right) return right;
if (s == Strings::top) return top;
if (s == Strings::bottom) return bottom;
if (s == Strings::x) return x;
if (s == Strings::y) return y;
if (s == Strings::width) return width;
if (s == Strings::height) return height;
if (s == Strings::parent) return parent;
return unknown;
}
//==============================================================================
RelativeCoordinate::RelativeCoordinate()
{
}
RelativeCoordinate::RelativeCoordinate (const Expression& term_)
: term (term_)
{
}
RelativeCoordinate::RelativeCoordinate (const RelativeCoordinate& other)
: term (other.term)
{
}
RelativeCoordinate& RelativeCoordinate::operator= (const RelativeCoordinate& other)
{
term = other.term;
return *this;
}
#if JUCE_COMPILER_SUPPORTS_MOVE_SEMANTICS
RelativeCoordinate::RelativeCoordinate (RelativeCoordinate&& other) noexcept
: term (static_cast<Expression&&> (other.term))
{
}
RelativeCoordinate& RelativeCoordinate::operator= (RelativeCoordinate&& other) noexcept
{
term = static_cast<Expression&&> (other.term);
return *this;
}
#endif
RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin)
: term (absoluteDistanceFromOrigin)
{
}
RelativeCoordinate::RelativeCoordinate (const String& s)
{
String error;
term = Expression (s, error);
}
RelativeCoordinate::~RelativeCoordinate()
{
}
bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const noexcept
{
return term.toString() == other.term.toString();
}
bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const noexcept
{
return ! operator== (other);
}
double RelativeCoordinate::resolve (const Expression::Scope* scope) const
{
if (scope != nullptr)
return term.evaluate (*scope);
return term.evaluate();
}
bool RelativeCoordinate::isRecursive (const Expression::Scope* scope) const
{
String error;
if (scope != nullptr)
term.evaluate (*scope, error);
else
term.evaluate (Expression::Scope(), error);
return error.isNotEmpty();
}
void RelativeCoordinate::moveToAbsolute (double newPos, const Expression::Scope* scope)
{
if (scope != nullptr)
{
term = term.adjustedToGiveNewResult (newPos, *scope);
}
else
{
Expression::Scope defaultScope;
term = term.adjustedToGiveNewResult (newPos, defaultScope);
}
}
bool RelativeCoordinate::isDynamic() const
{
return term.usesAnySymbols();
}
String RelativeCoordinate::toString() const
{
return term.toString();
}
| 412 | 0.90478 | 1 | 0.90478 | game-dev | MEDIA | 0.221234 | game-dev | 0.877681 | 1 | 0.877681 |
MafiaHub/Framework | 11,196 | code/framework/src/integrations/client/scripting/builtins/views.h | /*
* MafiaHub OSS license
* Copyright (c) 2021-2024, MafiaHub. All rights reserved.
*
* This file comes from MafiaHub, hosted at https://github.com/MafiaHub/Framework.
* See LICENSE file in the source repository for information regarding licensing.
*/
#pragma once
#include <sol/sol.hpp>
#include "gui/manager.h"
#include "gui/view.h"
#include <logging/logger.h>
#include "core_modules.h"
#include <mutex>
#include <unordered_set>
#include <vector>
#include <JavaScriptCorePP/JSHelper.h>
namespace Framework::Integrations::Scripting {
class ViewWrapper {
private:
int _viewId;
Framework::GUI::Manager *_webManager;
Framework::GUI::View *_view;
sol::function _onViewInit {};
using EventMeta = std::pair<int, std::string>;
static inline std::map<EventMeta, Framework::Scripting::EventHandler> _eventHandlers = {};
public:
ViewWrapper(int viewId, Framework::GUI::Manager *manager): _viewId(viewId), _webManager(manager), _view(nullptr) {
if (_webManager) {
_view = _webManager->GetView(_viewId);
// Hook up a window object ready callback
_view->SetOnWindowObjectReadyCallback([viewId, this](uint64_t frame_id, bool is_main_frame, std::string url) {
const auto view = Framework::CoreModules::GetGUIManager()->GetView(viewId);
const auto sdk = view->GetSDK();
// Grab the context
auto context = JavaScriptCorePP::JSContext(sdk->GetContext());
auto obj = context.GetGlobalObject();
// Set up a bootstrapped Event system
const std::string eventBootstrappingModule = R"(
(function() {
var __mh_events = {};
window.on = function(eventName, callback) {
if (!__mh_events[eventName]) {
__mh_events[eventName] = [];
}
__mh_events[eventName].push(callback);
};
window.__mh_emit = function(eventName, eventPayload) {
if (__mh_events[eventName]) {
for (var i = 0; i < __mh_events[eventName].length; i++) {
__mh_events[eventName][i](eventPayload);
}
}
};
})()
)";
view->EvaluateScript(eventBootstrappingModule);
// Bind emit function
obj["emit"] = [viewId, this](const JavaScriptCorePP::JSContext &context, const std::vector<JavaScriptCorePP::JSValue> &args, JavaScriptCorePP::JSValue &returnValue, JavaScriptCorePP::JSValue &returnException) {
// Make sure there is only two arguments
if (args.size() == 0) {
returnException = context.CreateString("Invalid argument count: emit(string, object | string | null)");
return;
}
std::string eventName;
std::string eventPayload;
// Grab the event name - must be a string
if (args[0].IsString()) {
eventName = args[0].GetString();
}
else {
returnException = context.CreateString("First argument must be a string");
return;
}
const auto scriptingModule = Framework::CoreModules::GetScriptingEngine();
sol::object payload {};
if (args[1].IsObject() || args[1].IsString()) {
try {
std::string payloadStr = "{}";
if (args[1].IsString()) {
payloadStr = args[1].GetString();
}
else if (args[1].IsObject()) {
payloadStr = args[1].ToJSON();
}
payloadStr = args[1].ToJSON();
nlohmann::json payloadJson = nlohmann::json::parse(payloadStr);
payload = Framework::Scripting::Utils::JsonToSol(sol::this_state(scriptingModule->GetLuaEngine()->lua_state()), payloadJson);
}
catch (const std::exception &ex) {
Logging::GetLogger(FRAMEWORK_INNER_CLIENT)->error("Failed to parse event payload: {}", ex.what());
return;
}
}
InvokeEvent(EventMeta(viewId, eventName), payload);
};
});
// Hook up a DOMContentLoaded callback
_view->SetOnDOMReadyCallback([viewId, this](uint64_t frame_id, bool is_main_frame, std::string url) {
if (_onViewInit.valid()) {
sol::protected_function pf {_onViewInit};
auto result = pf(viewId, frame_id, is_main_frame, url);
if (!result.valid()) {
sol::error err = result;
spdlog::error(err.what());
}
}
});
}
}
inline void ListenEvent(std::string name, sol::function fnc) {
_eventHandlers[EventMeta(_viewId, name)].push_back(fnc);
}
template <typename... Args>
static inline void InvokeEvent(const EventMeta &name, Args &&...args) {
auto it = _eventHandlers.find(name);
if (it != _eventHandlers.end()) {
for (auto &callback : it->second) {
sol::protected_function pf {callback};
auto result = pf(std::forward<Args>(args)...);
if (!result.valid()) {
sol::error err = result;
spdlog::error(err.what());
}
}
}
}
void InvokeJSEvent(const std::string &eventName, const sol::object object) {
if (_view) {
try {
// Convert the object to JSON
nlohmann::json jsonPayload = Framework::Scripting::Utils::SolToJson(object);
std::string eventPayload = jsonPayload.dump();
// Emit the event to the view
_view->EvaluateScript(fmt::format("window.__mh_emit(`{}`, `{}`);", eventName, eventPayload));
}
catch (const std::exception &ex) {
Logging::GetLogger(FRAMEWORK_INNER_CLIENT)->error("Failed to emit event: {}", ex.what());
}
}
}
// Explicit method to destroy the view
void Destroy() {
if (_webManager && _view) {
// Then destroy the view
_webManager->DestroyView(_viewId);
_view = nullptr;
}
}
int GetId() const {
return _viewId;
}
void SetPosition(int x, int y) {
if (_view) {
_view->SetPosition(x, y);
}
}
void SetZIndex(int z) {
if (_view) {
_view->SetZIndex(z);
}
}
int GetZIndex() const {
if (_view) {
return _view->GetZIndex();
}
return 0;
}
void Focus(bool enable) {
if (_view) {
_view->Focus(enable);
}
}
bool HasFocus() const {
if (_view) {
return _view->HasFocus();
}
return false;
}
void Display(bool enable) {
if (_view) {
_view->Display(enable);
}
}
bool ShouldDisplay() const {
if (_view) {
return _view->ShouldDisplay();
}
return false;
}
std::string EvaluateScript(const std::string &script) {
if (_view) {
return _view->EvaluateScript(script);
}
return "";
}
void SetOnViewInit(sol::function callback) {
_onViewInit = callback;
}
};
class Views {
private:
static ViewWrapper *CreateView(const std::string &url, int width = 0, int height = 0, int x = 0, int y = 0) {
auto guiManager = Framework::CoreModules::GetGUIManager();
if (!guiManager) {
throw std::runtime_error("GUI Manager is not initialized");
}
int viewId = guiManager->CreateView(url, width, height, x, y);
if (viewId < 0) {
throw std::runtime_error("Failed to create view");
}
const auto view = guiManager->GetView(viewId);
view->Display(true);
view->Focus(false);
// ensures the view is destroyed on gamemode reload or server disconnect
view->SetGarbageCollected(true);
return new ViewWrapper(viewId, guiManager);
}
public:
static void Register(sol::state *luaEngine) {
// Register the ViewWrapper class
sol::usertype<ViewWrapper> viewWrapperType = luaEngine->new_usertype<ViewWrapper>("View", sol::no_constructor);
viewWrapperType["create"] = &Views::CreateView;
viewWrapperType["getId"] = &ViewWrapper::GetId;
viewWrapperType["setPosition"] = &ViewWrapper::SetPosition;
viewWrapperType["setZIndex"] = &ViewWrapper::SetZIndex;
viewWrapperType["getZIndex"] = &ViewWrapper::GetZIndex;
viewWrapperType["setFocus"] = &ViewWrapper::Focus;
viewWrapperType["getFocus"] = &ViewWrapper::HasFocus;
viewWrapperType["setDisplay"] = &ViewWrapper::Display;
viewWrapperType["getDisplay"] = &ViewWrapper::ShouldDisplay;
viewWrapperType["on"] = &ViewWrapper::ListenEvent;
viewWrapperType["emit"] = &ViewWrapper::InvokeJSEvent;
viewWrapperType["onViewInit"] = &ViewWrapper::SetOnViewInit;
viewWrapperType["destroy"] = &ViewWrapper::Destroy;
// TODO: consider whether we want to expose raw JS calls to the user
// viewWrapperType["evaluateScript"] = &ViewWrapper::EvaluateScript;
}
};
} // namespace Framework::Integrations::Scripting
| 412 | 0.960314 | 1 | 0.960314 | game-dev | MEDIA | 0.66782 | game-dev | 0.948366 | 1 | 0.948366 |
FlansMods/FlansMod | 19,573 | src/main/java/com/flansmod/client/gui/teams/GuiEditLoadout.java | package com.flansmod.client.gui.teams;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import org.lwjgl.opengl.GL11;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
import com.flansmod.client.teams.ClientTeamsData;
import com.flansmod.common.FlansMod;
import com.flansmod.common.guns.AttachmentType;
import com.flansmod.common.guns.EnumAttachmentType;
import com.flansmod.common.guns.GunType;
import com.flansmod.common.guns.ItemGun;
import com.flansmod.common.guns.ItemShootable;
import com.flansmod.common.guns.Paintjob;
import com.flansmod.common.guns.ShootableType;
import com.flansmod.common.paintjob.IPaintableItem;
import com.flansmod.common.paintjob.PaintableType;
import com.flansmod.common.teams.LoadoutPool;
import com.flansmod.common.teams.LoadoutPool.LoadoutEntry;
import com.flansmod.common.teams.LoadoutPool.LoadoutEntryInfoType;
import com.flansmod.common.teams.LoadoutPool.LoadoutEntryPaintjob;
import com.flansmod.common.teams.PlayerLoadout;
import com.flansmod.common.teams.PlayerRankData;
import com.flansmod.common.teams.TeamsManagerRanked;
import com.flansmod.common.types.IFlanItem;
import com.flansmod.common.types.InfoType;
public class GuiEditLoadout extends GuiTeamsBase
{
/**
* The background image
*/
private static final ResourceLocation texture = new ResourceLocation("flansmod", "gui/LoadoutEditor.png");
private static final int WIDTH = 326, HEIGHT = 198;
protected int selectedLoadout = 0;
protected EnumLoadoutSlot selectedSlot = EnumLoadoutSlot.primary;
protected int selectedCategory = 0;
protected int scroller = 0;
private PlayerLoadout previousLoadout = null;
protected ArrayList<LoadoutEntry> availableComponents = new ArrayList<>();
private static final String[] WEAPON_COMPONENT_NAMES = new String[]
{"Weapon", "Paint", "Scope", "Barrel", "Stock", "Grip", "Extra"};
private static final String[] NON_WEAPON_COMPONENT_NAMES = new String[]
{"Item", "Paint"};
public GuiEditLoadout(int i)
{
super();
selectedLoadout = i;
previousLoadout = ClientTeamsData.theRankData.loadouts[selectedLoadout].copy();
RecalculateAvailableEntries();
}
@Override
public void initGui()
{
super.initGui();
ScaledResolution scaledresolution = new ScaledResolution(mc);
int w = scaledresolution.getScaledWidth();
int h = scaledresolution.getScaledHeight();
guiOriginX = w / 2 - WIDTH / 2;
guiOriginY = h / 2 - HEIGHT / 2;
buttonList.add(new GuiButton(0, width / 2 - WIDTH / 2 + 10, height / 2 - HEIGHT / 2 + 143, 82, 20, "Confirm"));
buttonList.add(new GuiButton(1, width / 2 - WIDTH / 2 + 10, height / 2 - HEIGHT / 2 + 165, 82, 20, "Cancel"));
}
@Override
protected void actionPerformed(GuiButton button)
{
if(button.id == 0) // Confirm
{
// Send data to server
TeamsManagerRanked.ConfirmLoadoutChanges();
ClientTeamsData.OpenLandingPage();
}
else if(button.id == 1) // Cancel
{
ClientTeamsData.theRankData.loadouts[selectedLoadout] = previousLoadout.copy();
ClientTeamsData.OpenLandingPage();
}
}
@Override
public void drawScreen(int i, int j, float f)
{
ScaledResolution scaledresolution = new ScaledResolution(mc);
int w = scaledresolution.getScaledWidth();
int h = scaledresolution.getScaledHeight();
drawDefaultBackground();
GlStateManager.enableBlend();
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
guiOriginX = w / 2 - WIDTH / 2;
guiOriginY = h / 2 - HEIGHT / 2;
//Bind the background texture
mc.renderEngine.bindTexture(texture);
int textureX = 512;
int textureY = 256;
PlayerRankData data = ClientTeamsData.theRankData;
LoadoutPool pool = ClientTeamsData.currentPool;
if(data == null || pool == null)
{
FlansMod.log.warn("Problem in landing page!");
return;
}
//Draw the background
drawModalRectWithCustomSizedTexture(guiOriginX, guiOriginY, 0, 0, WIDTH, HEIGHT, textureX, textureY);
// Draw title text
drawCenteredString(fontRenderer, "Edit Loadout " + (selectedLoadout + 1), guiOriginX + WIDTH / 2, guiOriginY + 4, 0xffffff);
// Draw loadout slots panel
{
mc.renderEngine.bindTexture(texture);
drawModalRectWithCustomSizedTexture(guiOriginX + 70, guiOriginY + 32 + 22 * selectedSlot.ordinal(), 70, 203, 36, 22, textureX, textureY);
drawCenteredString(fontRenderer, "Loadout", guiOriginX + 51, guiOriginY + 18, 0xffffff);
for(int n = 0; n < EnumLoadoutSlot.values().length; n++)
{
drawCenteredString(fontRenderer, EnumLoadoutSlot.values()[n].name, guiOriginX + 39, guiOriginY + 38 + 22 * n, 0xffffff);
ItemStack stack = data.loadouts[selectedLoadout].slots[n];
drawSlotInventory(stack, guiOriginX + 73, guiOriginY + 35 + 22 * n);
}
}
// Draw slot panel
{
mc.renderEngine.bindTexture(texture);
drawModalRectWithCustomSizedTexture(guiOriginX + 169, guiOriginY + 32 + 22 * selectedCategory, 70, 203, 36, 22, textureX, textureY);
drawCenteredString(fontRenderer, selectedSlot.name, guiOriginX + 150, guiOriginY + 18, 0xffffff);
if(selectedSlot.isWeapon)
{
for(int n = 0; n < WEAPON_COMPONENT_NAMES.length; n++)
{
ItemStack stack = data.loadouts[selectedLoadout].slots[selectedSlot.ordinal()];
InfoType type = (stack != null && stack.getItem() instanceof IFlanItem) ? ((IFlanItem)stack.getItem()).getInfoType() : null;
int numUnlocks = type != null ? data.GetNumUnlocksForType(type) : 0;
if(n == 1 && type != null && numUnlocks > 0)
{
drawCenteredString(fontRenderer, WEAPON_COMPONENT_NAMES[n] + " (" + numUnlocks + ")", guiOriginX + 138, guiOriginY + 38 + 22 * n, 0xffffff);
}
else
drawCenteredString(fontRenderer, WEAPON_COMPONENT_NAMES[n], guiOriginX + 138, guiOriginY + 38 + 22 * n, 0xffffff);
switch(n)
{
case 0: // Main item
{
ItemStack copy = ItemStack.EMPTY.copy();
if(stack != null)
{
copy = stack.copy();
copy.setItemDamage(0);
}
drawSlotInventory(copy, guiOriginX + 172, guiOriginY + 35 + 22 * n);
break;
}
case 1: // Paint
{
drawSlotInventory(stack, guiOriginX + 172, guiOriginY + 35 + 22 * n);
break;
}
default:
{
if(stack != null && !stack.isEmpty() && stack.getTagCompound() != null)
{
NBTTagCompound attachmentTags = stack.getTagCompound().getCompoundTag("attachments");
if(attachmentTags != null)
{
ItemStack attachmentStack = ItemStack.EMPTY.copy();
switch(n)
{
case 2: attachmentStack = new ItemStack(attachmentTags.getCompoundTag("scope"));
break;
case 3: attachmentStack = new ItemStack(attachmentTags.getCompoundTag("barrel"));
break;
case 4: attachmentStack = new ItemStack(attachmentTags.getCompoundTag("stock"));
break;
case 5: attachmentStack = new ItemStack(attachmentTags.getCompoundTag("grip"));
break;
case 6: attachmentStack = new ItemStack(attachmentTags.getCompoundTag("generic_0"));
break;
}
drawSlotInventory(attachmentStack, guiOriginX + 172, guiOriginY + 35 + 22 * n);
}
}
break;
}
}
}
}
else
{
for(int n = 0; n < NON_WEAPON_COMPONENT_NAMES.length; n++)
{
drawCenteredString(fontRenderer, NON_WEAPON_COMPONENT_NAMES[n], guiOriginX + 138, guiOriginY + 38 + 22 * n, 0xffffff);
ItemStack stack = data.loadouts[selectedLoadout].slots[selectedSlot.ordinal()];
switch(n)
{
case 0: // Main item
{
ItemStack copy = ItemStack.EMPTY.copy();
if(stack != null)
{
copy = stack.copy();
copy.setItemDamage(0);
}
drawSlotInventory(copy, guiOriginX + 172, guiOriginY + 35 + 22 * n);
break;
}
case 1: // Paint
{
drawSlotInventory(stack, guiOriginX + 172, guiOriginY + 35 + 22 * n);
break;
}
default:
{
break;
}
}
}
}
}
// Draw stats panel
{
String name = "";
ItemStack stack = data.loadouts[selectedLoadout].slots[selectedSlot.ordinal()];
if(stack != null && !stack.isEmpty())
{
name = stack.getDisplayName();
}
drawCenteredString(fontRenderer, name, guiOriginX + 262, guiOriginY + 18, 0xffffff);
DrawGun(stack, guiOriginX + 254, guiOriginY + 48, 40f);
drawCenteredString(fontRenderer, "Damage", guiOriginX + 234, guiOriginY + 60, 0xffffff);
drawCenteredString(fontRenderer, "Accuracy", guiOriginX + 234, guiOriginY + 70, 0xffffff);
drawCenteredString(fontRenderer, "Ammo", guiOriginX + 234, guiOriginY + 80, 0xffffff);
if(stack != null && stack.getItem() instanceof ItemGun)
{
GunType type = ((ItemGun)stack.getItem()).GetType();
LoadoutEntryInfoType entry = pool.GetLoadoutEntryForInfoType(selectedSlot.ordinal(), type);
ShootableType mainAmmo = null;
int numClips = 1;
for(ItemStack extra : entry.extraItems)
{
if(extra != null && extra.getItem() instanceof ItemShootable)
{
mainAmmo = ((ItemShootable)extra.getItem()).type;
numClips = extra.getCount();
break;
}
}
if(mainAmmo != null)
{
drawCenteredString(fontRenderer, String.format("%.0f", type.damage * mainAmmo.damageVsLiving * mainAmmo.numBullets), guiOriginX + 290, guiOriginY + 60, 0xffffff);
drawCenteredString(fontRenderer, String.format("%.0f", (50.0f - type.bulletSpread) * 2.0f), guiOriginX + 290, guiOriginY + 70, 0xffffff);
drawCenteredString(fontRenderer, String.format("%d", mainAmmo.roundsPerItem * numClips), guiOriginX + 290, guiOriginY + 80, 0xffffff);
}
}
}
// Draw selector panel
{
drawCenteredString(fontRenderer, "Choose " + WEAPON_COMPONENT_NAMES[selectedCategory].toLowerCase(), guiOriginX + 262, guiOriginY + 95, 0xffffff);
for(int row = 0; row < 4; row++)
{
for(int col = 0; col < 6; col++)
{
int index = scroller * 24 + row * 6 + col;
if(index >= availableComponents.size())
{
continue;
}
LoadoutEntry entry = availableComponents.get(index);
if(entry instanceof LoadoutEntryInfoType)
{
drawSlotInventory(new ItemStack(((LoadoutEntryInfoType)entry).type.getItem()), guiOriginX + 209 + col * 18, guiOriginY + 107 + row * 18);
}
else if(entry instanceof LoadoutEntryPaintjob)
{
Paintjob paintjob = ((LoadoutEntryPaintjob)entry).paintjob;
DrawRarityBackground(paintjob.rarity, guiOriginX + 209 + col * 18, guiOriginY + 107 + row * 18);
drawSlotInventory(new ItemStack(paintjob.parent.getItem(), 1, paintjob.ID), guiOriginX + 209 + col * 18, guiOriginY + 107 + row * 18);
}
if(!entry.available)
{
mc.renderEngine.bindTexture(texture);
GlStateManager.pushMatrix();
GlStateManager.translate(0.0f, 0.0f, 101.0f);
drawModalRectWithCustomSizedTexture(guiOriginX + 209 + col * 18, guiOriginY + 107 + row * 18, 332, 161, 16, 16, textureX, textureY);
if(entry.unlockLevel > 0)
{
drawCenteredString(fontRenderer, "" + entry.unlockLevel, guiOriginX + 218 + col * 18, guiOriginY + 112 + row * 18, 0xffffff);
}
GlStateManager.popMatrix();
}
}
}
}
// Resets some GL modes to prevent screen going grey sometimes. Quick and easy hack. Thanks, stick.
drawSlotInventory(new ItemStack(Items.STICK), -50, -50);
super.drawScreen(i, j, f);
}
private boolean IsInSquare(int clickX, int clickY, int x, int y, int w, int h)
{
return x <= clickX && clickX < x + w
&& y <= clickY && clickY < y + h;
}
@Override
protected void mouseClicked(int i, int j, int k) throws IOException
{
super.mouseClicked(i, j, k);
int x = i - guiOriginX;
int y = j - guiOriginY;
if(k == 0 || k == 1)
{
// Loadout slots panel
for(int n = 0; n < EnumLoadoutSlot.values().length; n++)
{
if(IsInSquare(x, y, 70, 32 + 22 * n, 22, 22))
{
selectedSlot = EnumLoadoutSlot.values()[n];
//if(!selectedSlot.isWeapon && selectedCategory > 2)
selectedCategory = 0;
RecalculateAvailableEntries();
}
}
// Slot panel
if(selectedSlot.isWeapon)
{
for(int n = 0; n < WEAPON_COMPONENT_NAMES.length; n++)
{
if(IsInSquare(x, y, 169, 32 + 22 * n, 22, 22))
{
selectedCategory = n;
RecalculateAvailableEntries();
}
}
}
else
{
for(int n = 0; n < NON_WEAPON_COMPONENT_NAMES.length; n++)
{
if(IsInSquare(x, y, 169, 32 + 22 * n, 22, 22))
{
selectedCategory = n;
RecalculateAvailableEntries();
}
}
}
// Selector panel
for(int row = 0; row < 4; row++)
{
for(int col = 0; col < 6; col++)
{
int index = scroller * 24 + row * 6 + col;
if(index >= availableComponents.size()) continue;
if(!availableComponents.get(index).available) continue;
if(IsInSquare(x, y, 209 + col * 18, 107 + row * 18, 18, 18))
{
LoadoutEntry entry = availableComponents.get(index);
SelectItem(entry);
}
}
}
if(IsInSquare(x, y, 257, 179, 10, 10))
{
SelectItem(null);
}
}
}
public void SelectItem(LoadoutEntry entry)
{
PlayerRankData data = ClientTeamsData.theRankData;
LoadoutPool pool = ClientTeamsData.currentPool;
switch(selectedCategory)
{
case 0: // Main item
{
if(entry instanceof LoadoutEntryInfoType)
{
data.loadouts[selectedLoadout].slots[selectedSlot.ordinal()] = new ItemStack(((LoadoutEntryInfoType)entry).type.getItem());
}
else if(entry != null)
{
FlansMod.log.warn("Loadout entry doesn't match for slot");
}
break;
}
case 1: // Paint
{
if(entry instanceof LoadoutEntryPaintjob)
{
if(data.loadouts[selectedLoadout].slots[selectedSlot.ordinal()] != null)
{
data.loadouts[selectedLoadout].slots[selectedSlot.ordinal()].setItemDamage(((LoadoutEntryPaintjob)entry).paintjob.ID);
}
else FlansMod.log.warn("Applying paintjob to null item!");
}
else if(entry != null)
{
FlansMod.log.warn("Loadout entry doesn't match slot");
}
}
default: // Attachments
{
if(entry instanceof LoadoutEntryInfoType || entry == null)
{
ItemStack stack = data.loadouts[selectedLoadout].slots[selectedSlot.ordinal()];
if(stack != null && !stack.isEmpty())
{
if(stack.getTagCompound() == null)
{
stack.setTagCompound(new NBTTagCompound());
}
NBTTagCompound attachmentTags = stack.getTagCompound().getCompoundTag("attachments");
if(attachmentTags == null)
{
attachmentTags = new NBTTagCompound();
}
NBTTagCompound ourTags = new NBTTagCompound();
if(entry != null)
{
ItemStack attachmentStack = new ItemStack(((LoadoutEntryInfoType)entry).type.getItem());
attachmentStack.writeToNBT(ourTags);
}
switch(selectedCategory)
{
case 2: attachmentTags.setTag("scope", ourTags);
break;
case 3: attachmentTags.setTag("barrel", ourTags);
break;
case 4: attachmentTags.setTag("stock", ourTags);
break;
case 5: attachmentTags.setTag("grip", ourTags);
break;
case 6: attachmentTags.setTag("generic_0", ourTags);
break;
}
stack.getTagCompound().setTag("attachments", attachmentTags);
}
else FlansMod.log.warn("Applying attachment to null item!");
}
else FlansMod.log.warn("Loadout entry doesn't match for slot");
}
}
}
public class LoadoutComparator implements Comparator<LoadoutEntry>
{
@Override
public int compare(LoadoutEntry a, LoadoutEntry b)
{
if(a.unlockLevel < b.unlockLevel) return -1;
if(a.unlockLevel > b.unlockLevel) return 1;
if(a instanceof LoadoutEntryPaintjob && b instanceof LoadoutEntryPaintjob)
{
if(((LoadoutEntryPaintjob)a).paintjob.rarity.ordinal() < ((LoadoutEntryPaintjob)b).paintjob.rarity.ordinal())
return -1;
if(((LoadoutEntryPaintjob)a).paintjob.rarity.ordinal() > ((LoadoutEntryPaintjob)b).paintjob.rarity.ordinal())
return 1;
}
return 0;
}
}
public void RecalculateAvailableEntries()
{
availableComponents.clear();
PlayerRankData data = ClientTeamsData.theRankData;
LoadoutPool pool = ClientTeamsData.currentPool;
ArrayList<LoadoutEntry> unlockedEntries = new ArrayList<>();
ArrayList<LoadoutEntry> lockedEntries = new ArrayList<>();
if(selectedCategory == 1) // Paint
{
ItemStack stack = data.loadouts[selectedLoadout].slots[selectedSlot.ordinal()];
if(stack != null && stack.getItem() instanceof IPaintableItem)
{
PaintableType type = ((IPaintableItem)stack.getItem()).GetPaintableType();
for(int i = 0; i < type.paintjobs.size(); i++)
{
LoadoutEntryPaintjob entry = new LoadoutEntryPaintjob();
entry.unlockLevel = 0;
entry.paintjob = type.paintjobs.get(i);
if(i == 0)
{
entry.available = true;
}
else
{
entry.available = TeamsManagerRanked.LocalPlayerOwnsUnlock(entry.paintjob.hashCode());
}
if(entry.available)
unlockedEntries.add(entry);
else
lockedEntries.add(entry);
}
}
}
else
{
for(LoadoutEntryInfoType entry : pool.unlocks[selectedSlot.ordinal()])
{
switch(selectedCategory)
{
case 0: // Main item
{
if(entry.type instanceof AttachmentType) continue;
break;
}
case 1: break; // Paint. Shouldn't even get here
default: // Attachments. Check sub-type
{
// Check it is an attachment
if(!(entry.type instanceof AttachmentType)) continue;
// Check that the gun allows it
GunType gunType = ((ItemGun)data.loadouts[selectedLoadout].slots[selectedSlot.ordinal()].getItem()).GetType();
if(!gunType.allowAllAttachments && !gunType.allowedAttachments.contains(entry.type)) continue;
// And check that it is right for the slot
EnumAttachmentType attachType = ((AttachmentType)entry.type).type;
switch(selectedCategory)
{
case 2: if(attachType != EnumAttachmentType.sights) continue;
else break;
case 3: if(attachType != EnumAttachmentType.barrel) continue;
else break;
case 4: if(attachType != EnumAttachmentType.stock) continue;
else break;
case 5: if(attachType != EnumAttachmentType.grip) continue;
else break;
case 6: if(attachType != EnumAttachmentType.generic) continue;
else break;
}
break;
}
}
LoadoutEntryInfoType copy = new LoadoutEntryInfoType();
copy.type = entry.type;
copy.unlockLevel = entry.unlockLevel;
copy.available = data.currentLevel >= copy.unlockLevel;
if(copy.available)
unlockedEntries.add(copy);
else
lockedEntries.add(copy);
}
}
unlockedEntries.sort(new LoadoutComparator());
lockedEntries.sort(new LoadoutComparator());
availableComponents.addAll(unlockedEntries);
availableComponents.addAll(lockedEntries);
}
@Override
public boolean doesGuiPauseGame()
{
return false;
}
}
| 412 | 0.936729 | 1 | 0.936729 | game-dev | MEDIA | 0.857508 | game-dev | 0.987625 | 1 | 0.987625 |
gdquest-demos/godot-2d-space-game | 2,515 | project/world/game_world.gd | # Spawns the station, asteroids, and pirates when entering the game.
# Keeps track of resources available in the world and which asteroid clusters holds it,
# and spawns more when running low.
# It also signals the pirate spawner when an upgrade has been made.
class_name GameWorld
extends Node2D
# Radius of the world in pixels.
@export var radius := 8000.0
# Minimum amount of iron that must be added when the world spawns new asteroids.
# Used in `_spawn_asteroids`.
@export var iron_amount_balance_level := 100.0
# If the amouns of iron in the world goes below this threshold, spawns new asteroids.
@export var refresh_threshold_range := 25.0
var _spawned_positions := []
var _world_objects := []
var _iron_clusters := {}
@onready var rng := RandomNumberGenerator.new()
@onready var station_spawner: StationSpawner = $StationSpawner
@onready var asteroid_spawner: AsteroidSpawner = $AsteroidSpawner
@onready var pirate_spawner: PirateSpawner = $PirateSpawner
func _ready() -> void:
await owner.ready
setup()
func setup() -> void:
rng.randomize()
Events.upgrade_chosen.connect(_on_Events_upgrade_chosen)
asteroid_spawner.cluster_depleted.connect(_on_AsteroidSpawner_cluster_depleted)
station_spawner.spawn_station(rng)
asteroid_spawner.spawn_asteroid_clusters(rng, iron_amount_balance_level, radius)
pirate_spawner.spawn_pirate_group(
rng, 0, radius, _find_largest_inoccupied_asteroid_cluster().global_position
)
# Returns the AsteroidCluster with the most iron that isn't occupied.
# If all clusters are occupied, returns `null`.
func _find_largest_inoccupied_asteroid_cluster() -> AsteroidCluster:
var target_cluster: AsteroidCluster
var target_cluster_iron_amount := -INF
for cluster in asteroid_spawner.get_children():
assert(cluster is AsteroidCluster)
if cluster.is_occupied:
continue
if cluster.iron_amount > target_cluster_iron_amount:
target_cluster = cluster
target_cluster_iron_amount = cluster.iron_amount
if target_cluster:
target_cluster.is_occupied = true
return target_cluster
# Spawn a new group of pirates upon getting an upgrade
func _on_Events_upgrade_chosen(_choice) -> void:
var target_cluster := _find_largest_inoccupied_asteroid_cluster()
if target_cluster:
pirate_spawner.spawn_pirate_group(rng, 0, radius, target_cluster.global_position)
func _on_AsteroidSpawner_cluster_depleted(iron_left: float) -> void:
if iron_left < refresh_threshold_range:
asteroid_spawner.spawn_asteroid_clusters(rng, iron_amount_balance_level, radius)
| 412 | 0.759351 | 1 | 0.759351 | game-dev | MEDIA | 0.961979 | game-dev | 0.764264 | 1 | 0.764264 |
ProjectDreamland/area51 | 30,108 | Support/Objects/DeadBody.cpp | #include "DeadBody.hpp"
#include "e_ScratchMem.hpp"
#include "Entropy\Entropy.hpp"
#include "Characters\Character.hpp"
#include "Loco\Loco.hpp"
#include "Objects\BaseProjectile.hpp"
#include "Decals\DecalMgr.hpp"
#include "Dictionary\global_dictionary.hpp"
#include "Characters\ActorEffects.hpp"
static const f32 FLOOR_RAY_TEST_EXTENT = 50.0f;
static const s32 MAX_DEAD_BODIES = 4;
static const f32 FADEOUT_START_TIME = 8.0f;
static const f32 FADEOUT_TIME = 2.0f;
//=========================================================================
// EXTERNS
//=========================================================================
#ifdef X_EDITOR
extern xbool g_game_running ;
#endif // X_EDITOR
//=========================================================================
// OBJECT DESC
//=========================================================================
static struct dead_body_desc : public object_desc
{
dead_body_desc( void ) : object_desc( object::TYPE_DEAD_BODY,
"Dead Body",
"AI",
object::ATTR_SPACIAL_ENTRY |
object::ATTR_NEEDS_LOGIC_TIME |
object::ATTR_SOUND_SOURCE |
object::ATTR_COLLIDABLE |
object::ATTR_BLOCKS_ALL_PROJECTILES |
object::ATTR_BLOCKS_RAGDOLL |
object::ATTR_BLOCKS_SMALL_DEBRIS |
object::ATTR_DAMAGEABLE |
object::ATTR_NO_RUNTIME_SAVE |
object::ATTR_RENDERABLE |
object::ATTR_TRANSPARENT,
FLAGS_GENERIC_EDITOR_CREATE | FLAGS_NO_ICON |
FLAGS_IS_DYNAMIC ) {}
//-------------------------------------------------------------------------
virtual object* Create( void ) { return new dead_body; }
//-------------------------------------------------------------------------
#ifdef X_EDITOR
virtual s32 OnEditorRender( object& Object ) const
{
object_desc::OnEditorRender( Object );
return -1;
}
#endif // X_EDITOR
} s_DeadBodyDesc;
//=========================================================================
const object_desc& dead_body::GetTypeDesc( void ) const
{
return s_DeadBodyDesc;
}
//=========================================================================
const object_desc& dead_body::GetObjectType( void )
{
return s_DeadBodyDesc;
}
//=========================================================================
// FUNCTIONS
//=========================================================================
//=========================================================================
dead_body::dead_body( void ) :
m_bPhysics(FALSE),
m_bCreatedBlood(FALSE),
m_bCanDelete(FALSE),
m_bPermanent(FALSE),
m_bDestroy(FALSE),
m_bDrainable(FALSE),
m_TimeAlive(0.0f),
m_NoEnergyTimer(0),
m_pActorEffects(NULL),
m_AnimGroupName(-1),
m_AnimName(-1),
m_AnimFrame(0),
m_SimulationTime(0.0f),
m_RagdollType(ragdoll::TYPE_CIVILIAN),
m_BloodDecalGroup(-1)
{
m_FloorProperties.Init( 100.0f, 0.5f );
// This assumes that the dead body is about 2.5 meters tall. Then is about 2
// meters around. The bbox is center around the eyes of the player.
m_ZoneTracker.SetBBox( bbox( vector3( -100, -200, -100 ),
vector3( 100, 50, 100 ) ) );
}
//=========================================================================
dead_body::~dead_body()
{
if( m_pActorEffects )
{
delete m_pActorEffects;
m_pActorEffects = NULL;
}
}
//=========================================================================
void dead_body::OnKill( void )
{
}
//=========================================================================
void dead_body::OnMove( const vector3& NewPos )
{
// Call base class
object::OnMove( NewPos );
#ifdef X_EDITOR
// If being moved in the editor, re-initialize
if ( (!g_game_running) && (GetAttrBits() & (object::ATTR_EDITOR_SELECTED | object::ATTR_EDITOR_PLACEMENT_OBJECT)) )
InitializeEditorPlaced() ;
#endif // X_EDITOR
// Update zone tracking
g_ZoneMgr.UpdateZoneTracking( *this, m_ZoneTracker, NewPos );
}
//=========================================================================
void dead_body::OnTransform( const matrix4& L2W )
{
// Call base class
object::OnTransform( L2W );
#ifdef X_EDITOR
// If being moved in the editor, re-initialize
if ( (!g_game_running) && (GetAttrBits() & (object::ATTR_EDITOR_SELECTED | object::ATTR_EDITOR_PLACEMENT_OBJECT)) )
InitializeEditorPlaced() ;
#endif // X_EDITOR
// Update zone tracking
g_ZoneMgr.UpdateZoneTracking( *this, m_ZoneTracker, L2W.GetTranslation() );
}
//=========================================================================
bbox dead_body::GetLocalBBox( void ) const
{
return bbox( vector3(-150, -150, -150), vector3(150,150,150) );
}
//===========================================================================
void dead_body::LimitDeadBodyCount( void )
{
// Should only be called when a non-permanent body is created.
ASSERT( !m_bPermanent );
ASSERT( !m_bDestroy );
// Find the oldest non-permanent dead body, and non-permanent count.
dead_body* pOldestDeadBody = NULL;
s32 nDeadBodies = 0;
select_slot_iterator SlotIter;
g_ObjMgr.SelectByAttribute( object::ATTR_ALL, object::TYPE_DEAD_BODY );
for( SlotIter.Begin(); !SlotIter.AtEnd(); SlotIter.Next() )
{
// Get body.
dead_body* pDeadBody = (dead_body*)SlotIter.Get();
ASSERT( pDeadBody );
// Don't consider self.
if( pDeadBody == this )
continue;
// Leave permanent bodies.
if( pDeadBody->m_bPermanent )
continue;
// Skip bodies that have already been flagged to be destroyed.
if( pDeadBody->m_bDestroy )
continue;
// Update count.
nDeadBodies++;
// Is this the oldest? (Or the first to make it this far?)
if( pOldestDeadBody )
{
// Is this the oldest?
if( pDeadBody->m_TimeAlive > pOldestDeadBody->m_TimeAlive )
pOldestDeadBody = pDeadBody;
}
else
{
// First to make it this far.
pOldestDeadBody = pDeadBody;
}
}
SlotIter.End();
// Flag oldest to be deleted if there are too many.
if( nDeadBodies > MAX_DEAD_BODIES )
{
ASSERT( pOldestDeadBody != this );
ASSERT( !pOldestDeadBody->m_bPermanent );
ASSERT( !pOldestDeadBody->m_bDestroy );
pOldestDeadBody->m_bDestroy = TRUE;
}
}
//===========================================================================
xbool dead_body::Initialize( actor& Actor, xbool doBodyFade, actor_effects* pActorEffects )
{
// copy in the actor effects
if( m_pActorEffects )
{
delete m_pActorEffects;
}
m_pActorEffects = pActorEffects;
// Lookup geometry and animation info
skin_inst& SkinInst = Actor.GetSkinInst() ;
const char* pGeomFileName = SkinInst.GetSkinGeomName() ;
const char* pAnimFileName = Actor.GetAnimGroupHandle().GetName() ;
m_bPermanent = !doBodyFade;
// Initialize the ragdoll
if ( !m_Ragdoll.Init( pGeomFileName, pAnimFileName, Actor.GetRagdollType(), GetGuid() ) )
return FALSE;
// Copy all the skin data
GetSkinInst() = Actor.GetSkinInst() ;
// Set the zone info
m_ZoneTracker = Actor.GetZoneTracker();
SetZone1( Actor.GetZone1() ) ;
SetZone2( Actor.GetZone2() ) ;
// Make sure to tell the spatial database where we are
OnTransform( Actor.GetL2W() );
// Copy the time when It was created
m_TimeAlive = 0.0f;
// Copy floor properties
m_FloorProperties = Actor.GetFloorProperties() ;
// Now setup the matrices of the ragdoll from the current animation to inherit velocities
loco* pLoco = Actor.GetLocoPointer() ;
if (pLoco)
m_Ragdoll.SetMatrices(pLoco->m_Player, pLoco->GetDeltaPos()) ;
// Make active
m_bPhysics = TRUE ;
// copy the decal data
m_hBloodDecalPackage.SetName( Actor.GetBloodDecalPackage() );
m_BloodDecalGroup = Actor.GetBloodDecalGroup();
// Delete oldest if too many
if( doBodyFade )
{
LimitDeadBodyCount() ;
}
// Success
return TRUE;
}
//===============================================================================
// NOTE: "LimitDeadBodyCount" is not called when using this initialization function
// (it is only called when creating permanent dead bodies in the editor)
xbool dead_body::Initialize( const char* pGeomName,
const char* pAnimGroupName,
const char* pAnimName,
s32 AnimFrame,
ragdoll::type RagdollType )
{
// Must be valid
if ( (!pGeomName) || (!pAnimGroupName) || (!pAnimName) )
return FALSE;
// Initialize the ragdoll
if ( !m_Ragdoll.Init( pGeomName, pAnimGroupName, RagdollType, GetGuid() ) )
return FALSE;
// Copy the time when It was created
m_TimeAlive = 0.0f;
// Lookup animation group
const anim_group::handle& hAnimGroup = m_Ragdoll.GetAnimGroupHandle() ;
const anim_group* pAnimGroup = hAnimGroup.GetPointer() ;
if (!pAnimGroup)
return FALSE;
// Lookup animation info
s32 nBones = pAnimGroup->GetNBones() ;
s32 iAnim = pAnimGroup->GetAnimIndex( pAnimName ) ;
if ( iAnim == -1 )
return FALSE;
const anim_info& AnimInfo = pAnimGroup->GetAnimInfo( iAnim ) ;
// Clamp frame
s32 LastFrame = x_max(0, AnimInfo.GetNFrames() - 2) ;
if (AnimFrame > LastFrame)
AnimFrame = LastFrame ;
// Allocate temporary memory for keys and matrices
smem_StackPushMarker();
byte* pData = smem_StackAlloc( nBones * ( sizeof(anim_key) + sizeof(matrix4) ) );
if (!pData)
{
smem_StackPopToMarker();
return FALSE;
}
// Setup ptrs
matrix4* pMatrices = (matrix4*)pData;
anim_key* pKeys = (anim_key*)(pData + (nBones * sizeof(matrix4)) );
// Compute matrices
AnimInfo.GetInterpKeys( (f32)AnimFrame, pKeys, nBones );
pAnimGroup->ComputeBonesL2W( GetL2W(), pKeys, nBones, pMatrices, TRUE ) ;
// Finally, setup the ragdoll particles
m_Ragdoll.SetMatrices( pMatrices, nBones );
// Free alloced memory
smem_StackPopToMarker();
// Stop any velocity due to constraints being met
m_Ragdoll.ZeroVelocity() ;
// Success
return TRUE;
}
//===============================================================================
xbool dead_body::InitializeEditorPlaced( void )
{
// Valid?
if ((!GetSkinInst().GetSkinGeomName()) || (!GetSkinInst().GetSkinGeom()) || (m_AnimGroupName == -1) || (m_AnimName == -1))
return FALSE;
// Never delete
m_bPermanent = TRUE ;
// Make sure properties are included in game save/load
SetAttrBits( GetAttrBits() & ~object::ATTR_NO_RUNTIME_SAVE) ;
// Initialize from properties
if ( !Initialize(GetSkinInst().GetSkinGeomName(),
g_StringMgr.GetString(m_AnimGroupName),
g_StringMgr.GetString(m_AnimName),
m_AnimFrame,
m_RagdollType) )
{
return FALSE;
}
// Run the physics to make the ragdoll settle and setup floor color
m_Ragdoll.ZeroDeltaTime() ;
f32 Step = 1.0f / 30.0f ;
for ( f32 Time = 0 ; Time < m_SimulationTime ; Time += Step )
{
m_Ragdoll.Advance( Step ) ;
}
m_Ragdoll.ZeroDeltaTime() ;
// Turn off physics so body is frozen
m_Ragdoll.ZeroVelocity() ;
m_FloorProperties.ForceUpdate(m_Ragdoll.GetCenterPos());
// Success
return TRUE;
}
//===============================================================================
matrix4* dead_body::GetBonesForRender( u64 LODMask, s32& nActiveBones )
{
// Get number of bones to render
nActiveBones = GetSkinInst().GetNActiveBones(LODMask);
// are the current matrices valid?
if ( m_CachedL2Ws.IsValid(nActiveBones) )
return m_CachedL2Ws.GetMatrices();
// allocate room for the new matrices
matrix4* pMatrices = m_CachedL2Ws.GetMatrices(nActiveBones);
// Compute render matrices
if (m_Ragdoll.IsInitialized())
m_Ragdoll.ComputeMatrices(pMatrices, nActiveBones);
else
{
// Ragdoll not present (must be creating a new ragdoll in editor), so just use bind pose
for (s32 i = 0 ; i < nActiveBones ; i++)
pMatrices[i] = GetL2W() ;
}
// the matrices are no longer dirty
m_CachedL2Ws.SetDirty(FALSE);
return m_CachedL2Ws.GetMatrices();
}
//===============================================================================
void dead_body::OnRenderShadowCast( u64 ProjMask )
{
// Geometry present?
skin_geom* pSkinGeom = GetSkinInst().GetSkinGeom() ;
if (!pSkinGeom)
return ;
// Compute LOD mask
u64 LODMask = GetSkinInst().GetLODMask(GetL2W()) ;
if (LODMask == 0)
return;
// Compute LOD mask for the shadow render (by putting zero in for screen size
// we force the lowest lod)
u64 ShadLODMask = GetSkinInst().GetLODMask(0);
if (ShadLODMask == 0)
return ;
// get the matrices
s32 nActiveBones = 0;
matrix4* pMatrices = GetBonesForRender( LODMask|ShadLODMask, nActiveBones );
if ( !pMatrices )
return;
// Setup render flags
u32 Flags = (GetFlagBits() & object::FLAG_CHECK_PLANES) ? render::CLIPPED : 0 ;
// Render that puppy!
GetSkinInst().RenderShadowCast( &GetL2W(),
pMatrices,
nActiveBones,
Flags,
ShadLODMask,
ProjMask ) ;
}
//===============================================================================
void dead_body::OnRender( void )
{
// render any actor effects
if( m_pActorEffects )
m_pActorEffects->Render( this );
// Geometry present?
skin_geom* pSkinGeom = GetSkinInst().GetSkinGeom() ;
if (!pSkinGeom)
return ;
// Compute LOD mask
u64 LODMask = GetSkinInst().GetLODMask(GetL2W()) ;
if (LODMask == 0)
return;
// get the matrices
s32 nActiveBones = 0;
matrix4* pMatrices = GetBonesForRender( LODMask, nActiveBones );
if ( !pMatrices )
return;
// Setup render flags and fill in the fade amount
xcolor Ambient = GetFloorColor();
u32 Flags = (GetFlagBits() & object::FLAG_CHECK_PLANES) ? render::CLIPPED : 0 ;
if ( (!m_bPermanent) && (m_TimeAlive > FADEOUT_START_TIME) )
{
Flags |= render::FADING_ALPHA;
f32 Alpha = 1.0f - ((m_TimeAlive - FADEOUT_START_TIME) / FADEOUT_TIME);
Alpha = MIN( Alpha, 1.0f );
Alpha = MAX( Alpha, 0.0f );
Ambient.A = (u8)(Alpha*255.0f);
}
// Render that puppy!
GetSkinInst().Render( &GetL2W(),
pMatrices,
nActiveBones,
Flags,
LODMask,
Ambient ) ;
}
//===============================================================================
void dead_body::OnRenderTransparent( void )
{
if( m_pActorEffects )
{
f32 Alpha = 1.0f;
if ( (!m_bPermanent) && (m_TimeAlive > FADEOUT_START_TIME) )
{
Alpha = 1.0f - ((m_TimeAlive - FADEOUT_START_TIME) / FADEOUT_TIME);
Alpha = MIN( Alpha, 1.0f );
Alpha = MAX( Alpha, 0.0f );
}
m_pActorEffects->RenderTransparent( this, Alpha );
}
}
//===============================================================================
static f32 RAGDOLL_KINETIC_ENERGY_LIMIT = 1.0f;
static f32 RAGDOLL_NO_ENERGY_TIMEOUT = 1.0f;
void dead_body::OnAdvanceLogic( f32 DeltaTime )
{
CONTEXT( "dead_body::OnAdvanceLogic" );
// If no ragdoll, then delete to stop crashes...
if (!m_Ragdoll.IsInitialized())
{
g_ObjMgr.DestroyObject( GetGuid() );
return;
}
// update any actor effects
if( m_pActorEffects )
m_pActorEffects->Update( this, DeltaTime );
// Flagged to be destroyed?
if (m_bDestroy)
{
ASSERT(!m_bPermanent) ;
g_ObjMgr.DestroyObject( GetGuid() );
return;
}
// Time out and delete his body?
if( (m_bCanDelete) && (!m_bPermanent) && (m_TimeAlive >= (FADEOUT_START_TIME+FADEOUT_TIME)) )
{
g_ObjMgr.DestroyObject( GetGuid() );
return;
}
// Update the timer.
if ( m_bPermanent )
m_TimeAlive = 0.0f;
else
m_TimeAlive += DeltaTime;
// Okay lets assume next time we can be deleted
m_bCanDelete = TRUE;
// mreed: commented this out so the bodies settle faster and there is less processor draw.
// Make characters collide with ragdoll
//m_Ragdoll.ApplyCharacterConstraints() ;
// Has ragdoll stopped moving?
if (m_Ragdoll.GetKineticEnergy() < RAGDOLL_KINETIC_ENERGY_LIMIT)
{
// Increase timer
m_NoEnergyTimer += DeltaTime ;
// Has the ragdoll been idle for over 2 seconds?
if ( m_NoEnergyTimer > RAGDOLL_NO_ENERGY_TIMEOUT )
{
// Stop the physics
m_bPhysics = FALSE;
// Generate the blood pool just once, after the deadbody has stopped..
if (!m_bCreatedBlood)
{
CreateBloodPool();
m_bCreatedBlood = TRUE ;
}
}
}
else
{
// Keep updating
m_NoEnergyTimer = 0 ;
m_bPhysics = TRUE ;
}
// Advance the physics?
if ( m_bPhysics )
m_Ragdoll.Advance(DeltaTime) ;
// Move the object to the new spot
OnMove( m_Ragdoll.GetCenterPos() );
// set up the ambient color for rendering
m_FloorProperties.Update( GetPosition(), DeltaTime );
// since the ragdoll has been updated, the matrices are no longer valid
m_CachedL2Ws.SetDirty(TRUE);
// x_DebugMsg( "Rag: %f\n", m_Ragdoll.GetKineticEnergy() );
}
//===============================================================================
void dead_body::CreateBloodPool( void )
{
// DBS Jan. 7, 04: I think this was meant to a be a blood pool that would
// grow as time went on and possibly animate. It was never implemented
}
//===========================================================================
void dead_body::CreateSplatDecalOnGround( const pain &Pain )
{
(void)Pain;
// create a splat decal on the ground
decal_package* pPackage = m_hBloodDecalPackage.GetPointer();
if ( !pPackage )
return;
if ( (m_BloodDecalGroup<0) || (m_BloodDecalGroup>=pPackage->GetNGroups()) )
return;
s32 nDecalDefs = pPackage->GetNDecalDefs( m_BloodDecalGroup );
if ( nDecalDefs == 0 )
return;
/*
// figure out what size blood we'd like. The group is ordered: sml, med, big, smear, pool
s32 iDecalDef;
f32 Size = 250.0f;
if ( Pain.DamageR0 > 80.0f )
{
iDecalDef = 2;
}
else
{
if ( x_rand() & 1 )
iDecalDef = 1;
else
iDecalDef = 3;
if ( Pain.DamageR0 < 25.0f )
Size = 75.0f;
else
Size = 150.0f;
}
iDecalDef = MIN(nDecalDefs-2, iDecalDef);
Size = x_frand( Size*0.25f, Size );
// figure out a random orientation for the blood splat
radian3 BloodOrient;
BloodOrient.Pitch = x_frand(R_80, R_100);
BloodOrient.Yaw = x_frand(R_0, R_360);
BloodOrient.Roll = R_0;
vector3 RayStart = Pain.PtOfImpact;
RayStart.GetY() += 10.0f;
vector3 RayEnd( 0.0f, 0.0f, 1.0f );
RayEnd.Rotate( BloodOrient );
RayEnd = 40.0f * RayEnd;
RayEnd += RayStart;
// generate the decal
const decal_definition& DecalDef = pPackage->GetDecalDef( m_BloodDecalGroup, iDecalDef );
g_DecalMgr.CreateDecalFromRayCast( DecalDef,
RayStart,
RayEnd,
vector2( Size, Size ),
DecalDef.RandomRoll() );
*/
}
//===============================================================================
void dead_body::OnPain( const pain& Pain )
{
// if we've already starting fading the body out, don't do any more splatting
if ( m_TimeAlive > FADEOUT_START_TIME )
return;
health_handle Handle(GetLogicalName());
Pain.ComputeDamageAndForce( Handle, GetGuid(), GetPosition() );
// Create blood
CreateSplatDecalOnGround(Pain);
// Bring back to life...
m_bCanDelete = FALSE;
m_bPhysics = TRUE;
m_NoEnergyTimer = TRUE;
// Reset creation time so it's put at back of deletion
m_TimeAlive = 0.0f;
// Use the hit_type to determine how to react
switch( Pain.GetHitType() )
{
case 0:
// Small impact like bullets
m_Ragdoll.ApplyBlast( Pain.GetPosition(), Pain.GetDirection(), 60, 1000) ;
particle_emitter::CreateOnPainEffect( Pain, 0, particle_emitter::BLOODY_MESS, FALSE );
break;
case 1:
case 2:
case 3:
// Explosive grenade
m_Ragdoll.ApplyBlast( Pain.GetPosition(), 100.0f, 500.0f );
m_Ragdoll.ApplyBlast( Pain.GetPosition(), vector3(0,1,0), 100.0f, 1000.0f ) ;
break;
case 4:
// Melee
m_Ragdoll.ApplyVectorForce( Pain.GetDirection(), 1000.0f );
particle_emitter::CreateOnPainEffect( Pain, 0, particle_emitter::BLOODY_MESS, FALSE );
break;
}
}
//===============================================================================
void dead_body::OnColCheck( void )
{
// Get moving object
guid MovingGuid = g_CollisionMgr.GetMovingObjGuid() ;
object* pObject = g_ObjMgr.GetObjectByGuid(MovingGuid) ;
#ifdef X_EDITOR
// Allow ragdoll to be selected in the editor?
if (g_CollisionMgr.IsEditorSelectRay())
{
// Use ragdoll if possible
if (m_Ragdoll.IsInitialized())
{
m_Ragdoll.OnColCheck() ;
return ;
}
// Start with object bbox incase geometry is not present
bbox BBox = GetBBox() ;
// Use geometry bbox?
geom* pGeom = GetSkinInst().GetGeom() ;
if (pGeom)
{
BBox = pGeom->m_BBox ;
BBox.Transform(GetL2W()) ;
}
// Apply
g_CollisionMgr.StartApply( GetGuid() ) ;
g_CollisionMgr.ApplyAABBox( BBox ) ;
g_CollisionMgr.EndApply() ;
}
#endif // X_EDITOR
// Only collide with bullets
if ( (pObject) && (pObject->IsKindOf( base_projectile::GetRTTI())) )
{
m_Ragdoll.OnColCheck() ;
}
}
//===============================================================================
void dead_body::ChangeObjectGuid( guid NewGuid )
{
// Update dead body object
g_ObjMgr.ChangeObjectGuid( GetGuid(), NewGuid ) ;
// Update ragdoll so collision works
m_Ragdoll.SetObjectGuid( NewGuid ) ;
}
//===============================================================================
// Editor functions
//===============================================================================
void dead_body::OnEnumProp( prop_enum& List )
{
// Call base class
object::OnEnumProp(List);
// Character properties - lets trigger system check the health
List.PropEnumHeader( "Character", "This is here so you can check the health with triggers", 0 ) ;
List.PropEnumFloat ( "Character\\Health", "This is here so you can check the health with triggers", PROP_TYPE_EXPOSE ) ;
// Dead body
List.PropEnumHeader("DeadBody", "Editor placed ragdoll deadbody", 0 ) ;
// Ragdoll properties
List.PropEnumBool ( "DeadBody\\Physics", "Start with physics active? (FALSE = frozen, TRUE = moving!)\nFor performance try leaving this to FALSE!", PROP_TYPE_MUST_ENUM);
List.PropEnumEnum ( "DeadBody\\RagdollType", ragdoll::s_TypeList.BuildString(), "Type of ragdoll rig to use.", PROP_TYPE_MUST_ENUM);
List.PropEnumFloat ( "DeadBody\\SimulationTime", "Physics time to simulate before level starts.", PROP_TYPE_MUST_ENUM);
// Animation properties
List.PropEnumExternal( "DeadBody\\AnimGroupName", "Resource\0animexternal", "Select the animation group and animation.", PROP_TYPE_MUST_ENUM | PROP_TYPE_EXTERNAL );
List.PropEnumString ( "DeadBody\\AnimName", "Name of the animation to play.", PROP_TYPE_MUST_ENUM);
List.PropEnumInt ( "DeadBody\\AnimFrame", "Frame of animation to start at.", PROP_TYPE_MUST_ENUM);
// Geometry properties
GetSkinInst().OnEnumProp(List);
// Decals
List.PropEnumHeader ( "BloodDecals", "Which blood decals this actor will leave.", 0 );
List.PropEnumExternal( "BloodDecals\\Package", "Decal Resource\0decalpkg\0", "Which blood decal package this actor uses.", 0 );
List.PropEnumInt ( "BloodDecals\\Group", "Within the decal package, which group of bloud this actor uses.", 0 );
}
//===============================================================================
xbool dead_body::OnProperty( prop_query& I )
{
// Call base class
if (object::OnProperty(I))
{
// Initialize zone tracker?
if( I.IsVar( "Base\\Position" ) )
{
g_ZoneMgr.InitZoneTracking( *this, m_ZoneTracker );
}
return TRUE;
}
// Health?
if ( I.IsVar( "Character\\Health" ) )
{
if (I.IsRead())
I.SetVarFloat(0) ;
return TRUE ;
}
// Physics?
if ( I.IsVar( "DeadBody\\Physics" ) )
{
if (I.IsRead())
I.SetVarBool(m_bPhysics) ;
else
m_bPhysics = I.GetVarBool() ;
return TRUE ;
}
// RagdollType?
if( I.IsVar( "DeadBody\\RagdollType" ) )
{
RagdollType_OnProperty( I, m_RagdollType );
#ifdef X_EDITOR
// Re-initialize
if ( !I.IsRead() )
InitializeEditorPlaced() ;
#endif // X_EDITOR
return TRUE;
}
// SimulationTime
if (I.VarFloat( "DeadBody\\SimulationTime", m_SimulationTime, 0.0f, 5.0f ))
{
#ifdef X_EDITOR
// Re-initialize
if ( !I.IsRead() )
InitializeEditorPlaced() ;
#endif // X_EDITOR
return TRUE ;
}
// AnimGroup, AnimName
if( I.IsVar( "DeadBody\\AnimGroupName" ) )
{
if( I.IsRead() )
{
if ( m_AnimGroupName >= 0 )
I.SetVarExternal( g_StringMgr.GetString(m_AnimGroupName), 256 );
else
I.SetVarExternal("", 256);
}
else
{
// Get the FileName
xstring String = I.GetVarExternal();
if( !String.IsEmpty() )
{
s32 PkgIndex = String.Find( '\\', 0 );
if( PkgIndex != -1 )
{
xstring Pkg = String.Left( PkgIndex );
Pkg += "\0\0";
m_AnimName = g_StringMgr.Add( String.Right( String.GetLength() - PkgIndex - 1) );
m_AnimGroupName = g_StringMgr.Add( Pkg );
}
else
{
m_AnimGroupName = g_StringMgr.Add( String );
}
}
#ifdef X_EDITOR
// Re-initialize
InitializeEditorPlaced() ;
#endif // X_EDITOR
}
return TRUE;
}
// AnimName
if (I.IsVar( "DeadBody\\AnimName" ))
{
if( I.IsRead() )
{
if (m_AnimName >= 0)
I.SetVarString( g_StringMgr.GetString(m_AnimName), 256 );
else
I.SetVarString( "", 256);
}
else
{
if (x_strlen(I.GetVarString()) > 0)
m_AnimName = g_StringMgr.Add( I.GetVarString() );
#ifdef X_EDITOR
// Re-initialize
InitializeEditorPlaced() ;
#endif // X_EDITOR
}
return TRUE;
}
// AnimFrame
if (I.VarInt( "DeadBody\\AnimFrame", m_AnimFrame, 0 ))
{
#ifdef X_EDITOR
// Re-initialize
if ( !I.IsRead() )
InitializeEditorPlaced() ;
#endif // X_EDITOR
return TRUE ;
}
// Geometry
if (GetSkinInst().OnProperty(I))
{
#ifdef X_EDITOR
// Re-initialize if geometry is selected
if ( ( !I.IsRead() ) && ( I.IsVar( "RenderInst\\File" ) ) )
InitializeEditorPlaced() ;
#endif // X_EDITOR
return TRUE ;
}
// Decal package
if ( I.IsVar( "BloodDecals\\Package" ) )
{
if ( I.IsRead() )
I.SetVarExternal( m_hBloodDecalPackage.GetName(), RESOURCE_NAME_SIZE );
else
m_hBloodDecalPackage.SetName( I.GetVarExternal() );
return TRUE;
}
// Decal group
if ( I.VarInt( "BloodDecals\\Group", m_BloodDecalGroup ) )
{
return TRUE;
}
return FALSE ;
}
//===============================================================================
| 412 | 0.980893 | 1 | 0.980893 | game-dev | MEDIA | 0.960982 | game-dev | 0.883763 | 1 | 0.883763 |
vicaya/hypertable | 8,273 | src/cc/Common/ScopeGuard.h | /**
* Copyright (C) 2007 Luke Lu (Zvents, Inc.)
*
* This file is part of Hypertable.
*
* Hypertable 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 any later version.
*
* Hypertable 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 Hypertable. If not, see <http://www.gnu.org/licenses/>
*/
// Addapted from http://www.ddj.com/cpp/184403758
#ifndef HT_SCOPEGUARD_H
#define HT_SCOPEGUARD_H
namespace Hypertable {
class ScopeGuardImplBase {
protected:
~ScopeGuardImplBase() { }
ScopeGuardImplBase(const ScopeGuardImplBase& other) throw()
: m_dismissed(other.m_dismissed) {
other.dismiss();
}
template <typename GuardT>
static void safe_run(GuardT& guard) throw() {
if (!guard.m_dismissed) try {
guard.run();
}
catch(...) { }
}
public:
ScopeGuardImplBase() throw() : m_dismissed(false) { }
void dismiss() const throw() { m_dismissed = true; }
private:
ScopeGuardImplBase& operator=(const ScopeGuardImplBase&); // not assignable
mutable bool m_dismissed;
};
/**
* According to the C++ standard, a reference initialized with a temporary
* value makes that temporary value live for the lifetime of the reference
* itself. This can save us from having to explicitly instantiate the guards
* with long type parameters
*/
typedef const ScopeGuardImplBase& ScopeGuard;
/**
* Guard implementation for free function with no paramter
*/
template <typename FunT>
class ScopeGuardImpl0 : public ScopeGuardImplBase {
public:
static ScopeGuardImpl0<FunT> make_guard(FunT fun) {
return ScopeGuardImpl0<FunT>(fun);
}
~ScopeGuardImpl0() throw() { safe_run(*this); }
void run() { m_fun(); }
private:
ScopeGuardImpl0(FunT fun) : m_fun(fun) { }
FunT m_fun;
};
template <typename FunT>
inline ScopeGuardImpl0<FunT> make_guard(FunT fun) {
return ScopeGuardImpl0<FunT>::make_guard(fun);
}
/**
* Guard implementation for free function with 1 parameter
*/
template <typename FunT, typename P1T>
class ScopeGuardImpl1 : public ScopeGuardImplBase {
public:
static ScopeGuardImpl1<FunT, P1T> make_guard(FunT fun, P1T p1) {
return ScopeGuardImpl1<FunT, P1T>(fun, p1);
}
~ScopeGuardImpl1() throw() { safe_run(*this); }
void run() { m_fun(m_p1); }
private:
ScopeGuardImpl1(FunT fun, P1T p1) : m_fun(fun), m_p1(p1) { }
FunT m_fun;
const P1T m_p1;
};
template <typename FunT, typename P1T>
inline ScopeGuardImpl1<FunT, P1T> make_guard(FunT fun, P1T p1) {
return ScopeGuardImpl1<FunT, P1T>::make_guard(fun, p1);
}
/**
* Guard implementation for free function with 2 parameters
*/
template <typename FunT, typename P1T, typename P2T>
class ScopeGuardImpl2: public ScopeGuardImplBase {
public:
static ScopeGuardImpl2<FunT, P1T, P2T> make_guard(FunT fun, P1T p1, P2T p2) {
return ScopeGuardImpl2<FunT, P1T, P2T>(fun, p1, p2);
}
~ScopeGuardImpl2() throw() { safe_run(*this); }
void run() { m_fun(m_p1, m_p2); }
private:
ScopeGuardImpl2(FunT fun, P1T p1, P2T p2) : m_fun(fun), m_p1(p1), m_p2(p2) { }
FunT m_fun;
const P1T m_p1;
const P2T m_p2;
};
template <typename FunT, typename P1T, typename P2T>
inline ScopeGuardImpl2<FunT, P1T, P2T> make_guard(FunT fun, P1T p1, P2T p2) {
return ScopeGuardImpl2<FunT, P1T, P2T>::make_guard(fun, p1, p2);
}
/**
* Guard implementation for free function with 3 parameters
*/
template <typename FunT, typename P1T, typename P2T, typename P3T>
class ScopeGuardImpl3 : public ScopeGuardImplBase {
public:
static ScopeGuardImpl3<FunT, P1T, P2T, P3T>
make_guard(FunT fun, P1T p1, P2T p2, P3T p3) {
return ScopeGuardImpl3<FunT, P1T, P2T, P3T>(fun, p1, p2, p3);
}
~ScopeGuardImpl3() throw() { safe_run(*this); }
void run() { m_fun(m_p1, m_p2, m_p3); }
private:
ScopeGuardImpl3(FunT fun, P1T p1, P2T p2, P3T p3)
: m_fun(fun), m_p1(p1), m_p2(p2), m_p3(p3) { }
FunT m_fun;
const P1T m_p1;
const P2T m_p2;
const P3T m_p3;
};
template <typename FunT, typename P1T, typename P2T, typename P3T>
inline ScopeGuardImpl3<FunT, P1T, P2T, P3T>
make_guard(FunT fun, P1T p1, P2T p2, P3T p3) {
return ScopeGuardImpl3<FunT, P1T, P2T, P3T>::make_guard(fun, p1, p2, p3);
}
/**
* Guard implementation for method with no parameter
*/
template <class ObjT, typename MethodT>
class ObjScopeGuardImpl0 : public ScopeGuardImplBase {
public:
static ObjScopeGuardImpl0<ObjT, MethodT>
make_obj_guard(ObjT &obj, MethodT method) {
return ObjScopeGuardImpl0<ObjT, MethodT>(obj, method);
}
~ObjScopeGuardImpl0() throw() { safe_run(*this); }
void run() { (m_obj.*m_method)(); }
private:
ObjScopeGuardImpl0(ObjT &obj, MethodT method)
: m_obj(obj), m_method(method) { }
ObjT &m_obj;
MethodT m_method;
};
template <class ObjT, typename MethodT>
inline ObjScopeGuardImpl0<ObjT, MethodT>
make_obj_guard(ObjT &obj, MethodT method) {
return ObjScopeGuardImpl0<ObjT, MethodT>::make_obj_guard(obj, method);
}
/**
* Guard implementation for method with 1 parameter
*/
template <class ObjT, typename MethodT, typename P1T>
class ObjScopeGuardImpl1 : public ScopeGuardImplBase {
public:
static ObjScopeGuardImpl1<ObjT, MethodT, P1T>
make_obj_guard(ObjT &obj, MethodT method, P1T p1) {
return ObjScopeGuardImpl1<ObjT, MethodT, P1T>(obj, method, p1);
}
~ObjScopeGuardImpl1() throw() { safe_run(*this); }
void run() { (m_obj.*m_method)(m_p1); }
protected:
ObjScopeGuardImpl1(ObjT &obj, MethodT method, P1T p1)
: m_obj(obj), m_method(method), m_p1(p1) { }
ObjT &m_obj;
MethodT m_method;
const P1T m_p1;
};
template <class ObjT, typename MethodT, typename P1T>
inline ObjScopeGuardImpl1<ObjT, MethodT, P1T>
make_obj_guard(ObjT &obj, MethodT method, P1T p1) {
return ObjScopeGuardImpl1<ObjT, MethodT, P1T>::make_obj_guard(obj, method,
p1);
}
/**
* Guard implementation for method with 2 parameters
*/
template <class ObjT, typename MethodT, typename P1T, typename P2T>
class ObjScopeGuardImpl2 : public ScopeGuardImplBase {
public:
static ObjScopeGuardImpl2<ObjT, MethodT, P1T, P2T>
make_obj_guard(ObjT &obj, MethodT method, P1T p1, P2T p2) {
return ObjScopeGuardImpl2<ObjT, MethodT, P1T, P2T>(obj, method, p1, p2);
}
~ObjScopeGuardImpl2() throw() { safe_run(*this); }
void run() { (m_obj.*m_method)(m_p1, m_p2); }
private:
ObjScopeGuardImpl2(ObjT &obj, MethodT method, P1T p1, P2T p2)
: m_obj(obj), m_method(method), m_p1(p1), m_p2(p2) { }
ObjT &m_obj;
MethodT m_method;
const P1T m_p1;
const P2T m_p2;
};
template <class ObjT, typename MethodT, typename P1T, typename P2T>
inline ObjScopeGuardImpl2<ObjT, MethodT, P1T, P2T>
make_obj_guard(ObjT &obj, MethodT method, P1T p1, P2T p2) {
return ObjScopeGuardImpl2<ObjT, MethodT, P1T, P2T>::make_obj_guard(obj,
method, p1, p2);
}
/**
* Used to pass parameter to the scope guard by reference
* e.g.:
* inline void decr(int &x) { --x; }
*
* void example() {
* int i = 0;
* ScopedGuard guard = make_guard(decr, by_ref(i));
* // ...
* }
*/
template <class T>
class RefHolder {
public:
RefHolder(T& ref) : m_ref(ref) {}
operator T& () const { return m_ref; }
private:
RefHolder& operator=(const RefHolder&); // not assignable
T& m_ref;
};
template <class T>
inline RefHolder<T> by_ref(T& t) {
return RefHolder<T>(t);
}
} // namespace Hypertable
// The two level macros are needed for var<lineno>.
// Otherwise, it'd be literally var__LINE__
#define HT_CONCAT_(s1, s2) s1##s2
#define HT_CONCAT(s1, s2) HT_CONCAT_(s1, s2)
#define HT_AUTO_VAR(var) HT_CONCAT(var, __LINE__)
#define HT_ON_SCOPE_EXIT(...) \
ScopeGuard HT_AUTO_VAR(guard) = make_guard(__VA_ARGS__); \
HT_UNUSED(HT_AUTO_VAR(guard))
#define HT_ON_OBJ_SCOPE_EXIT(...) \
ScopeGuard HT_AUTO_VAR(guard) = make_obj_guard(__VA_ARGS__); \
HT_UNUSED(HT_AUTO_VAR(guard))
#endif //HT_SCOPEGUARD_H
| 412 | 0.85715 | 1 | 0.85715 | game-dev | MEDIA | 0.202982 | game-dev | 0.808425 | 1 | 0.808425 |
wolf-plugins/wolf-shaper | 1,155 | src/Structures/ObjectPool.hpp | #include "Stack.hpp"
#ifndef WOLF_OBJECT_POOL_H_INCLUDED
#define WOLF_OBJECT_POOL_H_INCLUDED
START_NAMESPACE_DISTRHO
namespace wolf
{
template <class T>
class ObjectPool
{
public:
template <typename... Args>
ObjectPool(int numberOfObjects, Args &&...args);
~ObjectPool();
T *getObject();
void freeObject(T *object);
int numberObjectsLeft();
private:
wolf::Stack<T *> objects;
};
template <class T>
template <typename... Args>
ObjectPool<T>::ObjectPool(int numberOfObjects, Args &&...args)
: objects(numberOfObjects)
{
for (int i = 0; i < objects.getSize(); ++i)
{
this->objects.push(new T(args...));
}
}
template <class T>
ObjectPool<T>::~ObjectPool()
{
while (objects.getCount() > 0)
{
delete this->objects.pop();
}
}
template <class T>
T *ObjectPool<T>::getObject()
{
return this->objects.pop();
}
template <class T>
void ObjectPool<T>::freeObject(T *object)
{
object->reset();
this->objects.push(object);
}
template <class T>
int ObjectPool<T>::numberObjectsLeft()
{
return this->objects.getCount();
}
} // namespace wolf
END_NAMESPACE_DISTRHO
#endif | 412 | 0.812299 | 1 | 0.812299 | game-dev | MEDIA | 0.284202 | game-dev | 0.760368 | 1 | 0.760368 |
jMonkeyEngine/jmonkeyengine | 7,671 | jme3-core/src/main/java/com/jme3/anim/ArmatureMask.java | /*
* Copyright (c) 2009-2023 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.anim;
import com.jme3.export.InputCapsule;
import com.jme3.export.JmeExporter;
import com.jme3.export.JmeImporter;
import com.jme3.export.OutputCapsule;
import com.jme3.export.Savable;
import java.io.IOException;
import java.util.BitSet;
/**
* An AnimationMask to select joints from a single Armature.
*/
public class ArmatureMask implements AnimationMask, Savable {
private BitSet affectedJoints = new BitSet();
/**
* Instantiate a mask that affects no joints.
*/
public ArmatureMask() {
// do nothing
}
/**
* Instantiate a mask that affects all joints in the specified Armature.
*
* @param armature the Armature containing the joints (not null, unaffected)
*/
public ArmatureMask(Armature armature) {
int numJoints = armature.getJointCount();
affectedJoints.set(0, numJoints);
}
/**
* Remove all joints affected by the specified ArmatureMask.
*
* @param removeMask the set of joints to remove (not null, unaffected)
* @return this
*/
public ArmatureMask remove(ArmatureMask removeMask) {
BitSet removeBits = removeMask.getAffectedJoints();
affectedJoints.andNot(removeBits);
return this;
}
private BitSet getAffectedJoints() {
return affectedJoints;
}
/**
* Remove the named joints.
*
* @param armature the Armature containing the joints (not null, unaffected)
* @param jointNames the names of the joints to be removed
* @return this
*
* @throws IllegalArgumentException if it can not find the joint
* with the specified name on the provided armature
*/
public ArmatureMask removeJoints(Armature armature, String... jointNames) {
for (String jointName : jointNames) {
Joint joint = findJoint(armature, jointName);
int jointId = joint.getId();
affectedJoints.clear(jointId);
}
return this;
}
@Override
public boolean contains(Object target) {
return affectedJoints.get(((Joint) target).getId());
}
/**
* Create an ArmatureMask that selects the named Joint and all its
* descendants.
*
* @param armature the Armature containing the joints (not null)
* @param fromJoint the name of the ancestor joint
* @return a new mask
*
* @throws IllegalArgumentException if it can not find the joint
* with the specified name on the provided armature
*/
public static ArmatureMask createMask(Armature armature, String fromJoint) {
ArmatureMask mask = new ArmatureMask();
mask.addFromJoint(armature, fromJoint);
return mask;
}
/**
* Create an ArmatureMask that selects the named joints.
*
* @param armature the Armature containing the joints (not null)
* @param joints the names of the joints to be included
* @return a new mask
*
* @throws IllegalArgumentException if it can not find the joint
* with the specified name on the provided armature
*/
public static ArmatureMask createMask(Armature armature, String... joints) {
ArmatureMask mask = new ArmatureMask();
mask.addBones(armature, joints);
return mask;
}
/**
* Add joints to be influenced by this animation mask.
*
* @param armature the Armature containing the joints
* @param jointNames the names of the joints to be influenced
*
* @throws IllegalArgumentException if it can not find the joint
* with the specified name on the provided armature
*/
public void addBones(Armature armature, String... jointNames) {
for (String jointName : jointNames) {
Joint joint = findJoint(armature, jointName);
affectedJoints.set(joint.getId());
}
}
private Joint findJoint(Armature armature, String jointName) {
Joint joint = armature.getJoint(jointName);
if (joint == null) {
throw new IllegalArgumentException("Cannot find joint " + jointName);
}
return joint;
}
/**
* Add a joint and all its sub armature joints to be influenced by this animation mask.
*
* @param armature the Armature containing the ancestor joint
* @param jointName the names of the ancestor joint
*
* @throws IllegalArgumentException if it can not find the joint
* with the specified name on the provided armature
*/
public void addFromJoint(Armature armature, String jointName) {
Joint joint = findJoint(armature, jointName);
recurseAddJoint(joint);
}
private void recurseAddJoint(Joint joint) {
affectedJoints.set(joint.getId());
for (Joint j : joint.getChildren()) {
recurseAddJoint(j);
}
}
/**
* Add the specified Joint and all its ancestors.
*
* @param start the starting point (may be null, unaffected)
* @return this
*/
public ArmatureMask addAncestors(Joint start) {
for (Joint cur = start; cur != null; cur = cur.getParent()) {
int jointId = cur.getId();
affectedJoints.set(jointId);
}
return this;
}
/**
* Remove the specified Joint and all its ancestors.
*
* @param start the starting point (may be null, unaffected)
* @return this
*/
public ArmatureMask removeAncestors(Joint start) {
for (Joint cur = start; cur != null; cur = cur.getParent()) {
int jointId = cur.getId();
affectedJoints.clear(jointId);
}
return this;
}
@Override
public void write(JmeExporter ex) throws IOException {
OutputCapsule oc = ex.getCapsule(this);
oc.write(affectedJoints, "affectedJoints", null);
}
@Override
public void read(JmeImporter im) throws IOException {
InputCapsule ic = im.getCapsule(this);
affectedJoints = ic.readBitSet("affectedJoints", null);
}
}
| 412 | 0.688514 | 1 | 0.688514 | game-dev | MEDIA | 0.37268 | game-dev | 0.80255 | 1 | 0.80255 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.