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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Pugstorm/CoreKeeperModSDK | 2,002 | Packages/com.unity.entities/Unity.Entities.Hybrid/Iterators/TransformAccessArrayIterator.cs | using System;
using System.Linq;
using System.Reflection;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine;
using UnityEngine.Jobs;
using UnityEngine.Scripting;
namespace Unity.Entities
{
class TransformAccessArrayState : IDisposable
{
public TransformAccessArray Data;
public int OrderVersion;
public void Dispose()
{
if (Data.isCreated)
Data.Dispose();
}
}
/// <summary>
/// Allows access to GameObject transform data through an EntityQuery.
/// </summary>
public static class EntityQueryExtensionsForTransformAccessArray
{
/// <summary>
/// Allows access to GameObject transform data through an EntityQuery.
/// </summary>
/// <param name="query">The query matching entities whose transform data should be gathered</param>
/// <returns>An object that allows access to entity transform data</returns>
public static unsafe TransformAccessArray GetTransformAccessArray(this EntityQuery query)
{
var state = (TransformAccessArrayState)query._CachedState;
if (state == null)
state = new TransformAccessArrayState();
var orderVersion = query._GetImpl()->_Access->EntityComponentStore->GetComponentTypeOrderVersion(TypeManager.GetTypeIndex<Transform>());
if (state.Data.isCreated && orderVersion == state.OrderVersion)
return state.Data;
state.OrderVersion = orderVersion;
UnityEngine.Profiling.Profiler.BeginSample("DirtyTransformAccessArrayUpdate");
var trans = query.ToComponentArray<Transform>();
if (!state.Data.isCreated)
state.Data = new TransformAccessArray(trans);
else
state.Data.SetTransforms(trans);
UnityEngine.Profiling.Profiler.EndSample();
query._CachedState = state;
return state.Data;
}
}
}
| 412 | 0.854131 | 1 | 0.854131 | game-dev | MEDIA | 0.623539 | game-dev | 0.786416 | 1 | 0.786416 |
LostCityRS/Content | 2,252 | scripts/levelrequire/scripts/tier20.rs2 | // Melee
[opheld2,mithril_dagger] @levelrequire_attack(20, last_slot);
[opheld2,mithril_dagger_p] @levelrequire_attack(20, last_slot);
[opheld2,mithril_axe] @levelrequire_attack(20, last_slot);
[opheld2,mithril_pickaxe] @levelrequire_attack(20, last_slot);
[opheld2,mithril_mace] @levelrequire_attack(20, last_slot);
[opheld2,mithril_sword] @levelrequire_attack(20, last_slot);
[opheld2,mithril_scimitar] @levelrequire_attack(20, last_slot);
[opheld2,mithril_longsword] @levelrequire_attack(20, last_slot);
[opheld2,mithril_warhammer] @levelrequire_attack(20, last_slot);
[opheld2,mithril_battleaxe] @levelrequire_attack(20, last_slot);
[opheld2,mithril_spear] @levelrequire_attack(20, last_slot);
[opheld2,mithril_spear_p] @levelrequire_attack(20, last_slot);
[opheld2,mithril_2h_sword] @levelrequire_attack(20, last_slot);
[opheld2,excalibur] @levelrequire_attack(20, last_slot);
[opheld2,mithril_med_helm] @levelrequire_defence(20, last_slot);
[opheld2,mithril_full_helm] @levelrequire_defence(20, last_slot);
[opheld2,mithril_sq_shield] @levelrequire_defence(20, last_slot);
[opheld2,mithril_kiteshield] @levelrequire_defence(20, last_slot);
[opheld2,mithril_platelegs] @levelrequire_defence(20, last_slot);
[opheld2,mithril_plateskirt] @levelrequire_defence(20, last_slot);
[opheld2,mithril_chainbody] @levelrequire_defence(20, last_slot);
[opheld2,mithril_platebody] @levelrequire_defence(20, last_slot);
// Ranged
[opheld2,willow_longbow] @levelrequire_ranged(20, last_slot);
[opheld2,willow_shortbow] @levelrequire_ranged(20, last_slot);
[opheld2,coif] @levelrequire_ranged(20, last_slot);
[opheld2,studded_body] @levelrequire_ranged_and_defence(20, 20, last_slot);
[opheld2,studded_chaps] @levelrequire_ranged_lower(20, last_slot);
[opheld2,mithril_dart] @levelrequire_ranged(20, last_slot);
[opheld2,mithril_dart_p] @levelrequire_ranged(20, last_slot);
[opheld2,mithril_knife] @levelrequire_ranged(20, last_slot);
[opheld2,mithril_knife_p] @levelrequire_ranged(20, last_slot);
[opheld2,mithril_thrownaxe] @levelrequire_ranged(20, last_slot);
[opheld2,mithril_javelin] @levelrequire_ranged(20, last_slot);
[opheld2,mithril_javelin_p] @levelrequire_ranged(20, last_slot);
// Magic
[opheld2,boots_wizard] @levelrequire_magic(20, last_slot);
| 412 | 0.818797 | 1 | 0.818797 | game-dev | MEDIA | 0.989903 | game-dev | 0.685195 | 1 | 0.685195 |
elefant-ai/chatclef | 1,218 | src/main/java/adris/altoclef/tasks/resources/CraftWithMatchingWoolTask.java | package adris.altoclef.tasks.resources;
import adris.altoclef.util.CraftingRecipe;
import adris.altoclef.util.ItemTarget;
import adris.altoclef.util.helpers.ItemHelper;
import net.minecraft.item.Item;
import java.util.function.Function;
public abstract class CraftWithMatchingWoolTask extends CraftWithMatchingMaterialsTask {
private final Function<ItemHelper.ColorfulItems, Item> getMajorityMaterial;
private final Function<ItemHelper.ColorfulItems, Item> getTargetItem;
public CraftWithMatchingWoolTask(ItemTarget target, Function<ItemHelper.ColorfulItems, Item> getMajorityMaterial, Function<ItemHelper.ColorfulItems, Item> getTargetItem, CraftingRecipe recipe, boolean[] sameMask) {
super(target, recipe, sameMask);
this.getMajorityMaterial = getMajorityMaterial;
this.getTargetItem = getTargetItem;
}
@Override
protected Item getSpecificItemCorrespondingToMajorityResource(Item majority) {
for (ItemHelper.ColorfulItems colorfulItem : ItemHelper.getColorfulItems()) {
if (getMajorityMaterial.apply(colorfulItem) == majority) {
return getTargetItem.apply(colorfulItem);
}
}
return null;
}
}
| 412 | 0.820288 | 1 | 0.820288 | game-dev | MEDIA | 0.889648 | game-dev | 0.898735 | 1 | 0.898735 |
data2viz/data2viz | 3,522 | shape/src/commonMain/kotlin/io/data2viz/shape/curve/CatmullRomOpen.kt | /*
* Copyright (c) 2018-2021. data2viz sàrl.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.data2viz.shape.curve
import io.data2viz.geom.Path
import io.data2viz.shape.Curve
import io.data2viz.shape.epsilon
import kotlin.math.pow
import kotlin.math.sqrt
public class CatmullRomOpen(
override val path: Path,
public val alpha: Double = 0.5) : Curve {
private var x0 = -1.0
private var y0 = -1.0
private var x1 = -1.0
private var y1 = -1.0
private var x2 = -1.0
private var y2 = -1.0
private var _l01_a = 0.0
private var _l12_a = 0.0
private var _l23_a = 0.0
private var _l01_2a = 0.0
private var _l12_2a = 0.0
private var _l23_2a = 0.0
private var lineStatus = -1
private var pointStatus = -1
override fun areaStart() {
lineStatus = 0
}
override fun areaEnd() {
lineStatus = -1
}
override fun lineStart() {
x0 = -1.0
y0 = -1.0
x1 = -1.0
y1 = -1.0
x2 = -1.0
y2 = -1.0
_l01_a = 0.0
_l12_a = 0.0
_l23_a = 0.0
_l01_2a = 0.0
_l12_2a = 0.0
_l23_2a = 0.0
pointStatus = 0
}
override fun lineEnd() {
if (lineStatus > -1) {
if (lineStatus > 0) {
path.closePath()
}
lineStatus = 1 - lineStatus
}
}
// TODO : inherit from CatmullRom
private fun curve(x: Double, y: Double) {
var _x1 = x1
var _y1 = y1
var _x2 = x2
var _y2 = y2
if (_l01_a > epsilon) {
val a = 2 * _l01_2a + 3 * _l01_a * _l12_a + _l12_2a
val n = 3 * _l01_a * (_l01_a + _l12_a)
_x1 = (x1 * a - x0 * _l12_2a + x2 * _l01_2a) / n
_y1 = (y1 * a - y0 * _l12_2a + y2 * _l01_2a) / n
}
if (_l23_a > epsilon) {
val b = 2 * _l23_2a + 3 * _l23_a * _l12_a + _l12_2a
val m = 3 * _l23_a * (_l23_a + _l12_a)
_x2 = (x2 * b + x1 * _l23_2a - x * _l12_2a) / m
_y2 = (y2 * b + y1 * _l23_2a - y * _l12_2a) / m
}
path.bezierCurveTo(_x1, _y1, _x2, _y2, x2, y2)
}
override fun point(x: Double, y: Double) {
if (pointStatus > 0) {
val x23 = x2 - x
val y23 = y2 - y
_l23_2a = (x23 * x23 + y23 * y23).pow(alpha)
_l23_a = sqrt(_l23_2a)
}
when (pointStatus) {
0 -> pointStatus = 1
1 -> pointStatus = 2
2 -> {
pointStatus = 3
if (lineStatus > 0) path.lineTo(x2, y2) else path.moveTo(x2, y2)
}
3 -> {
pointStatus = 4
curve(x, y)
}
else -> curve(x, y)
}
_l01_a = _l12_a
_l12_a = _l23_a
_l01_2a = _l12_2a
_l12_2a = _l23_2a
x0 = x1
x1 = x2
x2 = x
y0 = y1
y1 = y2
y2 = y
}
}
| 412 | 0.716689 | 1 | 0.716689 | game-dev | MEDIA | 0.500437 | game-dev | 0.809606 | 1 | 0.809606 |
ratrecommends/dice-heroes | 5,170 | main/src/com/vlaaad/dice/game/world/players/Player.java | /*
* Dice heroes is a turn based rpg-strategy game where characters are dice.
* Copyright (C) 2016 Vladislav Protsenko
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.vlaaad.dice.game.world.players;
import com.badlogic.gdx.utils.ObjectIntMap;
import com.badlogic.gdx.utils.ObjectMap;
import com.badlogic.gdx.utils.ObjectSet;
import com.vlaaad.dice.game.config.abilities.Ability;
import com.vlaaad.dice.game.config.items.Item;
import com.vlaaad.dice.game.objects.Creature;
import com.vlaaad.dice.game.user.Die;
import com.vlaaad.dice.game.world.players.tutorial.TutorialProvider;
/**
* Created 08.07.14 by vlaaad
*/
public class Player {
public final Fraction fraction;
private final ObjectMap<Fraction, FractionRelation> relations;
public final ObjectIntMap<Ability> potions = new ObjectIntMap<Ability>();
public final ObjectIntMap<Item> earnedItems = new ObjectIntMap<Item>();
public final ObjectSet<Creature> creatures = new ObjectSet<Creature>();
public final ObjectSet<Die> dice = new ObjectSet<Die>();
public final ObjectIntMap<Ability> usedPotions = new ObjectIntMap<Ability>();
public TutorialProvider tutorialProvider = TutorialProvider.NO_TUTORIALS;
private int nextSummonedId = 10000000;
/**
* @param relations map like (enemy -> enemy, strangers -> ally). Must contain relations for any other fraction.
*/
public Player(Fraction fraction, ObjectMap<Fraction, FractionRelation> relations) {
this.fraction = fraction;
this.relations = relations;
}
public Creature addCreature(Die die) {
Creature creature = new Creature(die, this);
addCreature(creature);
return creature;
}
public void addDie(Die die) {
dice.add(die);
}
public void addCreature(Creature creature) {
creatures.add(creature);
}
public FractionRelation getFractionRelation(Player that) {
if (this == that)
return FractionRelation.ally;
FractionRelation res = relations.get(that.fraction);
if (res == null)
throw new IllegalStateException("undefined relation between " + this + " and " + that + ": " + relations);
return res;
}
/**
* @return self, ally or enemy
*/
public PlayerRelation getPlayerRelation(Player that) {
if (this == that)
return PlayerRelation.self;
return relations.get(that.fraction) == FractionRelation.ally ? PlayerRelation.ally : PlayerRelation.enemy;
}
public boolean inRelation(Player that, PlayerRelation relation) {
switch (relation) {
case any:
return true;
case none:
return false;
case self:
return this == that;
case allyOrEnemy:
return this != that;
case ally:
return this != that && relations.get(that.fraction) == FractionRelation.ally;
case enemy:
return this != that && relations.get(that.fraction) == FractionRelation.enemy;
case allyOrSelf:
return this == that || relations.get(that.fraction) == FractionRelation.ally;
case enemyOrSelf:
return this == that || relations.get(that.fraction) == FractionRelation.enemy;
default:
throw new IllegalArgumentException("unknown relation: " + relation);
}
}
public void setPotions(ObjectIntMap<Ability> potions) {
this.potions.putAll(potions);
}
public void earn(ObjectIntMap<Item> items) {
for (Item item : items.keys()) {
earnedItems.getAndIncrement(item, 0, items.get(item, 0));
}
}
public Iterable<? extends Ability> potions() {
return potions.keys();
}
public int getPotionCount(Ability potion) {
return potions.get(potion, 0);
}
public boolean hasPotions() { return potions.size > 0; }
public void onUsePotion(Ability potion) {
potions.getAndIncrement(potion, 0, -1);
usedPotions.getAndIncrement(potion, 0, 1);
int count = potions.get(potion, 0);
if (count == 0) {
potions.remove(potion, 0);
} else if (count < 0) {
throw new IllegalStateException("no more potions!");
}
}
@Override public String toString() {
return "@" + fraction.toString() + "#" + Integer.toHexString(hashCode());
}
public int nextSummonedId() {
return nextSummonedId++;
}
}
| 412 | 0.908248 | 1 | 0.908248 | game-dev | MEDIA | 0.976305 | game-dev | 0.977008 | 1 | 0.977008 |
DeltaV-Station/Delta-v | 9,181 | Content.Shared/Projectiles/SharedProjectileSystem.cs | using System.Numerics;
using Content.Shared.CombatMode.Pacification;
using Content.Shared.Damage;
using Content.Shared.DoAfter;
using Content.Shared.Hands.EntitySystems;
using Content.Shared.Interaction;
using Content.Shared.Inventory;
using Content.Shared.Mobs.Components;
using Content.Shared.Throwing;
using Robust.Shared.Audio.Systems;
using Robust.Shared.Map;
using Robust.Shared.Network;
using Robust.Shared.Physics;
using Robust.Shared.Physics.Components;
using Robust.Shared.Physics.Dynamics;
using Robust.Shared.Physics.Events;
using Robust.Shared.Physics.Systems;
using Robust.Shared.Serialization;
using Robust.Shared.Utility;
namespace Content.Shared.Projectiles;
public abstract partial class SharedProjectileSystem : EntitySystem
{
public const string ProjectileFixture = "projectile";
[Dependency] private readonly INetManager _net = default!;
[Dependency] private readonly SharedAudioSystem _audio = default!;
[Dependency] private readonly SharedDoAfterSystem _doAfter = default!;
[Dependency] private readonly SharedHandsSystem _hands = default!;
[Dependency] private readonly SharedPhysicsSystem _physics = default!;
[Dependency] private readonly SharedTransformSystem _transform = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<ProjectileComponent, PreventCollideEvent>(PreventCollision);
SubscribeLocalEvent<EmbeddableProjectileComponent, ProjectileHitEvent>(OnEmbedProjectileHit);
SubscribeLocalEvent<EmbeddableProjectileComponent, ThrowDoHitEvent>(OnEmbedThrowDoHit);
SubscribeLocalEvent<EmbeddableProjectileComponent, ActivateInWorldEvent>(OnEmbedActivate);
SubscribeLocalEvent<EmbeddableProjectileComponent, RemoveEmbeddedProjectileEvent>(OnEmbedRemove);
SubscribeLocalEvent<EmbeddableProjectileComponent, ComponentShutdown>(OnEmbeddableCompShutdown);
SubscribeLocalEvent<EmbeddedContainerComponent, EntityTerminatingEvent>(OnEmbeddableTermination);
}
private void OnEmbedActivate(Entity<EmbeddableProjectileComponent> embeddable, ref ActivateInWorldEvent args)
{
// Unremovable embeddables moment
if (embeddable.Comp.RemovalTime == null)
return;
if (args.Handled || !args.Complex || !TryComp<PhysicsComponent>(embeddable, out var physics) ||
physics.BodyType != BodyType.Static)
return;
args.Handled = true;
_doAfter.TryStartDoAfter(new DoAfterArgs(EntityManager,
args.User,
embeddable.Comp.RemovalTime.Value,
new RemoveEmbeddedProjectileEvent(),
eventTarget: embeddable,
target: embeddable));
}
private void OnEmbedRemove(Entity<EmbeddableProjectileComponent> embeddable, ref RemoveEmbeddedProjectileEvent args)
{
if (args.Cancelled)
return;
EmbedDetach(embeddable, embeddable.Comp, args.User);
// try place it in the user's hand
_hands.TryPickupAnyHand(args.User, embeddable);
}
private void OnEmbeddableCompShutdown(Entity<EmbeddableProjectileComponent> embeddable, ref ComponentShutdown arg)
{
EmbedDetach(embeddable, embeddable.Comp);
}
private void OnEmbedThrowDoHit(Entity<EmbeddableProjectileComponent> embeddable, ref ThrowDoHitEvent args)
{
if (!embeddable.Comp.EmbedOnThrow)
return;
EmbedAttach(embeddable, args.Target, null, embeddable.Comp);
}
private void OnEmbedProjectileHit(Entity<EmbeddableProjectileComponent> embeddable, ref ProjectileHitEvent args)
{
EmbedAttach(embeddable, args.Target, args.Shooter, embeddable.Comp);
// Raise a specific event for projectiles.
if (TryComp(embeddable, out ProjectileComponent? projectile))
{
var ev = new ProjectileEmbedEvent(projectile.Shooter!.Value, projectile.Weapon!.Value, args.Target);
RaiseLocalEvent(embeddable, ref ev);
}
}
private void EmbedAttach(EntityUid uid, EntityUid target, EntityUid? user, EmbeddableProjectileComponent component)
{
TryComp<PhysicsComponent>(uid, out var physics);
_physics.SetLinearVelocity(uid, Vector2.Zero, body: physics);
_physics.SetBodyType(uid, BodyType.Static, body: physics);
var xform = Transform(uid);
_transform.SetParent(uid, xform, target);
if (component.Offset != Vector2.Zero)
{
var rotation = xform.LocalRotation;
if (TryComp<ThrowingAngleComponent>(uid, out var throwingAngleComp))
rotation += throwingAngleComp.Angle;
_transform.SetLocalPosition(uid, xform.LocalPosition + rotation.RotateVec(component.Offset), xform);
}
_audio.PlayPredicted(component.Sound, uid, null);
component.EmbeddedIntoUid = target;
var ev = new EmbedEvent(user, target);
RaiseLocalEvent(uid, ref ev);
Dirty(uid, component);
EnsureComp<EmbeddedContainerComponent>(target, out var embeddedContainer);
//Assert that this entity not embed
DebugTools.AssertEqual(embeddedContainer.EmbeddedObjects.Contains(uid), false);
embeddedContainer.EmbeddedObjects.Add(uid);
}
public void EmbedDetach(EntityUid uid, EmbeddableProjectileComponent? component, EntityUid? user = null)
{
if (!Resolve(uid, ref component))
return;
if (component.EmbeddedIntoUid is not null)
{
if (TryComp<EmbeddedContainerComponent>(component.EmbeddedIntoUid.Value, out var embeddedContainer))
{
embeddedContainer.EmbeddedObjects.Remove(uid);
Dirty(component.EmbeddedIntoUid.Value, embeddedContainer);
if (embeddedContainer.EmbeddedObjects.Count == 0)
RemCompDeferred<EmbeddedContainerComponent>(component.EmbeddedIntoUid.Value);
}
}
if (component.DeleteOnRemove && _net.IsServer)
{
QueueDel(uid);
return;
}
var xform = Transform(uid);
if (TerminatingOrDeleted(xform.GridUid) && TerminatingOrDeleted(xform.MapUid))
return;
TryComp<PhysicsComponent>(uid, out var physics);
_physics.SetBodyType(uid, BodyType.Dynamic, body: physics, xform: xform);
_transform.AttachToGridOrMap(uid, xform);
component.EmbeddedIntoUid = null;
Dirty(uid, component);
// Reset whether the projectile has damaged anything if it successfully was removed
if (TryComp<ProjectileComponent>(uid, out var projectile))
{
projectile.Shooter = null;
projectile.Weapon = null;
projectile.ProjectileSpent = false;
Dirty(uid, projectile);
}
if (user != null)
{
// Land it just coz uhhh yeah
var landEv = new LandEvent(user, true);
RaiseLocalEvent(uid, ref landEv);
}
_physics.WakeBody(uid, body: physics);
}
private void OnEmbeddableTermination(Entity<EmbeddedContainerComponent> container, ref EntityTerminatingEvent args)
{
DetachAllEmbedded(container);
}
public void DetachAllEmbedded(Entity<EmbeddedContainerComponent> container)
{
foreach (var embedded in container.Comp.EmbeddedObjects)
{
if (!TryComp<EmbeddableProjectileComponent>(embedded, out var embeddedComp))
continue;
EmbedDetach(embedded, embeddedComp);
}
}
private void PreventCollision(EntityUid uid, ProjectileComponent component, ref PreventCollideEvent args)
{
if (component.IgnoreShooter && (args.OtherEntity == component.Shooter || args.OtherEntity == component.Weapon))
{
args.Cancelled = true;
}
}
public void SetShooter(EntityUid id, ProjectileComponent component, EntityUid shooterId)
{
if (component.Shooter == shooterId)
return;
component.Shooter = shooterId;
Dirty(id, component);
}
[Serializable, NetSerializable]
private sealed partial class RemoveEmbeddedProjectileEvent : DoAfterEvent
{
public override DoAfterEvent Clone() => this;
}
}
[Serializable, NetSerializable]
public sealed class ImpactEffectEvent : EntityEventArgs
{
public string Prototype;
public NetCoordinates Coordinates;
public ImpactEffectEvent(string prototype, NetCoordinates coordinates)
{
Prototype = prototype;
Coordinates = coordinates;
}
}
/// <summary>
/// Raised when an entity is just about to be hit with a projectile but can reflect it
/// </summary>
[ByRefEvent]
public record struct ProjectileReflectAttemptEvent(EntityUid ProjUid, ProjectileComponent Component, bool Cancelled) : IInventoryRelayEvent
{
SlotFlags IInventoryRelayEvent.TargetSlots => SlotFlags.WITHOUT_POCKET;
}
/// <summary>
/// Raised when a projectile hits an entity
/// </summary>
[ByRefEvent]
public record struct ProjectileHitEvent(DamageSpecifier Damage, EntityUid Target, EntityUid? Shooter = null);
| 412 | 0.838904 | 1 | 0.838904 | game-dev | MEDIA | 0.942285 | game-dev | 0.829568 | 1 | 0.829568 |
haiku/haiku | 1,091 | src/add-ons/print/drivers/gutenprint/GPArray.cpp | /*
* Copyright 2010, Haiku. All rights reserved.
* Distributed under the terms of the MIT License.
*
* Authors:
* Michael Pfeiffer
*/
#include<Debug.h>
template<typename TYPE>
GPArray<TYPE>::GPArray()
:
fArray(NULL),
fSize(0)
{
}
template<typename TYPE>
GPArray<TYPE>::~GPArray()
{
if (fArray != NULL) {
for (int i = 0; i < fSize; i ++)
delete fArray[i];
delete[] fArray;
fArray = NULL;
}
}
template<typename TYPE>
void
GPArray<TYPE>::SetSize(int size)
{
ASSERT(fSize == 0);
fArray = new PointerType[size];
if (fArray == NULL)
return;
fSize = size;
for (int i = 0; i < size; i ++) {
fArray[i] = NULL;
}
}
template<typename TYPE>
int
GPArray<TYPE>::Size() const
{
return fSize;
}
template<typename TYPE>
void
GPArray<TYPE>::DecreaseSize()
{
ASSERT(fArray != NULL);
ASSERT(fArray[fSize-1] == NULL);
fSize --;
}
template<typename TYPE>
TYPE**
GPArray<TYPE>::Array()
{
return fArray;
}
template<typename TYPE>
TYPE **
GPArray<TYPE>::Array() const
{
return fArray;
}
template<typename TYPE>
bool
GPArray<TYPE>::IsEmpty() const
{
return fSize == 0;
}
| 412 | 0.925607 | 1 | 0.925607 | game-dev | MEDIA | 0.268889 | game-dev | 0.974808 | 1 | 0.974808 |
wanglin2/lx-doc | 18,094 | flowchart/src/main/webapp/js/diagramly/DistanceGuides.js | /**
* Copyright (c) 2017, CTI LOGIC
* Copyright (c) 2006-2017, JGraph Ltd
* Copyright (c) 2006-2017, Gaudenz Alder
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. Neither the name of the copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//TODO integrate this code in mxGuide (Especially as this is now affecting the other guides)
(function()
{
var guideMove = mxGuide.prototype.move;
mxGuide.prototype.move = function (bounds, delta, gridEnabled, clone)
{
var yShift = delta.y;
var xShift = delta.x;
var hasHorGuides = false;
var hasVerGuides = false;
if (this.states != null && bounds != null && delta != null)
{
var guide = this;
var newState = new mxCellState();
var scale = this.graph.getView().scale;
var tolerance = Math.max(2, this.getGuideTolerance() / 2);
newState.x = bounds.x + xShift;
newState.y = bounds.y + yShift;
newState.width = bounds.width;
newState.height = bounds.height;
var verticalCells = [];
var horizontalCells = [];
//although states are defined as cellState, it has some mxRectangles!
var states = [];
for (var i = 0; i < this.states.length; i++)
{
var state = this.states[i];
var found = false;
if (state instanceof mxCellState)
{
if (clone || !this.graph.isCellSelected(state.cell))
{
if (((newState.x >= state.x && newState.x <= (state.x + state.width))
|| (state.x >= newState.x && state.x <= (newState.x + newState.width)))
&& (newState.y > state.y + state.height + 4|| newState.y + newState.height + 4 < state.y)) // + 4 to avoid having dy = 0 considered which cause a bug with 3 cells case
{
verticalCells.push(state);
}
else if (((newState.y >= state.y && newState.y <= (state.y + state.height))
|| (state.y >= newState.y && state.y <= (newState.y + newState.height)))
&& (newState.x > state.x + state.width + 4 || newState.x + newState.width + 4 < state.x)) // + 4 to avoid having dy = 0 considered which cause a bug with 3 cells case
{
horizontalCells.push(state);
}
}
}
}
var eqCy = 0;
var dy = 0;
var fixedDy = 0;
var midDy = 0;
var eqCx = 0;
var dx = 0;
var fixedDx = 0;
var midDx = 0;
var shift = 5 * scale;
if (verticalCells.length > 1)
{
verticalCells.push(newState);
verticalCells.sort(function(s1, s2)
{
return s1.y - s2.y;
});
var newStatePassed = false;
var firstMoving = newState == verticalCells[0];
var lastMoving = newState == verticalCells[verticalCells.length - 1];
//find the mid space and use it as dy and fixedDy
if (!firstMoving && !lastMoving)
{
for (var i = 1; i < verticalCells.length - 1; i++)
{
if (newState == verticalCells[i])
{
var s1 = verticalCells[i - 1];
var s3 = verticalCells[i + 1];
midDy = (s3.y - s1.y - s1.height - newState.height) / 2;
dy = midDy;
fixedDy = dy;
break;
}
}
}
for (var i = 0; i < verticalCells.length - 1; i++)
{
var s1 = verticalCells[i];
var s2 = verticalCells[i + 1];
var isMovingOne = newState == s1 || newState == s2;
var curDy = s2.y - s1.y - s1.height;
newStatePassed |= newState == s1;
if (dy == 0 && eqCy == 0)
{
dy = curDy;
eqCy = 1;
}
else if (Math.abs(dy - curDy) <= (isMovingOne || (i == 1 && newStatePassed)? tolerance : 0)) //non-moving cells must have exact same dy, must handle the case of having the first cell moving so we allow tolerance for second cell (until fixedDy is non-zero)
{
eqCy += 1;
}
else if (eqCy > 1 && newStatePassed) //stop and ignore the following cells
{
verticalCells = verticalCells.slice(0, i + 1);
break;
}
else if (verticalCells.length - i >= 3 && !newStatePassed) //reset and start counting again
{
eqCy = 0;
dy = midDy != 0? midDy : 0;
fixedDy = dy;
verticalCells.splice(0, i == 0? 1 : i);
i = -1;
}
else
{
break;
}
if (fixedDy == 0 && !isMovingOne)
{
fixedDy = curDy;
//Update dy such that following cells shows equal distance guides without tolerance
dy = fixedDy;
}
}
if (verticalCells.length == 3 && verticalCells[1] == newState)
{
fixedDy = 0;
}
}
if (horizontalCells.length > 1)
{
horizontalCells.push(newState)
horizontalCells.sort(function(s1, s2)
{
return s1.x - s2.x;
});
var newStatePassed = false;
var firstMoving = newState == horizontalCells[0];
var lastMoving = newState == horizontalCells[horizontalCells.length - 1];
//find the mid space and use it as dx and fixedDx
if (!firstMoving && !lastMoving)
{
for (var i = 1; i < horizontalCells.length - 1; i++)
{
if (newState == horizontalCells[i])
{
var s1 = horizontalCells[i - 1];
var s3 = horizontalCells[i + 1];
midDx = (s3.x - s1.x - s1.width - newState.width) / 2;
dx = midDx;
fixedDx = dx;
break;
}
}
}
for (var i = 0; i < horizontalCells.length - 1; i++)
{
var s1 = horizontalCells[i];
var s2 = horizontalCells[i + 1];
var isMovingOne = newState == s1 || newState == s2;
var curDx = s2.x - s1.x - s1.width;
newStatePassed |= newState == s1;
if (dx == 0 && eqCx == 0)
{
dx = curDx;
eqCx = 1;
}
else if (Math.abs(dx - curDx) <= (isMovingOne || (i == 1 && newStatePassed)? tolerance : 0))
{
eqCx += 1;
}
else if (eqCx > 1 && newStatePassed) //stop and ignore the following cells
{
horizontalCells = horizontalCells.slice(0, i + 1);
break;
}
else if (horizontalCells.length - i >= 3 && !newStatePassed) //reset and start counting again
{
eqCx = 0;
dx = midDx != 0? midDx : 0;
fixedDx = dx;
horizontalCells.splice(0, i == 0? 1 : i);
i = -1;
}
else
{
break;
}
if (fixedDx == 0 && !isMovingOne)
{
fixedDx = curDx;
//Update dx such that following cells shows equal distance guides without tolerance
dx = fixedDx;
}
}
if (horizontalCells.length == 3 && horizontalCells[1] == newState)
{
fixedDx = 0;
}
}
var createEqGuide = function(p1, p2, curGuide, isVer)
{
var points = [];
var dx = 0
var dy = 0;
if (isVer)
{
dx = shift;
dy = 0;
}
else
{
dx = 0;
dy = shift;
}
points.push(new mxPoint(p1.x - dx, p1.y - dy));
points.push(new mxPoint(p1.x + dx, p1.y + dy));
points.push(p1);
points.push(p2);
points.push(new mxPoint(p2.x - dx, p2.y - dy));
points.push(new mxPoint(p2.x + dx, p2.y + dy));
if (curGuide != null)
{
curGuide.points = points;
return curGuide;
}
else
{
var guideEq = new mxPolyline(points, mxConstants.GUIDE_COLOR, mxConstants.GUIDE_STROKEWIDTH);
guideEq.dialect = mxConstants.DIALECT_SVG;
guideEq.pointerEvents = false;
guideEq.init(guide.graph.getView().getOverlayPane());
return guideEq;
}
};
var hideEqGuides = function(horizontal, vertical)
{
if (horizontal && guide.guidesArrHor != null)
{
for (var i = 0; i < guide.guidesArrHor.length; i++)
{
guide.guidesArrHor[i].node.style.visibility = "hidden";
}
}
if (vertical && guide.guidesArrVer != null)
{
for (var i = 0; i < guide.guidesArrVer.length; i++)
{
guide.guidesArrVer[i].node.style.visibility = "hidden";
}
}
};
if (eqCx > 1 && eqCx == horizontalCells.length - 1)
{
var guidesArr = [];
var curArr = guide.guidesArrHor;
var hPoints = [];
var newX = 0;
//If the newState (moving cell) is the first one, use the next one for x coordinate such that the guide doesn't move with the cell
var firstI = horizontalCells[0] == newState? 1 : 0;
var firstY = horizontalCells[firstI].y + horizontalCells[firstI].height;
if (fixedDx > 0)
{
for (var i = 0; i < horizontalCells.length - 1; i++)
{
var s1 = horizontalCells[i];
var s2 = horizontalCells[i + 1];
if (newState == s1)
{
newX = s2.x - s1.width - fixedDx;
hPoints.push(new mxPoint(newX + s1.width + shift, firstY));
hPoints.push(new mxPoint(s2.x - shift, firstY));
}
else if (newState == s2)
{
hPoints.push(new mxPoint(s1.x + s1.width + shift, firstY));
newX = s1.x + s1.width + fixedDx;
hPoints.push(new mxPoint(newX - shift, firstY));
}
else
{
hPoints.push(new mxPoint(s1.x + s1.width + shift, firstY));
hPoints.push(new mxPoint(s2.x - shift, firstY));
}
}
}
else //this is the case when there are 3 cells and the middle one is moving
{
var s1 = horizontalCells[0];
var s3 = horizontalCells[2];
newX = s1.x + s1.width + (s3.x - s1.x - s1.width - newState.width) / 2;
hPoints.push(new mxPoint(s1.x + s1.width + shift, firstY));
hPoints.push(new mxPoint(newX - shift, firstY));
hPoints.push(new mxPoint(newX + newState.width + shift, firstY));
hPoints.push(new mxPoint(s3.x - shift, firstY));
}
for (var i = 0; i < hPoints.length; i += 2)
{
var p1 = hPoints[i];
var p2 = hPoints[i+1];
var guideEq = createEqGuide(p1, p2, curArr != null ? curArr[i/2] : null);
guideEq.node.style.visibility = "visible";
guideEq.redraw();
guidesArr.push(guideEq);
}
//destroy old non-recycled guides
for (var i = hPoints.length / 2; curArr != null && i < curArr.length; i ++)
{
curArr[i].destroy();
}
guide.guidesArrHor = guidesArr;
xShift = newX - bounds.x;
hasHorGuides = true;
}
else
{
hideEqGuides(true);
}
if (eqCy > 1 && eqCy == verticalCells.length - 1)
{
var guidesArr = [];
var curArr = guide.guidesArrVer;
var vPoints = [];
var newY = 0;
//If the newState (moving cell) is the first one, use the next one for x coordinate such that the guide doesn't move with the cell
var firstI = verticalCells[0] == newState? 1 : 0;
var firstX = verticalCells[firstI].x + verticalCells[firstI].width;
if (fixedDy > 0)
{
for (var i = 0; i < verticalCells.length - 1; i++)
{
var s1 = verticalCells[i];
var s2 = verticalCells[i + 1];
if (newState == s1)
{
newY = s2.y - s1.height - fixedDy;
vPoints.push(new mxPoint(firstX, newY + s1.height + shift));
vPoints.push(new mxPoint(firstX, s2.y - shift));
}
else if (newState == s2)
{
vPoints.push(new mxPoint(firstX, s1.y + s1.height + shift));
newY = s1.y + s1.height + fixedDy;
vPoints.push(new mxPoint(firstX, newY - shift));
}
else
{
vPoints.push(new mxPoint(firstX, s1.y + s1.height + shift));
vPoints.push(new mxPoint(firstX, s2.y - shift));
}
}
}
else //this is the case when there are 3 cells and the middle one is moving
{
var s1 = verticalCells[0];
var s3 = verticalCells[2];
newY = s1.y + s1.height + (s3.y - s1.y - s1.height - newState.height) / 2;
vPoints.push(new mxPoint(firstX, s1.y + s1.height + shift));
vPoints.push(new mxPoint(firstX, newY - shift));
vPoints.push(new mxPoint(firstX, newY + newState.height + shift));
vPoints.push(new mxPoint(firstX, s3.y - shift));
}
for (var i = 0; i < vPoints.length; i += 2)
{
var p1 = vPoints[i];
var p2 = vPoints[i+1];
var guideEq = createEqGuide(p1, p2, curArr != null ? curArr[i/2] : null, true);
guideEq.node.style.visibility = "visible";
guideEq.redraw();
guidesArr.push(guideEq);
}
//destroy old non-recycled guides
for (var i = vPoints.length / 2; curArr != null && i < curArr.length; i ++)
{
curArr[i].destroy();
}
guide.guidesArrVer = guidesArr;
yShift = newY - bounds.y;
hasVerGuides = true;
}
else
{
hideEqGuides(false, true);
}
}
if (hasHorGuides || hasVerGuides)
{
var eqPoint = new mxPoint(xShift, yShift);
var newPoint = guideMove.call(this, bounds, eqPoint, gridEnabled, clone);
//Adjust our point to match non-conflicting other guides
if (hasHorGuides && !hasVerGuides)
{
eqPoint.y = newPoint.y;
}
else if (hasVerGuides && !hasHorGuides)
{
eqPoint.x = newPoint.x;
}
//Hide other guide if this guide overrides them
if (newPoint.y != eqPoint.y)
{
if (this.guideY != null && this.guideY.node != null)
{
this.guideY.node.style.visibility = 'hidden';
}
}
if (newPoint.x != eqPoint.x)
{
if (this.guideX != null && this.guideX.node != null)
{
this.guideX.node.style.visibility = 'hidden';
}
}
return eqPoint;
}
else
{
hideEqGuides(true, true);
return guideMove.apply(this, arguments);
}
};
var guideSetVisible = mxGuide.prototype.setVisible;
mxGuide.prototype.setVisible = function (visible)
{
var guide = this;
guideSetVisible.call(guide, visible);
var guidesArrVer = guide.guidesArrVer;
var guidesArrHor = guide.guidesArrHor;
if (guidesArrVer != null)
{
for (var i = 0; i < guidesArrVer.length; i++)
{
guidesArrVer[i].node.style.visibility = visible? "visible" : "hidden";
}
}
if (guidesArrHor != null)
{
for (var i = 0; i < guidesArrHor.length; i++)
{
guidesArrHor[i].node.style.visibility = visible? "visible" : "hidden";
}
}
};
var guideDestroy = mxGuide.prototype.destroy;
mxGuide.prototype.destroy = function()
{
guideDestroy.call(this);
var guidesArrVer = this.guidesArrVer;
var guidesArrHor = this.guidesArrHor;
if (guidesArrVer != null)
{
for (var i = 0; i < guidesArrVer.length; i++)
{
guidesArrVer[i].destroy();
}
this.guidesArrVer = null;
}
if (guidesArrHor != null)
{
for (var i = 0; i < guidesArrHor.length; i++)
{
guidesArrHor[i].destroy();
}
this.guidesArrHor = null;
}
};
})(); | 412 | 0.95366 | 1 | 0.95366 | game-dev | MEDIA | 0.801035 | game-dev | 0.998968 | 1 | 0.998968 |
frzyc/genshin-optimizer | 12,274 | libs/gi/sheets/src/Characters/Lyney/index.tsx | import { objKeyMap, range } from '@genshin-optimizer/common/util'
import type { CharacterKey } from '@genshin-optimizer/gi/consts'
import { allStats, getCharEle } from '@genshin-optimizer/gi/stats'
import type { Data } from '@genshin-optimizer/gi/wr'
import {
constant,
equal,
greaterEq,
infoMut,
input,
lookup,
min,
naught,
percent,
prod,
subscript,
sum,
tally,
} from '@genshin-optimizer/gi/wr'
import { cond, st, stg } from '../../SheetUtil'
import { CharacterSheet } from '../CharacterSheet'
import type { TalentSheet } from '../ICharacterSheet.d'
import { charTemplates } from '../charTemplates'
import {
dataObjForCharacterSheet,
dmgNode,
healNodeTalent,
plungingDmgNodes,
} from '../dataUtil'
const key: CharacterKey = 'Lyney'
const skillParam_gen = allStats.char.skillParam[key]
const ct = charTemplates(key)
let a = 0,
s = 0,
b = 0
const dm = {
normal: {
hitArr: [
skillParam_gen.auto[a++],
skillParam_gen.auto[a++],
skillParam_gen.auto[++a], // 3x2, skip one entry
skillParam_gen.auto[++a],
],
},
plunging: {
dmg: skillParam_gen.auto[++a],
low: skillParam_gen.auto[++a],
high: skillParam_gen.auto[++a],
},
charged: {
aimed: skillParam_gen.auto[++a],
fullyAimed: skillParam_gen.auto[++a],
propDmg: skillParam_gen.auto[++a],
hpCost: skillParam_gen.auto[++a],
hatHp: skillParam_gen.auto[++a],
hatDuration: skillParam_gen.auto[++a][0],
pyrotechnicDmg: skillParam_gen.auto[++a],
thornDmg: skillParam_gen.auto[++a],
thornInterval: skillParam_gen.auto[++a][0],
},
skill: {
dmg: skillParam_gen.skill[s++],
dmgInc: skillParam_gen.skill[s++],
hpRegen: skillParam_gen.skill[s++],
cd: skillParam_gen.skill[s++][0],
},
burst: {
skillDmg: skillParam_gen.burst[b++],
fireworkDmg: skillParam_gen.burst[b++],
duration: skillParam_gen.burst[b++][0],
cd: skillParam_gen.burst[b++][0],
enerCost: skillParam_gen.burst[b++][0],
},
passive1: {
energy: skillParam_gen.passive1[0][0],
propAddlDmg: skillParam_gen.passive1[1][0],
},
passive2: {
dmg_: skillParam_gen.passive2[0][0],
extraDmg_: skillParam_gen.passive2[1][0],
},
constellation2: {
critDmg_: skillParam_gen.constellation2[0],
stackCd: skillParam_gen.constellation2[1],
maxStacks: skillParam_gen.constellation2[2],
},
constellation4: {
enemy_pyro_res_: skillParam_gen.constellation4[0],
duration: skillParam_gen.constellation4[1],
},
constellation6: {
dmg: skillParam_gen.constellation6[0],
},
} as const
const [condPropStacksPath, condPropStacks] = cond(key, 'propStacks')
const propStacksArr = range(1, 5)
const propStacks = infoMut(
lookup(
condPropStacks,
objKeyMap(propStacksArr, (stacks) => constant(stacks)),
constant(0)
),
{ name: ct.ch('propStacks') }
)
// TODO: Check if this scales with Bennett ult. If it does not, change this to premod.atk
const skillDmgInc = prod(
propStacks,
subscript(input.total.skillIndex, dm.skill.dmgInc, { unit: '%' }),
input.total.atk
)
const [condA1DrainHpPath, condA1DrainHp] = cond(key, 'a1DrainHp')
const a1_hatDmgInc = greaterEq(
input.asc,
1,
equal(
condA1DrainHp,
'on',
prod(percent(dm.passive1.propAddlDmg), input.total.atk)
)
)
const [condA4AffectedByPyroPath, condA4AffectedByPyro] = cond(
key,
'a4AffectedByPyro'
)
const numPyroOther = infoMut(min(2, sum(tally.pyro, -1)), { asConst: true })
const a4AffectedByPyro_dmg_ = greaterEq(
input.asc,
4,
equal(
condA4AffectedByPyro,
'on',
sum(
percent(dm.passive2.dmg_),
prod(percent(dm.passive2.extraDmg_), numPyroOther)
)
)
)
const [condC2StacksPath, condC2Stacks] = cond(key, 'c2Stacks')
const c2StacksArr = range(1, dm.constellation2.maxStacks)
const c2_critDMG_ = greaterEq(
input.constellation,
2,
prod(
percent(dm.constellation2.critDmg_),
lookup(
condC2Stacks,
objKeyMap(c2StacksArr, (stacks) => constant(stacks)),
naught
)
)
)
const [condC4HitPath, condC4Hit] = cond(key, 'c4Hit')
const c4_pyro_enemy_res_ = greaterEq(
input.constellation,
4,
equal(condC4Hit, 'on', -dm.constellation4.enemy_pyro_res_)
)
const hit_ele_pyro = { hit: { ele: constant(getCharEle(key)) } }
const hat_addl: Data = {
premod: { charged_dmgInc: a1_hatDmgInc },
...hit_ele_pyro,
}
const dmgFormulas = {
normal: Object.fromEntries(
dm.normal.hitArr.map((arr, i) => [i, dmgNode('atk', arr, 'normal')])
),
charged: {
aimed: dmgNode('atk', dm.charged.aimed, 'charged'),
fullyAimed: dmgNode('atk', dm.charged.fullyAimed, 'charged', hit_ele_pyro),
prop: dmgNode('atk', dm.charged.propDmg, 'charged', hit_ele_pyro),
hpCost: prod(
subscript(input.total.autoIndex, dm.charged.hpCost, { unit: '%' }),
input.total.hp
),
hatHp: prod(
subscript(input.total.autoIndex, dm.charged.hatHp, { unit: '%' }),
input.total.hp
),
pyrotechnic: dmgNode('atk', dm.charged.pyrotechnicDmg, 'charged', hat_addl),
spiritbreath: dmgNode('atk', dm.charged.thornDmg, 'charged', hit_ele_pyro),
},
plunging: plungingDmgNodes('atk', dm.plunging),
skill: {
dmg: dmgNode('atk', dm.skill.dmg, 'skill'),
skillDmgInc,
hpRegen: healNodeTalent(
'hp',
dm.skill.hpRegen,
new Array(15).fill(0),
'skill',
undefined,
propStacks
),
},
burst: {
dmg: dmgNode('atk', dm.burst.skillDmg, 'burst'),
fireworkDmg: dmgNode('atk', dm.burst.fireworkDmg, 'burst'),
},
passive1: {
hatDmgInc: a1_hatDmgInc,
},
constellation6: {
dmg: greaterEq(
input.constellation,
6,
dmgNode(
'atk',
dm.charged.pyrotechnicDmg,
'charged',
hit_ele_pyro,
percent(dm.constellation6.dmg)
)
),
},
}
const nodeC3 = greaterEq(input.constellation, 3, 3)
const nodeC5 = greaterEq(input.constellation, 5, 3)
export const data = dataObjForCharacterSheet(key, dmgFormulas, {
premod: {
burstBoost: nodeC5,
autoBoost: nodeC3,
critDMG_: c2_critDMG_,
all_dmg_: a4AffectedByPyro_dmg_,
skill_dmgInc: skillDmgInc,
},
teamBuff: {
premod: {
pyro_enemyRes_: c4_pyro_enemy_res_,
},
},
})
const sheet: TalentSheet = {
auto: ct.talentTem('auto', [
{
text: ct.chg('auto.fields.normal'),
},
{
fields: dm.normal.hitArr.map((_, i) => ({
node: infoMut(dmgFormulas.normal[i], {
name: ct.chg(`auto.skillParams.${i}`),
multi: i === 2 ? 2 : undefined,
}),
})),
},
{
text: ct.chg('auto.fields.plunging'),
},
{
fields: [
{
node: infoMut(dmgFormulas.plunging.dmg, {
name: stg('plunging.dmg'),
}),
},
{
node: infoMut(dmgFormulas.plunging.low, {
name: stg('plunging.low'),
}),
},
{
node: infoMut(dmgFormulas.plunging.high, {
name: stg('plunging.high'),
}),
},
],
},
{
text: ct.chg('auto.fields.charged'),
},
{
fields: [
{
node: infoMut(dmgFormulas.charged.aimed, {
name: ct.chg(`auto.skillParams.6`),
}),
},
{
node: infoMut(dmgFormulas.charged.fullyAimed, {
name: ct.chg(`auto.skillParams.7`),
}),
},
{
node: infoMut(dmgFormulas.charged.prop, {
name: ct.chg('auto.skillParams.8'),
}),
},
{
node: infoMut(dmgFormulas.charged.hpCost, {
name: ct.chg('auto.skillParams.9'),
}),
},
],
},
ct.headerTem('constellation6', {
fields: [
{
node: infoMut(dmgFormulas.constellation6.dmg, {
name: ct.ch('c6Dmg'),
}),
},
],
}),
{
text: ct.chg('auto.fields.grinMalkin'),
},
{
fields: [
{
node: infoMut(dmgFormulas.charged.hatHp, {
name: ct.chg('auto.skillParams.10'),
}),
},
{
text: ct.chg('auto.skillParams.11'),
value: dm.charged.hatDuration,
unit: 's',
},
{
node: infoMut(dmgFormulas.charged.pyrotechnic, {
name: ct.chg('auto.skillParams.12'),
}),
},
],
},
ct.condTem('passive1', {
value: condA1DrainHp,
path: condA1DrainHpPath,
name: ct.ch('a1CondName'),
states: {
on: {
fields: [
{
node: infoMut(a1_hatDmgInc, { name: ct.ch('hatDmgInc') }),
},
{
text: stg('energyRegen'),
value: 3,
},
],
},
},
}),
{
text: ct.chg('auto.fields.arkhe'),
},
{
fields: [
{
node: infoMut(dmgFormulas.charged.spiritbreath, {
name: ct.chg('auto.skillParams.13'),
}),
},
{
text: ct.chg('auto.skillParams.14'),
value: dm.charged.thornInterval,
unit: 's',
},
],
},
]),
skill: ct.talentTem('skill', [
{
fields: [
{
node: infoMut(dmgFormulas.skill.dmg, {
name: ct.chg(`skill.skillParams.0`),
}),
},
{
text: stg('cd'),
value: dm.skill.cd,
unit: 's',
},
],
},
ct.condTem('skill', {
value: condPropStacks,
path: condPropStacksPath,
name: ct.ch('propStacksUsed'),
states: objKeyMap(propStacksArr, (stacks) => ({
name: st('stack', { count: stacks }),
fields: [
{
node: dmgFormulas.skill.skillDmgInc,
},
{
node: infoMut(dmgFormulas.skill.hpRegen, {
name: ct.chg('skill.skillParams.2'),
}),
},
],
})),
}),
]),
burst: ct.talentTem('burst', [
{
fields: [
{
node: infoMut(dmgFormulas.burst.dmg, {
name: ct.chg(`burst.skillParams.0`),
}),
},
{
node: infoMut(dmgFormulas.burst.fireworkDmg, {
name: ct.chg(`burst.skillParams.1`),
}),
},
{
text: stg('duration'),
value: dm.burst.duration,
unit: 's',
},
{
text: stg('cd'),
value: dm.burst.cd,
unit: 's',
},
{
text: stg('energyCost'),
value: dm.burst.enerCost,
},
],
},
]),
passive1: ct.talentTem('passive1'),
passive2: ct.talentTem('passive2', [
ct.condTem('passive2', {
value: condA4AffectedByPyro,
path: condA4AffectedByPyroPath,
name: st('enemyAffected.pyro'),
states: {
on: {
fields: [
{
node: a4AffectedByPyro_dmg_,
},
],
},
},
}),
]),
passive3: ct.talentTem('passive3'),
constellation1: ct.talentTem('constellation1'),
constellation2: ct.talentTem('constellation2', [
ct.condTem('constellation2', {
path: condC2StacksPath,
value: condC2Stacks,
name: st('timeOnField'),
states: objKeyMap(c2StacksArr, (stacks) => ({
name: st('seconds', { count: stacks * 2 }),
fields: [
{
node: c2_critDMG_,
},
],
})),
}),
]),
constellation3: ct.talentTem('constellation3', [
{ fields: [{ node: nodeC3 }] },
]),
constellation4: ct.talentTem('constellation4', [
ct.condTem('constellation4', {
value: condC4Hit,
path: condC4HitPath,
name: st('hitOp.charged'),
states: {
on: {
fields: [
{
node: c4_pyro_enemy_res_,
},
{
text: stg('duration'),
value: dm.constellation4.duration,
unit: 's',
},
],
},
},
}),
]),
constellation5: ct.talentTem('constellation5', [
{ fields: [{ node: nodeC5 }] },
]),
constellation6: ct.talentTem('constellation6'),
}
export default new CharacterSheet(sheet, data)
| 412 | 0.72449 | 1 | 0.72449 | game-dev | MEDIA | 0.507509 | game-dev | 0.753773 | 1 | 0.753773 |
FakeFishGames/Barotrauma | 2,313 | Barotrauma/BarotraumaShared/SharedSource/Events/EventActions/GodModeAction.cs | namespace Barotrauma
{
/// <summary>
/// Makes a specific character invulnerable to damage and unable to die.
/// </summary>
class GodModeAction : EventAction
{
[Serialize(true, IsPropertySaveable.Yes, description: "Should the godmode be enabled or disabled?")]
public bool Enabled { get; set; }
[Serialize(false, IsPropertySaveable.Yes, description: "Should the character's active afflictions be updated (e.g. applying visual effects of the afflictions)")]
public bool UpdateAfflictions { get; set; }
[Serialize("", IsPropertySaveable.Yes, description: "Tag of the character whose godmode to enable/disable.")]
public Identifier TargetTag { get; set; }
public GodModeAction(ScriptedEvent parentEvent, ContentXElement element) : base(parentEvent, element) { }
private bool isFinished = false;
public override bool IsFinished(ref string goTo)
{
return isFinished;
}
public override void Reset()
{
isFinished = false;
}
public override void Update(float deltaTime)
{
if (isFinished) { return; }
var targets = ParentEvent.GetTargets(TargetTag);
foreach (var target in targets)
{
if (target != null && target is Character character)
{
if (Enabled)
{
if (UpdateAfflictions)
{
character.CharacterHealth.Unkillable = true;
}
else
{
character.GodMode = true;
}
}
else
{
character.CharacterHealth.Unkillable = false;
character.GodMode = false;
}
}
}
isFinished = true;
}
public override string ToDebugString()
{
return $"{ToolBox.GetDebugSymbol(isFinished)} {nameof(GodModeAction)} -> (TargetTag: {TargetTag.ColorizeObject()}, " +
(Enabled ? "Enable godmode" : "Disable godmode");
}
}
} | 412 | 0.889239 | 1 | 0.889239 | game-dev | MEDIA | 0.950707 | game-dev | 0.825337 | 1 | 0.825337 |
Minecraft-LightLand/Youkai-Homecoming | 3,133 | src/main/java/dev/xkmc/youkaishomecoming/content/pot/cooking/mid/MidCookingPotBlock.java | package dev.xkmc.youkaishomecoming.content.pot.cooking.mid;
import com.tterrag.registrate.providers.DataGenContext;
import com.tterrag.registrate.providers.RegistrateBlockstateProvider;
import dev.xkmc.l2modularblock.BlockProxy;
import dev.xkmc.l2modularblock.DelegateBlock;
import dev.xkmc.l2modularblock.impl.BlockEntityBlockMethodImpl;
import dev.xkmc.l2modularblock.one.ShapeBlockMethod;
import dev.xkmc.l2modularblock.type.BlockMethod;
import dev.xkmc.youkaishomecoming.content.block.food.PotFoodBlock;
import dev.xkmc.youkaishomecoming.content.pot.cooking.core.PotClick;
import dev.xkmc.youkaishomecoming.content.pot.cooking.core.PotFall;
import dev.xkmc.youkaishomecoming.init.registrate.YHBlocks;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.VoxelShape;
import net.minecraftforge.client.model.generators.ModelFile;
import org.jetbrains.annotations.Nullable;
public class MidCookingPotBlock implements ShapeBlockMethod {
public static final BlockMethod INS = new MidCookingPotBlock();
public static final BlockMethod BE = new BlockEntityBlockMethodImpl<>(YHBlocks.MID_POT_BE, MidCookingPotBlockEntity.class);
public static final VoxelShape SHAPE = Block.box(2, 0, 2, 14, 6, 14);
public static DelegateBlock create(BlockBehaviour.Properties p) {
return DelegateBlock.newBaseBlock(p, INS, new PotClick(YHBlocks.IRON_POT), new PotFall(), BE, BlockProxy.HORIZONTAL);
}
@Override
public @Nullable VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext ctx) {
return SHAPE;
}
public static void buildState(DataGenContext<Block, ? extends Block> ctx, RegistrateBlockstateProvider pvd) {
pvd.horizontalBlock(ctx.get(), pvd.models().getBuilder(ctx.getName())
.parent(new ModelFile.UncheckedModelFile(pvd.modLoc("custom/bowl/short/short_iron_pot")))
.texture("top", pvd.modLoc("block/bowl/short/short_iron_pot_top"))
.texture("side", pvd.modLoc("block/bowl/short/short_iron_pot_side"))
.texture("bottom", pvd.modLoc("block/bowl/short/short_iron_pot_bottom"))
.renderType("cutout")
);
}
public static void buildPotFood(DataGenContext<Block, ? extends Block> ctx, RegistrateBlockstateProvider pvd, String name) {
pvd.horizontalBlock(ctx.get(), state -> {
int serve = state.getValue(PotFoodBlock.SERVE_2);
String suffix = serve == 2 ? "" : "_serve1";
return pvd.models().getBuilder(ctx.getName() + suffix)
.parent(new ModelFile.UncheckedModelFile(pvd.modLoc("custom/bowl/short/" + name + suffix)))
.texture("top", pvd.modLoc("block/bowl/short/short_iron_pot_top"))
.texture("side", pvd.modLoc("block/bowl/short/short_iron_pot_side"))
.texture("bottom", pvd.modLoc("block/bowl/short/short_iron_pot_bottom"))
.texture("base", pvd.modLoc("block/bowl/short/" + name))
.renderType("cutout");
}
);
}
}
| 412 | 0.896826 | 1 | 0.896826 | game-dev | MEDIA | 0.981625 | game-dev | 0.775644 | 1 | 0.775644 |
narknon/FF7R2UProj | 1,454 | Source/EndDataObject/Public/EndDataTableStateCondition.h | #pragma once
#include "CoreMinimal.h"
#include "EndDataTableRowBase.h"
#include "EndDataTableStateCondition.generated.h"
USTRUCT(BlueprintType)
struct FEndDataTableStateCondition : public FEndDataTableRowBase {
GENERATED_BODY()
public:
private:
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
TArray<FString> StartBracket_Array;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
TArray<uint8> TargetType_Array;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
TArray<FName> TargetStringArgument_Array;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
TArray<FString> ComparisonOperator_Array;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
TArray<uint8> RightType_Array;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
TArray<FString> ComparisonStringValue_Array;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
TArray<int32> ComparisonValue_Array;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
TArray<FString> EndBracket_Array;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
TArray<FString> LogicalOperator_Array;
public:
ENDDATAOBJECT_API FEndDataTableStateCondition();
};
| 412 | 0.82393 | 1 | 0.82393 | game-dev | MEDIA | 0.788423 | game-dev | 0.615183 | 1 | 0.615183 |
betidestudio/SteamIntegrationKit | 1,341 | Source/SteamIntegrationKit/Functions/Friends/SIK_GetFollowerCount_AsyncFunction.h | // Copyright (c) 2024 Betide Studio. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "SIK_SharedFile.h"
#include "SIK_FriendsLibrary.h"
#include "Kismet/BlueprintAsyncActionBase.h"
#include "SIK_GetFollowerCount_AsyncFunction.generated.h"
DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FOnGetFollowerCount, int32, FollowerCount, FSIK_SteamId, UserSteamId);
UCLASS()
class STEAMINTEGRATIONKIT_API USIK_GetFollowerCount_AsyncFunction : public UBlueprintAsyncActionBase
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintCallable, DisplayName="Get Steam Follower Count",meta = (BlueprintInternalUseOnly = "true",Keywords="GetFollowerCount"), Category= "Steam Integration Kit || SDK Functions || Friends")
static USIK_GetFollowerCount_AsyncFunction* GetFollowerCount(const FSIK_SteamId& SteamId);
UPROPERTY(BlueprintAssignable)
FOnGetFollowerCount OnSuccess;
UPROPERTY(BlueprintAssignable)
FOnGetFollowerCount OnFailure;
private:
FSIK_SteamId m_SteamId;
virtual void Activate() override;
#if (WITH_ENGINE_STEAM && ONLINESUBSYSTEMSTEAM_PACKAGE) || (WITH_STEAMKIT && !WITH_ENGINE_STEAM)
void OnGetFollowerCount(FriendsGetFollowerCount_t* FriendsGetFollowerCount, bool bIOFailure);
SteamAPICall_t m_CallbackHandle;
CCallResult<USIK_GetFollowerCount_AsyncFunction, FriendsGetFollowerCount_t> m_Callback;
#endif
};
| 412 | 0.878656 | 1 | 0.878656 | game-dev | MEDIA | 0.543739 | game-dev,networking | 0.800299 | 1 | 0.800299 |
oot-pc-port/oot-pc-port | 2,593 | asm/non_matchings/overlays/actors/ovl_En_Zl3/func_80B534CC.s | glabel func_80B534CC
/* 0011C 80B534CC 27BDFFC8 */ addiu $sp, $sp, 0xFFC8 ## $sp = FFFFFFC8
/* 00120 80B534D0 AFBF0014 */ sw $ra, 0x0014($sp)
/* 00124 80B534D4 848E0246 */ lh $t6, 0x0246($a0) ## 00000246
/* 00128 80B534D8 00803025 */ or $a2, $a0, $zero ## $a2 = 00000000
/* 0012C 80B534DC 24C30246 */ addiu $v1, $a2, 0x0246 ## $v1 = 00000246
/* 00130 80B534E0 15C00003 */ bne $t6, $zero, .L80B534F0
/* 00134 80B534E4 00001025 */ or $v0, $zero, $zero ## $v0 = 00000000
/* 00138 80B534E8 10000005 */ beq $zero, $zero, .L80B53500
/* 0013C 80B534EC 24830246 */ addiu $v1, $a0, 0x0246 ## $v1 = 00000246
.L80B534F0:
/* 00140 80B534F0 846F0000 */ lh $t7, 0x0000($v1) ## 00000246
/* 00144 80B534F4 25F8FFFF */ addiu $t8, $t7, 0xFFFF ## $t8 = FFFFFFFF
/* 00148 80B534F8 A4780000 */ sh $t8, 0x0000($v1) ## 00000246
/* 0014C 80B534FC 84620000 */ lh $v0, 0x0000($v1) ## 00000246
.L80B53500:
/* 00150 80B53500 14400008 */ bne $v0, $zero, .L80B53524
/* 00154 80B53504 2404003C */ addiu $a0, $zero, 0x003C ## $a0 = 0000003C
/* 00158 80B53508 2405003C */ addiu $a1, $zero, 0x003C ## $a1 = 0000003C
/* 0015C 80B5350C AFA3001C */ sw $v1, 0x001C($sp)
/* 00160 80B53510 0C01DF64 */ jal Math_Rand_S16Offset
/* 00164 80B53514 AFA60038 */ sw $a2, 0x0038($sp)
/* 00168 80B53518 8FA3001C */ lw $v1, 0x001C($sp)
/* 0016C 80B5351C 8FA60038 */ lw $a2, 0x0038($sp)
/* 00170 80B53520 A4620000 */ sh $v0, 0x0000($v1) ## 00000000
.L80B53524:
/* 00174 80B53524 84790000 */ lh $t9, 0x0000($v1) ## 00000000
/* 00178 80B53528 24C20244 */ addiu $v0, $a2, 0x0244 ## $v0 = 00000244
/* 0017C 80B5352C A4590000 */ sh $t9, 0x0000($v0) ## 00000244
/* 00180 80B53530 84480000 */ lh $t0, 0x0000($v0) ## 00000244
/* 00184 80B53534 29010003 */ slti $at, $t0, 0x0003
/* 00188 80B53538 54200003 */ bnel $at, $zero, .L80B53548
/* 0018C 80B5353C 8FBF0014 */ lw $ra, 0x0014($sp)
/* 00190 80B53540 A4400000 */ sh $zero, 0x0000($v0) ## 00000244
/* 00194 80B53544 8FBF0014 */ lw $ra, 0x0014($sp)
.L80B53548:
/* 00198 80B53548 27BD0038 */ addiu $sp, $sp, 0x0038 ## $sp = 00000000
/* 0019C 80B5354C 03E00008 */ jr $ra
/* 001A0 80B53550 00000000 */ nop
| 412 | 0.699456 | 1 | 0.699456 | game-dev | MEDIA | 0.986171 | game-dev | 0.630991 | 1 | 0.630991 |
0x7c13/Pal3.Unity | 6,741 | Assets/Plugins/SimpleFileBrowser/Scripts/FileBrowserItem.cs | using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
namespace SimpleFileBrowser
{
public class FileBrowserItem : ListItem, IPointerClickHandler, IPointerDownHandler, IPointerUpHandler
#if UNITY_EDITOR || ( !UNITY_ANDROID && !UNITY_IOS )
, IPointerEnterHandler, IPointerExitHandler
#endif
{
#region Constants
private const float DOUBLE_CLICK_TIME = 0.5f;
private const float TOGGLE_MULTI_SELECTION_HOLD_TIME = 0.5f;
#endregion
#region Variables
protected FileBrowser fileBrowser;
#pragma warning disable 0649
[SerializeField]
private Image background;
[SerializeField]
private Image icon;
public Image Icon { get { return icon; } }
[SerializeField]
private Image multiSelectionToggle;
[SerializeField]
private Text nameText;
#pragma warning restore 0649
#pragma warning disable 0414
private bool isSelected, isHidden;
#pragma warning restore 0414
private UISkin skin;
private float pressTime = Mathf.Infinity;
private float prevClickTime;
#endregion
#region Properties
private RectTransform m_transform;
public RectTransform TransformComponent
{
get
{
if( m_transform == null )
m_transform = (RectTransform) transform;
return m_transform;
}
}
public string Name { get { return nameText.text; } }
public bool IsDirectory { get; private set; }
#endregion
#region Initialization Functions
public void SetFileBrowser( FileBrowser fileBrowser, UISkin skin )
{
this.fileBrowser = fileBrowser;
OnSkinRefreshed( skin, false );
}
public void SetFile( Sprite icon, string name, bool isDirectory )
{
this.icon.sprite = icon;
nameText.text = name;
IsDirectory = isDirectory;
}
#endregion
#region Messages
private void Update()
{
if( fileBrowser.AllowMultiSelection && Time.realtimeSinceStartup - pressTime >= TOGGLE_MULTI_SELECTION_HOLD_TIME )
{
// Item is held for a while
pressTime = Mathf.Infinity;
fileBrowser.OnItemHeld( this );
}
}
#endregion
#region Pointer Events
public void OnPointerClick( PointerEventData eventData )
{
#if UNITY_EDITOR || UNITY_STANDALONE || UNITY_WEBGL || UNITY_WSA || UNITY_WSA_10_0
if( eventData.button == PointerEventData.InputButton.Middle )
return;
else if( eventData.button == PointerEventData.InputButton.Right )
{
// First, select the item
if( !isSelected )
{
prevClickTime = 0f;
fileBrowser.OnItemSelected( this, false );
}
// Then, show the context menu
fileBrowser.OnContextMenuTriggered( eventData.position );
return;
}
#endif
if( Time.realtimeSinceStartup - prevClickTime < DOUBLE_CLICK_TIME )
{
prevClickTime = 0f;
fileBrowser.OnItemSelected( this, true );
}
else
{
prevClickTime = Time.realtimeSinceStartup;
fileBrowser.OnItemSelected( this, false );
}
}
public void OnPointerDown( PointerEventData eventData )
{
#if UNITY_EDITOR || UNITY_STANDALONE || UNITY_WEBGL || UNITY_WSA || UNITY_WSA_10_0
if( eventData.button != PointerEventData.InputButton.Left )
return;
#endif
pressTime = Time.realtimeSinceStartup;
}
public void OnPointerUp( PointerEventData eventData )
{
#if UNITY_EDITOR || UNITY_STANDALONE || UNITY_WEBGL || UNITY_WSA || UNITY_WSA_10_0
if( eventData.button != PointerEventData.InputButton.Left )
return;
#endif
if( pressTime != Mathf.Infinity )
pressTime = Mathf.Infinity;
else if( fileBrowser.MultiSelectionToggleSelectionMode )
{
// We have activated MultiSelectionToggleSelectionMode with this press, processing the click would result in
// deselecting this item since its selected state would be toggled
eventData.eligibleForClick = false;
}
}
#if UNITY_EDITOR || ( !UNITY_ANDROID && !UNITY_IOS )
public void OnPointerEnter( PointerEventData eventData )
{
if( !isSelected )
background.color = skin.FileHoveredBackgroundColor;
}
#endif
#if UNITY_EDITOR || ( !UNITY_ANDROID && !UNITY_IOS )
public void OnPointerExit( PointerEventData eventData )
{
if( !isSelected )
background.color = ( Position % 2 ) == 0 ? skin.FileNormalBackgroundColor : skin.FileAlternatingBackgroundColor;
}
#endif
#endregion
#region Other Events
public void SetSelected( bool isSelected )
{
this.isSelected = isSelected;
background.color = isSelected ? skin.FileSelectedBackgroundColor : ( ( Position % 2 ) == 0 ? skin.FileNormalBackgroundColor : skin.FileAlternatingBackgroundColor );
nameText.color = isSelected ? skin.FileSelectedTextColor : skin.FileNormalTextColor;
if( isHidden )
{
Color c = nameText.color;
c.a = 0.55f;
nameText.color = c;
}
if( multiSelectionToggle ) // Quick links don't have multi-selection toggle
{
// Don't show multi-selection toggle for folders in file selection mode
if( fileBrowser.MultiSelectionToggleSelectionMode && ( !IsDirectory || fileBrowser.PickerMode != FileBrowser.PickMode.Files ) )
{
if( !multiSelectionToggle.gameObject.activeSelf )
{
multiSelectionToggle.gameObject.SetActive( true );
Vector2 shiftAmount = new Vector2( multiSelectionToggle.rectTransform.sizeDelta.x, 0f );
icon.rectTransform.anchoredPosition += shiftAmount;
nameText.rectTransform.anchoredPosition += shiftAmount;
}
multiSelectionToggle.sprite = isSelected ? skin.FileMultiSelectionToggleOnIcon : skin.FileMultiSelectionToggleOffIcon;
}
else if( multiSelectionToggle.gameObject.activeSelf )
{
multiSelectionToggle.gameObject.SetActive( false );
Vector2 shiftAmount = new Vector2( -multiSelectionToggle.rectTransform.sizeDelta.x, 0f );
icon.rectTransform.anchoredPosition += shiftAmount;
nameText.rectTransform.anchoredPosition += shiftAmount;
// Clicking a file shortly after disabling MultiSelectionToggleSelectionMode does nothing, this workaround fixes that issue
prevClickTime = 0f;
}
}
}
public void SetHidden( bool isHidden )
{
this.isHidden = isHidden;
Color c = icon.color;
c.a = isHidden ? 0.5f : 1f;
icon.color = c;
c = nameText.color;
c.a = isHidden ? 0.55f : ( isSelected ? skin.FileSelectedTextColor.a : skin.FileNormalTextColor.a );
nameText.color = c;
}
public void OnSkinRefreshed( UISkin skin, bool isInitialized = true )
{
this.skin = skin;
TransformComponent.sizeDelta = new Vector2( TransformComponent.sizeDelta.x, skin.FileHeight );
skin.ApplyTo( nameText, isSelected ? skin.FileSelectedTextColor : skin.FileNormalTextColor );
icon.rectTransform.sizeDelta = new Vector2( icon.rectTransform.sizeDelta.x, -skin.FileIconsPadding );
if( isInitialized )
SetSelected( isSelected );
}
#endregion
}
} | 412 | 0.944711 | 1 | 0.944711 | game-dev | MEDIA | 0.739189 | game-dev | 0.981815 | 1 | 0.981815 |
godotengine/godot-demo-projects | 2,155 | loading/serialization/save_load_json.gd | extends Button
# This script shows how to save data using the JSON file format.
# JSON is a widely used file format, but not all Godot types can be
# stored natively. For example, integers get converted into doubles,
# and to store Vector2 and other non-JSON types you need to convert
# them, such as to a String using var_to_str.
## The root game node (so we can get and instance enemies).
@export var game_node: NodePath
## The player node (so we can set/get its health and position).
@export var player_node: NodePath
const SAVE_PATH = "user://save_json.json"
func save_game() -> void:
var file := FileAccess.open(SAVE_PATH, FileAccess.WRITE)
var player := get_node(player_node)
# JSON doesn't support many of Godot's types such as Vector2.
# var_to_str can be used to convert any Variant to a String.
var save_dict := {
player = {
position = var_to_str(player.position),
health = var_to_str(player.health),
rotation = var_to_str(player.sprite.rotation),
},
enemies = [],
}
for enemy in get_tree().get_nodes_in_group(&"enemy"):
save_dict.enemies.push_back({
position = var_to_str(enemy.position),
})
file.store_line(JSON.stringify(save_dict))
get_node(^"../LoadJSON").disabled = false
func load_game() -> void:
var file := FileAccess.open(SAVE_PATH, FileAccess.READ)
var json := JSON.new()
json.parse(file.get_line())
var save_dict := json.get_data() as Dictionary
var player := get_node(player_node) as Player
# JSON doesn't support many of Godot's types such as Vector2.
# str_to_var can be used to convert a String to the corresponding Variant.
player.position = str_to_var(save_dict.player.position)
player.health = str_to_var(save_dict.player.health)
player.sprite.rotation = str_to_var(save_dict.player.rotation)
# Remove existing enemies before adding new ones.
get_tree().call_group(&"enemy", &"queue_free")
# Ensure the node structure is the same when loading.
var game := get_node(game_node)
for enemy_config: Dictionary in save_dict.enemies:
var enemy: Enemy = preload("res://enemy.tscn").instantiate()
enemy.position = str_to_var(enemy_config.position)
game.add_child(enemy)
| 412 | 0.66057 | 1 | 0.66057 | game-dev | MEDIA | 0.822618 | game-dev | 0.644227 | 1 | 0.644227 |
lgynico/mmo_skill | 1,056 | facade/task.go | package facade
import "github.com/lgynico/mmo_skill/conf"
type Task interface {
Exec(ctx Battle) bool
}
/* 效果 */
type EffectTask struct {
eff SkillEffect
effCfg *conf.SkillEffectRow
skill Skill
target BattleUnit
}
func NewEffTask(eff SkillEffect, skill Skill, effCfg *conf.SkillEffectRow, target BattleUnit) Task {
return &EffectTask{
eff: eff,
skill: skill,
effCfg: effCfg,
target: target,
}
}
func (t *EffectTask) Exec(ctx Battle) bool {
t.eff.OnEffect(t.skill, t.effCfg, t.target)
return true
}
/* 延迟效果事件 */
type DelayEffectTask struct {
EffectTask
delay int64
}
func NewDelayEffectTask(eff SkillEffect, skill Skill, effCfg *conf.SkillEffectRow, target BattleUnit, delay int64) Task {
task := NewEffTask(eff, skill, effCfg, target)
effTask := task.(*EffectTask)
return &DelayEffectTask{
EffectTask: *effTask,
delay: delay,
}
}
func (t *DelayEffectTask) Exec(ctx Battle) bool {
t.delay -= ctx.GetDeltaTime()
if t.delay > 0 {
return false
}
t.eff.OnEffect(t.skill, t.effCfg, t.target)
return true
}
| 412 | 0.694175 | 1 | 0.694175 | game-dev | MEDIA | 0.779523 | game-dev | 0.559077 | 1 | 0.559077 |
Dimbreath/AzurLaneData | 4,411 | en-US/view/activity/subpages/tianhouskinpage.lua | slot0 = class("TianHouSkinPage", import("...base.BaseActivityPage"))
slot1 = {
[0] = {
color = "ffffff",
name = "none"
},
{
color = "ffed95",
name = "na"
},
{
color = "feb8ff",
name = "k"
},
{
color = "ad92ff",
name = "rb"
},
{
color = "affff4",
name = "zn"
},
{
color = "ffa685",
name = "ca"
},
{
color = "c1ffa7",
name = "cu"
}
}
function slot0.GetCurrentDay()
return pg.TimeMgr.GetInstance():STimeDescS(pg.TimeMgr.GetInstance():GetServerTime(), "*t").yday
end
function slot0.OnInit(slot0)
slot0.bg = slot0:findTF("AD")
slot0.helpBtn = slot0:findTF("help", slot0.bg)
slot0.gotTag = slot0:findTF("got", slot0.bg)
slot0.medalText = slot0:findTF("medal", slot0.bg)
slot0.ticketText = slot0:findTF("ticket", slot0.bg)
slot0.fireworkBtn = slot0:findTF("game_list/firework", slot0.bg)
slot0.shootBtn = slot0:findTF("game_list/shoot", slot0.bg)
slot0.foodBtn = slot0:findTF("game_list/food", slot0.bg)
slot0.effectNode = slot0:findTF("effectNode", slot0.bg)
slot0.playEffectBtn = slot0:findTF("fire", slot0.bg)
end
function slot0.OnFirstFlush(slot0)
slot0.hubID = slot0.activity:getConfig("config_id")
onButton(slot0, slot0.helpBtn, function ()
pg.MsgboxMgr.GetInstance():ShowMsgBox({
type = MSGBOX_TYPE_HELP,
helps = i18n("help_summer_feast")
})
end, SFX_PANEL)
onButton(slot0, slot0.fireworkBtn, function ()
pg.m02:sendNotification(GAME.GO_MINI_GAME, 26)
end, SFX_PANEL)
onButton(slot0, slot0.shootBtn, function ()
pg.m02:sendNotification(GAME.GO_MINI_GAME, 27)
end, SFX_PANEL)
onButton(slot0, slot0.foodBtn, function ()
pg.m02:sendNotification(GAME.GO_MINI_GAME, 25)
end, SFX_PANEL)
slot0.ishow = getProxy(MiniGameProxy):GetMiniGameData(26):GetRuntimeData("elements") and #slot2 >= 4 and slot2[4] == slot0.GetCurrentDay()
onButton(slot0, slot0.playEffectBtn, function ()
if not uv0.ishow then
return
end
uv0:PlayFirework(uv1)
setActive(uv0.playEffectBtn, false)
end, SFX_PANEL)
blinkAni(slot0:findTF("light", slot0.playEffectBtn), 0.5)
end
function slot0.OnUpdateFlush(slot0)
slot2 = getProxy(MiniGameProxy):GetHubByHubId(slot0.hubID)
setText(slot0.ticketText, slot2.count)
setText(slot0.medalText, slot2.usedtime .. "/" .. slot2:getConfig("reward_need"))
setActive(slot0.gotTag, slot2.ultimate ~= 0)
if slot2.ultimate == 0 and slot3 <= slot2.usedtime then
pg.m02:sendNotification(GAME.SEND_MINI_GAME_OP, {
hubid = slot0.hubID,
cmd = MiniGameOPCommand.CMD_ULTIMATE,
args1 = {}
})
end
setActive(slot0.playEffectBtn, slot0.ishow)
pg.NewStoryMgr.GetInstance():Play("TIANHOUYUYI1")
end
function slot0.TransformColor(slot0)
return Color.New(tonumber(string.sub(slot0, 1, 2), 16) / 255, tonumber(string.sub(slot0, 3, 4), 16) / 255, tonumber(string.sub(slot0, 5, 6), 16) / 255)
end
function slot0.PlayFirework(slot0, slot1)
slot1 = slot1 or {
0,
0,
0
}
slot2 = UnityEngine.ParticleSystem.MinMaxGradient.New
pg.PoolMgr.GetInstance():GetPrefab("ui/firework", "", false, function (slot0)
slot2 = tf(slot0):Find("Fire"):GetComponent("ParticleSystem").main.startColor
tf(slot0):Find("Fire"):GetComponent("ParticleSystem").main.startColor = uv0(uv1.TransformColor(uv2[uv3[1]].color))
tf(slot0):Find("Fire/par_small"):GetComponent("ParticleSystem").main.startColor = uv0(uv1.TransformColor(uv2[uv3[2]].color))
tf(slot0):Find("Fire/par_small/par_big"):GetComponent("ParticleSystem").main.startColor = uv0(uv1.TransformColor(uv2[uv3[3]].color))
setParent(slot0, uv1.effectNode)
slot0.transform.localPosition = Vector2(0, 0)
uv1.fireEffect = slot0
end)
slot0:PlaySE()
end
function slot0.ClearEffectFirework(slot0)
slot0:StopSE()
if slot0.fireEffect then
pg.PoolMgr.GetInstance():ReturnPrefab("ui/firework", "", slot0.fireEffect)
end
end
function slot0.PlaySE(slot0)
if slot0.SETimer then
return
end
slot0.SECount = 10
slot0.SETimer = Timer.New(function ()
uv0.SECount = uv0.SECount - 1
if uv0.SECount <= 0 then
uv0.SECount = math.random(5, 20)
pg.CriMgr.GetInstance():PlaySE_V3("battle-firework")
end
end, 0.1, -1)
slot0.SETimer:Start()
end
function slot0.StopSE(slot0)
if slot0.SETimer then
pg.CriMgr.GetInstance():StopSEBattle_V3()
slot0.SETimer:Stop()
slot0.SETimer = nil
end
end
function slot0.OnHideFlush(slot0)
slot0:ClearEffectFirework()
end
function slot0.OnDestroy(slot0)
slot0:ClearEffectFirework()
end
return slot0
| 412 | 0.775055 | 1 | 0.775055 | game-dev | MEDIA | 0.948482 | game-dev | 0.922291 | 1 | 0.922291 |
rockthejvm/zio-course | 2,778 | src/main/scala/com/rockthejvm/part5testing/PropertyBasedTesting.scala | package com.rockthejvm.part5testing
import zio._
import zio.test._
import com.rockthejvm.utils._
object PropertyBasedTesting extends ZIOSpecDefault {
// "proofs"
// for all x,y,z, we have (x + y) + z == x + (y + z)
// shrinking
def spec = test("property-based-testing basics") {
check(Gen.int, Gen.int, Gen.int) { (x,y,z) =>
assertTrue(((x + y) + z) == (x - (y + z)))
}
}
/*
Property-based testing:
"for all x,y,z,... we have Statement to be true."
translation:
check(a bunch of generators) { (a,b,c,d,...) =>
assertions on the values generated
}
*/
// Gen[R,A]; R = "environment", A = value
val intGenerator = Gen.int
val charGenerator = Gen.char // also alphaChar, alphaNumericChar, asciiChar, hexChar, printableChar etc
val stringGenerator = Gen.string
val cappedLengthStringGenerator = Gen.stringN(10)(Gen.alphaNumericChar)
val constGenerator = Gen.const("Scala")
val valuesGenerator = Gen.elements(1,3,5,7,9)
val valuesIterableGenerator = Gen.fromIterable(1 to 1000)
val uniformDoublesGenerator = Gen.uniform // select doubles between 0 and 1
// produce collections
val listGenerator = Gen.listOf(Gen.string) // unbounded list of strings
val finiteSetGenerator = Gen.setOfN(10)(Gen.int) // sets of 10 integers
// option, either
val optionGenerator = Gen.option(Gen.int) // produce Option[Int]
val eitherGenerator = Gen.either(Gen.string, Gen.int) // produce Either[String, Int]
// combinators
val zippedGenerator = Gen.int.zip(Gen.string) // produces (Int, String)
val filteredGenerator = intGenerator.filter(_ % 3 == 0)
val mappedGenerator = intGenerator.map(n => (1 to n).map(_ => 'a').mkString)
val flatMappedGenerator = filteredGenerator.flatMap(l => Gen.stringN(l)(Gen.alphaNumericChar))
// for-comprehension
val uuidGenerator = for {
part1 <- Gen.stringN(8)(Gen.alphaNumericChar)
part2 <- Gen.stringN(4)(Gen.alphaNumericChar)
part3 <- Gen.stringN(4)(Gen.alphaNumericChar)
part4 <- Gen.stringN(12)(Gen.alphaNumericChar)
} yield s"$part1-$part2-$part3-$part4"
// general
val randomGenerator = Gen.fromRandom(random => random.nextUUID)
val effectGenerator = Gen.fromZIO(ZIO.succeed(42))
val generalGenerator = Gen.unfoldGen(0)(i => Gen.const(i + 1).zip(Gen.stringN(i)(Gen.alphaNumericChar)))
// lists of strings with the property that every string will have increasing length
}
object GenerationPlayground extends ZIOAppDefault {
def run = {
val generalGenerator = Gen.unfoldGen(0)(i => Gen.const(i + 1).zip(Gen.stringN(i)(Gen.alphaNumericChar)))
val generatedListsZIO = generalGenerator.runCollectN(100)
val generatedListsZIO_v2 = generatedListsZIO.provideLayer(Sized.live(50))
generatedListsZIO_v2.debugThread
}
}
| 412 | 0.829682 | 1 | 0.829682 | game-dev | MEDIA | 0.24771 | game-dev | 0.63534 | 1 | 0.63534 |
worron/awesome-config | 29,096 | color/blue/keys-config.lua | -----------------------------------------------------------------------------------------------------------------------
-- Hotkeys and mouse buttons config --
-----------------------------------------------------------------------------------------------------------------------
-- Grab environment
local table = table
local awful = require("awful")
local redflat = require("redflat")
-- Initialize tables and vars for module
-----------------------------------------------------------------------------------------------------------------------
local hotkeys = { mouse = {}, raw = {}, keys = {}, fake = {} }
-- key aliases
local apprunner = redflat.float.apprunner
local appswitcher = redflat.float.appswitcher
local current = redflat.widget.tasklist.filter.currenttags
local allscr = redflat.widget.tasklist.filter.allscreen
local laybox = redflat.widget.layoutbox
local redtip = redflat.float.hotkeys
local laycom = redflat.layout.common
local grid = redflat.layout.grid
local map = redflat.layout.map
local redtitle = redflat.titlebar
local qlaunch = redflat.float.qlaunch
-- Key support functions
-----------------------------------------------------------------------------------------------------------------------
-- change window focus by history
local function focus_to_previous()
awful.client.focus.history.previous()
if client.focus then client.focus:raise() end
end
-- change window focus by direction
local focus_switch_byd = function(dir)
return function()
awful.client.focus.bydirection(dir)
if client.focus then client.focus:raise() end
end
end
-- minimize and restore windows
local function minimize_all()
for _, c in ipairs(client.get()) do
if current(c, mouse.screen) then c.minimized = true end
end
end
local function minimize_all_except_focused()
for _, c in ipairs(client.get()) do
if current(c, mouse.screen) and c ~= client.focus then c.minimized = true end
end
end
local function restore_all()
for _, c in ipairs(client.get()) do
if current(c, mouse.screen) and c.minimized then c.minimized = false end
end
end
local function restore_client()
local c = awful.client.restore()
if c then client.focus = c; c:raise() end
end
-- close window
local function kill_all()
for _, c in ipairs(client.get()) do
if current(c, mouse.screen) and not c.sticky then c:kill() end
end
end
-- new clients placement
local function toggle_placement(env)
env.set_slave = not env.set_slave
redflat.float.notify:show({ text = (env.set_slave and "Slave" or "Master") .. " placement" })
end
-- numeric keys function builders
local function tag_numkey(i, mod, action)
return awful.key(
mod, "#" .. i + 9,
function ()
local screen = awful.screen.focused()
local tag = screen.tags[i]
if tag then action(tag) end
end
)
end
local function client_numkey(i, mod, action)
return awful.key(
mod, "#" .. i + 9,
function ()
if client.focus then
local tag = client.focus.screen.tags[i]
if tag then action(tag) end
end
end
)
end
-- brightness functions
local brightness = function(args)
redflat.float.brightness:change_with_xbacklight(args) -- use xbacklight
end
-- right bottom corner position
local rb_corner = function()
return { x = screen[mouse.screen].workarea.x + screen[mouse.screen].workarea.width,
y = screen[mouse.screen].workarea.y + screen[mouse.screen].workarea.height }
end
-- Build hotkeys depended on config parameters
-----------------------------------------------------------------------------------------------------------------------
function hotkeys:init(args)
-- Init vars
args = args or {}
local env = args.env
local volume = args.volume
local mainmenu = args.menu
local appkeys = args.appkeys or {}
self.mouse.root = (awful.util.table.join(
awful.button({ }, 3, function () mainmenu:toggle() end),
awful.button({ }, 4, awful.tag.viewnext),
awful.button({ }, 5, awful.tag.viewprev)
))
-- volume functions
local volume_raise = function() volume:change_volume({ show_notify = true }) end
local volume_lower = function() volume:change_volume({ show_notify = true, down = true }) end
local volume_mute = function() volume:mute() end
-- Init widgets
redflat.float.qlaunch:init()
-- Application hotkeys helper
--------------------------------------------------------------------------------
local apphelper = function(keys)
if not client.focus then return end
local app = client.focus.class:lower()
for name, sheet in pairs(keys) do
if name == app then
redtip:set_pack(
client.focus.class, sheet.pack, sheet.style.column, sheet.style.geometry,
function() redtip:remove_pack() end
)
redtip:show()
return
end
end
redflat.float.notify:show({ text = "No tips for " .. client.focus.class })
end
-- Keys for widgets
--------------------------------------------------------------------------------
-- Apprunner widget
------------------------------------------------------------
local apprunner_keys_move = {
{
{ env.mod }, "k", function() apprunner:down() end,
{ description = "Select next item", group = "Navigation" }
},
{
{ env.mod }, "i", function() apprunner:up() end,
{ description = "Select previous item", group = "Navigation" }
},
}
-- apprunner:set_keys(awful.util.table.join(apprunner.keys.move, apprunner_keys_move), "move")
apprunner:set_keys(apprunner_keys_move, "move")
-- Menu widget
------------------------------------------------------------
local menu_keys_move = {
{
{ env.mod }, "k", redflat.menu.action.down,
{ description = "Select next item", group = "Navigation" }
},
{
{ env.mod }, "i", redflat.menu.action.up,
{ description = "Select previous item", group = "Navigation" }
},
{
{ env.mod }, "j", redflat.menu.action.back,
{ description = "Go back", group = "Navigation" }
},
{
{ env.mod }, "l", redflat.menu.action.enter,
{ description = "Open submenu", group = "Navigation" }
},
}
-- redflat.menu:set_keys(awful.util.table.join(redflat.menu.keys.move, menu_keys_move), "move")
redflat.menu:set_keys(menu_keys_move, "move")
-- Appswitcher widget
------------------------------------------------------------
local appswitcher_keys = {
{
{ env.mod }, "a", function() appswitcher:switch() end,
{ description = "Select next app", group = "Navigation" }
},
{
{ env.mod, "Shift" }, "a", function() appswitcher:switch() end,
{} -- hidden key
},
{
{ env.mod }, "q", function() appswitcher:switch({ reverse = true }) end,
{ description = "Select previous app", group = "Navigation" }
},
{
{ env.mod, "Shift" }, "q", function() appswitcher:switch({ reverse = true }) end,
{} -- hidden key
},
{
{}, "Super_L", function() appswitcher:hide() end,
{ description = "Activate and exit", group = "Action" }
},
{
{ env.mod }, "Super_L", function() appswitcher:hide() end,
{} -- hidden key
},
{
{ env.mod, "Shift" }, "Super_L", function() appswitcher:hide() end,
{} -- hidden key
},
{
{}, "Return", function() appswitcher:hide() end,
{ description = "Activate and exit", group = "Action" }
},
{
{}, "Escape", function() appswitcher:hide(true) end,
{ description = "Exit", group = "Action" }
},
{
{ env.mod }, "Escape", function() appswitcher:hide(true) end,
{} -- hidden key
},
{
{ env.mod }, "F1", function() redtip:show() end,
{ description = "Show hotkeys helper", group = "Action" }
},
}
appswitcher:set_keys(appswitcher_keys)
-- Emacs like key sequences
--------------------------------------------------------------------------------
-- initial key
local keyseq = { { env.mod }, "c", {}, {} }
-- group
keyseq[3] = {
{ {}, "k", {}, {} }, -- application kill group
{ {}, "c", {}, {} }, -- client managment group
{ {}, "r", {}, {} }, -- client managment group
{ {}, "n", {}, {} }, -- client managment group
{ {}, "g", {}, {} }, -- run or rise group
{ {}, "f", {}, {} }, -- launch application group
}
-- quick launch key sequence actions
for i = 1, 9 do
local ik = tostring(i)
table.insert(keyseq[3][5][3], {
{}, ik, function() qlaunch:run_or_raise(ik) end,
{ description = "Run or rise application №" .. ik, group = "Run or Rise", keyset = { ik } }
})
table.insert(keyseq[3][6][3], {
{}, ik, function() qlaunch:run_or_raise(ik, true) end,
{ description = "Launch application №".. ik, group = "Quick Launch", keyset = { ik } }
})
end
-- application kill sequence actions
keyseq[3][1][3] = {
{
{}, "f", function() if client.focus then client.focus:kill() end end,
{ description = "Kill focused client", group = "Kill application", keyset = { "f" } }
},
{
{}, "a", kill_all,
{ description = "Kill all clients with current tag", group = "Kill application", keyset = { "a" } }
},
}
-- client managment sequence actions
keyseq[3][2][3] = {
{
{}, "p", function () toggle_placement(env) end,
{ description = "Switch master/slave window placement", group = "Clients managment", keyset = { "p" } }
},
}
keyseq[3][3][3] = {
{
{}, "f", restore_client,
{ description = "Restore minimized client", group = "Clients managment", keyset = { "f" } }
},
{
{}, "a", restore_all,
{ description = "Restore all clients with current tag", group = "Clients managment", keyset = { "a" } }
},
}
keyseq[3][4][3] = {
{
{}, "f", function() if client.focus then client.focus.minimized = true end end,
{ description = "Minimized focused client", group = "Clients managment", keyset = { "f" } }
},
{
{}, "a", minimize_all,
{ description = "Minimized all clients with current tag", group = "Clients managment", keyset = { "a" } }
},
{
{}, "e", minimize_all_except_focused,
{ description = "Minimized all clients except focused", group = "Clients managment", keyset = { "e" } }
},
}
-- Layouts
--------------------------------------------------------------------------------
-- shared layout keys
local layout_tile = {
{
{ env.mod }, "l", function () awful.tag.incmwfact( 0.05) end,
{ description = "Increase master width factor", group = "Layout" }
},
{
{ env.mod }, "j", function () awful.tag.incmwfact(-0.05) end,
{ description = "Decrease master width factor", group = "Layout" }
},
{
{ env.mod }, "i", function () awful.client.incwfact( 0.05) end,
{ description = "Increase window factor of a client", group = "Layout" }
},
{
{ env.mod }, "k", function () awful.client.incwfact(-0.05) end,
{ description = "Decrease window factor of a client", group = "Layout" }
},
{
{ env.mod, }, "+", function () awful.tag.incnmaster( 1, nil, true) end,
{ description = "Increase the number of master clients", group = "Layout" }
},
{
{ env.mod }, "-", function () awful.tag.incnmaster(-1, nil, true) end,
{ description = "Decrease the number of master clients", group = "Layout" }
},
{
{ env.mod, "Control" }, "+", function () awful.tag.incncol( 1, nil, true) end,
{ description = "Increase the number of columns", group = "Layout" }
},
{
{ env.mod, "Control" }, "-", function () awful.tag.incncol(-1, nil, true) end,
{ description = "Decrease the number of columns", group = "Layout" }
},
}
laycom:set_keys(layout_tile, "tile")
-- grid layout keys
local layout_grid_move = {
{
{ env.mod }, "KP_Up", function() grid.move_to("up") end,
{ description = "Move window up", group = "Movement" }
},
{
{ env.mod }, "KP_Down", function() grid.move_to("down") end,
{ description = "Move window down", group = "Movement" }
},
{
{ env.mod }, "KP_Left", function() grid.move_to("left") end,
{ description = "Move window left", group = "Movement" }
},
{
{ env.mod }, "KP_right", function() grid.move_to("right") end,
{ description = "Move window right", group = "Movement" }
},
{
{ env.mod, "Control" }, "KP_Up", function() grid.move_to("up", true) end,
{ description = "Move window up by bound", group = "Movement" }
},
{
{ env.mod, "Control" }, "KP_Down", function() grid.move_to("down", true) end,
{ description = "Move window down by bound", group = "Movement" }
},
{
{ env.mod, "Control" }, "KP_Left", function() grid.move_to("left", true) end,
{ description = "Move window left by bound", group = "Movement" }
},
{
{ env.mod, "Control" }, "KP_Right", function() grid.move_to("right", true) end,
{ description = "Move window right by bound", group = "Movement" }
},
}
local layout_grid_resize = {
{
{ env.mod }, "i", function() grid.resize_to("up") end,
{ description = "Inrease window size to the up", group = "Resize" }
},
{
{ env.mod }, "k", function() grid.resize_to("down") end,
{ description = "Inrease window size to the down", group = "Resize" }
},
{
{ env.mod }, "j", function() grid.resize_to("left") end,
{ description = "Inrease window size to the left", group = "Resize" }
},
{
{ env.mod }, "l", function() grid.resize_to("right") end,
{ description = "Inrease window size to the right", group = "Resize" }
},
{
{ env.mod, "Shift" }, "i", function() grid.resize_to("up", nil, true) end,
{ description = "Decrease window size from the up", group = "Resize" }
},
{
{ env.mod, "Shift" }, "k", function() grid.resize_to("down", nil, true) end,
{ description = "Decrease window size from the down", group = "Resize" }
},
{
{ env.mod, "Shift" }, "j", function() grid.resize_to("left", nil, true) end,
{ description = "Decrease window size from the left", group = "Resize" }
},
{
{ env.mod, "Shift" }, "l", function() grid.resize_to("right", nil, true) end,
{ description = "Decrease window size from the right", group = "Resize" }
},
{
{ env.mod, "Control" }, "i", function() grid.resize_to("up", true) end,
{ description = "Increase window size to the up by bound", group = "Resize" }
},
{
{ env.mod, "Control" }, "k", function() grid.resize_to("down", true) end,
{ description = "Increase window size to the down by bound", group = "Resize" }
},
{
{ env.mod, "Control" }, "j", function() grid.resize_to("left", true) end,
{ description = "Increase window size to the left by bound", group = "Resize" }
},
{
{ env.mod, "Control" }, "l", function() grid.resize_to("right", true) end,
{ description = "Increase window size to the right by bound", group = "Resize" }
},
{
{ env.mod, "Control", "Shift" }, "i", function() grid.resize_to("up", true, true) end,
{ description = "Decrease window size from the up by bound ", group = "Resize" }
},
{
{ env.mod, "Control", "Shift" }, "k", function() grid.resize_to("down", true, true) end,
{ description = "Decrease window size from the down by bound ", group = "Resize" }
},
{
{ env.mod, "Control", "Shift" }, "j", function() grid.resize_to("left", true, true) end,
{ description = "Decrease window size from the left by bound ", group = "Resize" }
},
{
{ env.mod, "Control", "Shift" }, "l", function() grid.resize_to("right", true, true) end,
{ description = "Decrease window size from the right by bound ", group = "Resize" }
},
}
redflat.layout.grid:set_keys(layout_grid_move, "move")
redflat.layout.grid:set_keys(layout_grid_resize, "resize")
-- user map layout keys
local layout_map_layout = {
{
{ env.mod }, "s", function() map.swap_group() end,
{ description = "Change placement direction for group", group = "Layout" }
},
{
{ env.mod }, "v", function() map.new_group(true) end,
{ description = "Create new vertical group", group = "Layout" }
},
{
{ env.mod }, "h", function() map.new_group(false) end,
{ description = "Create new horizontal group", group = "Layout" }
},
{
{ env.mod, "Control" }, "v", function() map.insert_group(true) end,
{ description = "Insert new vertical group before active", group = "Layout" }
},
{
{ env.mod, "Control" }, "h", function() map.insert_group(false) end,
{ description = "Insert new horizontal group before active", group = "Layout" }
},
{
{ env.mod }, "d", function() map.delete_group() end,
{ description = "Destroy group", group = "Layout" }
},
{
{ env.mod, "Control" }, "d", function() map.clean_groups() end,
{ description = "Destroy all empty groups", group = "Layout" }
},
{
{ env.mod }, "f", function() map.set_active() end,
{ description = "Set active group", group = "Layout" }
},
{
{ env.mod }, "g", function() map.move_to_active() end,
{ description = "Move focused client to active group", group = "Layout" }
},
{
{ env.mod, "Control" }, "f", function() map.hilight_active() end,
{ description = "Hilight active group", group = "Layout" }
},
{
{ env.mod }, "a", function() map.switch_active(1) end,
{ description = "Activate next group", group = "Layout" }
},
{
{ env.mod }, "q", function() map.switch_active(-1) end,
{ description = "Activate previous group", group = "Layout" }
},
{
{ env.mod }, "]", function() map.move_group(1) end,
{ description = "Move active group to the top", group = "Layout" }
},
{
{ env.mod }, "[", function() map.move_group(-1) end,
{ description = "Move active group to the bottom", group = "Layout" }
},
{
{ env.mod }, "r", function() map.reset_tree() end,
{ description = "Reset layout structure", group = "Layout" }
},
}
local layout_map_resize = {
{
{ env.mod }, "j", function() map.incfactor(nil, 0.1, false) end,
{ description = "Increase window horizontal size factor", group = "Resize" }
},
{
{ env.mod }, "l", function() map.incfactor(nil, -0.1, false) end,
{ description = "Decrease window horizontal size factor", group = "Resize" }
},
{
{ env.mod }, "i", function() map.incfactor(nil, 0.1, true) end,
{ description = "Increase window vertical size factor", group = "Resize" }
},
{
{ env.mod }, "k", function() map.incfactor(nil, -0.1, true) end,
{ description = "Decrease window vertical size factor", group = "Resize" }
},
{
{ env.mod, "Control" }, "j", function() map.incfactor(nil, 0.1, false, true) end,
{ description = "Increase group horizontal size factor", group = "Resize" }
},
{
{ env.mod, "Control" }, "l", function() map.incfactor(nil, -0.1, false, true) end,
{ description = "Decrease group horizontal size factor", group = "Resize" }
},
{
{ env.mod, "Control" }, "i", function() map.incfactor(nil, 0.1, true, true) end,
{ description = "Increase group vertical size factor", group = "Resize" }
},
{
{ env.mod, "Control" }, "k", function() map.incfactor(nil, -0.1, true, true) end,
{ description = "Decrease group vertical size factor", group = "Resize" }
},
}
redflat.layout.map:set_keys(layout_map_layout, "layout")
redflat.layout.map:set_keys(layout_map_resize, "resize")
-- Global keys
--------------------------------------------------------------------------------
self.raw.root = {
{
{ env.mod }, "F1", function() redtip:show() end,
{ description = "[Hold] Show awesome hotkeys helper", group = "Main" }
},
{
{ env.mod, "Control" }, "F1", function() apphelper(appkeys) end,
{ description = "[Hold] Show hotkeys helper for application", group = "Main" }
},
{
{ env.mod }, "c", function() redflat.float.keychain:activate(keyseq, "User") end,
{ description = "[Hold] User key sequence", group = "Main" }
},
{
{ env.mod }, "F2", function () redflat.service.navigator:run() end,
{ description = "[Hold] Tiling window control mode", group = "Window control" }
},
{
{ env.mod }, "h", function() redflat.float.control:show() end,
{ description = "[Hold] Floating window control mode", group = "Window control" }
},
{
{ env.mod }, "Return", function() awful.spawn(env.terminal) end,
{ description = "Open a terminal", group = "Actions" }
},
{
{ env.mod, "Mod1" }, "space", function() awful.spawn("gpaste-client ui") end,
{ description = "Clipboard manager", group = "Actions" }
},
{
{ env.mod, "Control" }, "r", awesome.restart,
{ description = "Reload WM", group = "Actions" }
},
{
{ env.mod }, "l", focus_switch_byd("right"),
{ description = "Go to right client", group = "Client focus" }
},
{
{ env.mod }, "j", focus_switch_byd("left"),
{ description = "Go to left client", group = "Client focus" }
},
{
{ env.mod }, "i", focus_switch_byd("up"),
{ description = "Go to upper client", group = "Client focus" }
},
{
{ env.mod }, "k", focus_switch_byd("down"),
{ description = "Go to lower client", group = "Client focus" }
},
{
{ env.mod }, "u", awful.client.urgent.jumpto,
{ description = "Go to urgent client", group = "Client focus" }
},
{
{ env.mod }, "Tab", focus_to_previous,
{ description = "Go to previos client", group = "Client focus" }
},
{
{ env.mod }, "w", function() mainmenu:show() end,
{ description = "Show main menu", group = "Widgets" }
},
{
{ env.mod }, "r", function() apprunner:show() end,
{ description = "Application launcher", group = "Widgets" }
},
{
{ env.mod }, "p", function() redflat.float.prompt:run() end,
{ description = "Show the prompt box", group = "Widgets" }
},
{
{ env.mod }, "x", function() redflat.float.top:show("cpu") end,
{ description = "Show the top process list", group = "Widgets" }
},
{
{ env.mod, "Control" }, "m", function() redflat.widget.mail:update(true) end,
{ description = "Check new mail", group = "Widgets" }
},
{
{ env.mod, "Control" }, "i", function() redflat.widget.minitray:toggle() end,
{ description = "Show minitray", group = "Widgets" }
},
{
{ env.mod, "Control" }, "u", function() redflat.widget.updates:update(true) end,
{ description = "Check available updates", group = "Widgets" }
},
{
{ env.mod }, "g", function() qlaunch:show() end,
{ description = "Application quick launcher", group = "Widgets" }
},
{
{ env.mod }, "z", function() redflat.service.logout:show() end,
{ description = "Log out screen", group = "Widgets" }
},
{
{ env.mod }, "y", function() laybox:toggle_menu(mouse.screen.selected_tag) end,
{ description = "Show layout menu", group = "Layouts" }
},
{
{ env.mod}, "Up", function() awful.layout.inc(1) end,
{ description = "Select next layout", group = "Layouts" }
},
{
{ env.mod }, "Down", function() awful.layout.inc(-1) end,
{ description = "Select previous layout", group = "Layouts" }
},
{
{}, "XF86MonBrightnessUp", function() brightness({ step = 2 }) end,
{ description = "Increase brightness", group = "Brightness control" }
},
{
{}, "XF86MonBrightnessDown", function() brightness({ step = 2, down = true }) end,
{ description = "Reduce brightness", group = "Brightness control" }
},
{
{}, "XF86AudioRaiseVolume", volume_raise,
{ description = "Increase volume", group = "Volume control" }
},
{
{}, "XF86AudioLowerVolume", volume_lower,
{ description = "Reduce volume", group = "Volume control" }
},
{
{}, "XF86AudioMute", volume_mute,
{ description = "Mute audio", group = "Volume control" }
},
{
{ env.mod }, "a", nil, function() appswitcher:show({ filter = current }) end,
{ description = "Switch to next with current tag", group = "Application switcher" }
},
{
{ env.mod }, "q", nil, function() appswitcher:show({ filter = current, reverse = true }) end,
{ description = "Switch to previous with current tag", group = "Application switcher" }
},
{
{ env.mod, "Shift" }, "a", nil, function() appswitcher:show({ filter = allscr }) end,
{ description = "Switch to next through all tags", group = "Application switcher" }
},
{
{ env.mod, "Shift" }, "q", nil, function() appswitcher:show({ filter = allscr, reverse = true }) end,
{ description = "Switch to previous through all tags", group = "Application switcher" }
},
{
{ env.mod }, "Escape", awful.tag.history.restore,
{ description = "Go previos tag", group = "Tag navigation" }
},
{
{ env.mod }, "Right", awful.tag.viewnext,
{ description = "View next tag", group = "Tag navigation" }
},
{
{ env.mod }, "Left", awful.tag.viewprev,
{ description = "View previous tag", group = "Tag navigation" }
},
{
{ env.mod }, "t", function() redtitle.toggle(client.focus) end,
{ description = "Show/hide titlebar for focused client", group = "Titlebar" }
},
--{
-- { env.mod, "Control" }, "t", function() redtitle.switch(client.focus) end,
-- { description = "Switch titlebar view for focused client", group = "Titlebar" }
--},
{
{ env.mod, "Shift" }, "t", function() redtitle.toggle_all() end,
{ description = "Show/hide titlebar for all clients", group = "Titlebar" }
},
{
{ env.mod, "Control", "Shift" }, "t", function() redtitle.global_switch() end,
{ description = "Switch titlebar view for all clients", group = "Titlebar" }
},
{
{ env.mod }, "e", function() redflat.float.player:show(rb_corner()) end,
{ description = "Show/hide widget", group = "Audio player" }
},
{
{}, "XF86AudioPlay", function() redflat.float.player:action("PlayPause") end,
{ description = "Play/Pause track", group = "Audio player" }
},
{
{}, "XF86AudioNext", function() redflat.float.player:action("Next") end,
{ description = "Next track", group = "Audio player" }
},
{
{}, "XF86AudioPrev", function() redflat.float.player:action("Previous") end,
{ description = "Previous track", group = "Audio player" }
},
{
{ env.mod, "Control" }, "s", function() for s in screen do env.wallpaper(s) end end,
{} -- hidden key
}
}
-- Client keys
--------------------------------------------------------------------------------
self.raw.client = {
{
{ env.mod }, "f", function(c) c.fullscreen = not c.fullscreen; c:raise() end,
{ description = "Toggle fullscreen", group = "Client keys" }
},
{
{ env.mod }, "F4", function(c) c:kill() end,
{ description = "Close", group = "Client keys" }
},
{
{ env.mod, "Control" }, "f", awful.client.floating.toggle,
{ description = "Toggle floating", group = "Client keys" }
},
{
{ env.mod, "Control" }, "o", function(c) c.ontop = not c.ontop end,
{ description = "Toggle keep on top", group = "Client keys" }
},
{
{ env.mod }, "n", function(c) c.minimized = true end,
{ description = "Minimize", group = "Client keys" }
},
{
{ env.mod }, "m", function(c) c.maximized = not c.maximized; c:raise() end,
{ description = "Maximize", group = "Client keys" }
}
}
self.keys.root = redflat.util.key.build(self.raw.root)
self.keys.client = redflat.util.key.build(self.raw.client)
-- Numkeys
--------------------------------------------------------------------------------
-- add real keys without description here
for i = 1, 9 do
self.keys.root = awful.util.table.join(
self.keys.root,
tag_numkey(i, { env.mod }, function(t) t:view_only() end),
tag_numkey(i, { env.mod, "Control" }, function(t) awful.tag.viewtoggle(t) end),
client_numkey(i, { env.mod, "Shift" }, function(t) client.focus:move_to_tag(t) end),
client_numkey(i, { env.mod, "Control", "Shift" }, function(t) client.focus:toggle_tag(t) end)
)
end
-- make fake keys with description special for key helper widget
local numkeys = { "1", "2", "3", "4", "5", "6", "7", "8", "9" }
self.fake.numkeys = {
{
{ env.mod }, "1..9", nil,
{ description = "Switch to tag", group = "Numeric keys", keyset = numkeys }
},
{
{ env.mod, "Control" }, "1..9", nil,
{ description = "Toggle tag", group = "Numeric keys", keyset = numkeys }
},
{
{ env.mod, "Shift" }, "1..9", nil,
{ description = "Move focused client to tag", group = "Numeric keys", keyset = numkeys }
},
{
{ env.mod, "Control", "Shift" }, "1..9", nil,
{ description = "Toggle focused client on tag", group = "Numeric keys", keyset = numkeys }
},
}
-- Hotkeys helper setup
--------------------------------------------------------------------------------
redflat.float.hotkeys:set_pack("Main", awful.util.table.join(self.raw.root, self.raw.client, self.fake.numkeys), 2)
-- Mouse buttons
--------------------------------------------------------------------------------
self.mouse.client = awful.util.table.join(
awful.button({}, 1, function (c) client.focus = c; c:raise() end),
awful.button({}, 2, awful.mouse.client.move),
awful.button({ env.mod }, 3, awful.mouse.client.resize),
awful.button({}, 8, function(c) c:kill() end)
)
-- Set root hotkeys
--------------------------------------------------------------------------------
root.keys(self.keys.root)
root.buttons(self.mouse.root)
end
-- End
-----------------------------------------------------------------------------------------------------------------------
return hotkeys
| 412 | 0.925579 | 1 | 0.925579 | game-dev | MEDIA | 0.729587 | game-dev,desktop-app | 0.95743 | 1 | 0.95743 |
peace-maker/smrpg | 7,921 | scripting/smrpg_effects/rendercolor.sp | /**
* This file is part of the SM:RPG Effect Hub.
* Handles the render color of players
*/
// Default render color to reset to when the fade finished.
int g_iDefaultColor[MAXPLAYERS+1][4];
float g_fColor[MAXPLAYERS+1][4];
int g_iColorFadeTarget[MAXPLAYERS+1][4];
float g_fColorFadeStep[MAXPLAYERS+1][4];
// Save which plugin last changed the color, so only that plugin may reset the color to default.
Handle g_hLastAccessedPlugin[MAXPLAYERS+1][4];
/**
* Setup helpers
*/
void RegisterRenderColorNatives()
{
CreateNative("SMRPG_SetClientDefaultColor", Native_SetClientDefaultColor);
CreateNative("SMRPG_SetClientRenderColor", Native_SetClientRenderColor);
CreateNative("SMRPG_SetClientRenderColorFadeTarget", Native_SetClientRenderColorFadeTarget);
CreateNative("SMRPG_SetClientRenderColorFadeStepsize", Native_SetClientRenderColorFadeStepsize);
CreateNative("SMRPG_ResetClientToDefaultColor", Native_ResetClientToDefaultColor);
}
void ResetRenderColorClient(int client)
{
for(int i=0;i<4;i++)
{
g_iDefaultColor[client][i] = 255;
g_iColorFadeTarget[client][i] = -1;
g_fColorFadeStep[client][i] = 1.0;
g_fColor[client][i] = 255.0;
g_hLastAccessedPlugin[client][i] = null;
}
}
void ApplyDefaultRenderColor(int client)
{
for(int i=0;i<4;i++)
{
g_iColorFadeTarget[client][i] = -1;
g_fColor[client][i] = 255.0;
}
Help_ResetClientToDefaultColor(null, client, true, true, true, true, true);
}
// Fade players from current color linearly to the fade target.
public void OnGameFrame()
{
bool bFade;
for(int client=1;client<=MaxClients;client++)
{
if(!IsClientInGame(client) || !IsPlayerAlive(client))
continue;
bFade = false;
int iColor[4];
for(int c=0;c<4;c++)
{
// Don't change this channel by default.
iColor[c] = -1;
// We don't want to fade this channel.
if(g_iColorFadeTarget[client][c] < 0)
continue;
// We need to fade up in that direction
if(g_fColor[client][c] < g_iColorFadeTarget[client][c])
{
g_fColor[client][c] += g_fColorFadeStep[client][c];
if(g_fColor[client][c] > 255)
g_fColor[client][c] = 255.0;
iColor[c] = RoundToFloor(g_fColor[client][c]);
bFade = true;
// Did we finish fading to that color?
if(g_fColor[client][c] >= g_iColorFadeTarget[client][c])
g_iColorFadeTarget[client][c] = -1;
}
// or fade down
else if(g_fColor[client][c] > g_iColorFadeTarget[client][c])
{
g_fColor[client][c] -= g_fColorFadeStep[client][c];
if(g_fColor[client][c] < 0)
g_fColor[client][c] = 0.0;
iColor[c] = RoundToFloor(g_fColor[client][c]);
bFade = true;
// Did we finish fading to that color?
if(g_fColor[client][c] <= g_iColorFadeTarget[client][c])
g_iColorFadeTarget[client][c] = -1;
}
// no need to fade anymore.
else
{
g_iColorFadeTarget[client][c] = -1;
iColor[c] = RoundToFloor(g_fColor[client][c]);
bFade = true;
}
}
if(bFade)
{
SetEntityRenderMode(client, RENDER_TRANSCOLOR);
Entity_SetRenderColor(client, iColor[0], iColor[1], iColor[2], iColor[3]);
}
}
}
/**
* Native handlers
*/
// native void SMRPG_SetClientDefaultColor(int client, int r=-1, int g=-1, int b=-1, int a=-1);
public int Native_SetClientDefaultColor(Handle plugin, int numParams)
{
int client = GetNativeCell(1);
if(client <= 0 || client > MaxClients)
return ThrowNativeError(SP_ERROR_NATIVE, "Invalid client index %d", client);
int iColor[4];
for(int i=0;i<4;i++)
{
iColor[i] = GetNativeCell(i+2);
if(iColor[i] >= 0)
{
// colors are bytes..
if(iColor[i] > 255)
iColor[i] = 255;
g_iDefaultColor[client][i] = iColor[i];
}
}
return 0;
}
// native void SMRPG_SetClientRenderColor(intclient, int r=-1, int g=-1, int b=-1, int a=-1);
public int Native_SetClientRenderColor(Handle plugin, int numParams)
{
int client = GetNativeCell(1);
if(client <= 0 || client > MaxClients)
return ThrowNativeError(SP_ERROR_NATIVE, "Invalid client index %d", client);
Help_SetClientRenderColor(plugin, client, GetNativeCell(2), GetNativeCell(3), GetNativeCell(4), GetNativeCell(5));
return 0;
}
stock void Help_SetClientRenderColor(Handle hPlugin, int client, int r=-1, int g=-1, int b=-1, int a=-1)
{
int iColor[4];
iColor[0] = r;
iColor[1] = g;
iColor[2] = b;
iColor[3] = a;
for(int i=0;i<4;i++)
{
// Entity_SetRenderColor checks explicitly for -1
if(iColor[i] < 0)
iColor[i] = -1;
// Only set the color, if we want to change it.
if(iColor[i] >= 0)
{
// colors are bytes..
if(iColor[i] > 255)
iColor[i] = 255;
g_fColor[client][i] = float(iColor[i]);
g_hLastAccessedPlugin[client][i] = hPlugin;
}
}
// Actually change the color.
SetEntityRenderMode(client, RENDER_TRANSCOLOR);
Entity_SetRenderColor(client, iColor[0], iColor[1], iColor[2], iColor[3]);
}
// native void SMRPG_SetClientRenderColorFadeTarget(int client, int r=-1, int g=-1, int b=-1, int a=-1);
public int Native_SetClientRenderColorFadeTarget(Handle plugin, int numParams)
{
int client = GetNativeCell(1);
if(client <= 0 || client > MaxClients)
return ThrowNativeError(SP_ERROR_NATIVE, "Invalid client index %d", client);
Help_SetClientRenderColorFadeTarget(plugin, client, GetNativeCell(2), GetNativeCell(3), GetNativeCell(4), GetNativeCell(5));
return 0;
}
stock void Help_SetClientRenderColorFadeTarget(Handle hPlugin, int client, int r=-1, int g=-1, int b=-1, int a=-1)
{
int iColor[4];
iColor[0] = r;
iColor[1] = g;
iColor[2] = b;
iColor[3] = a;
for(int i=0;i<4;i++)
{
if(iColor[i] < 0)
iColor[i] = -1;
// Start to fade to that color
if(iColor[i] >= 0)
{
// colors are bytes..
if(iColor[i] > 255)
iColor[i] = 255;
g_iColorFadeTarget[client][i] = iColor[i];
g_hLastAccessedPlugin[client][i] = hPlugin;
}
}
}
// native void SMRPG_SetClientRenderColorFadeStepsize(int client, int r=-1, int g=-1, int b=-1, int a=-1);
public int Native_SetClientRenderColorFadeStepsize(Handle plugin, int numParams)
{
int client = GetNativeCell(1);
if(client <= 0 || client > MaxClients)
return ThrowNativeError(SP_ERROR_NATIVE, "Invalid client index %d", client);
float fStepsize[4];
for(int i=0;i<4;i++)
{
fStepsize[i] = view_as<float>(GetNativeCell(i+2));
if(fStepsize[i] <= 0.0)
continue;
g_fColorFadeStep[client][i] = fStepsize[i];
}
return 0;
}
// native void SMRPG_ResetClientToDefaultColor(int client, bool bResetRed, bool bResetGreen, bool bResetBlue, bool bResetAlpha, bool bForceReset=false);
public int Native_ResetClientToDefaultColor(Handle plugin, int numParams)
{
int client = GetNativeCell(1);
if(client <= 0 || client > MaxClients)
return ThrowNativeError(SP_ERROR_NATIVE, "Invalid client index %d", client);
Help_ResetClientToDefaultColor(plugin, client, GetNativeCell(2), GetNativeCell(3), GetNativeCell(4), GetNativeCell(5), GetNativeCell(6));
return 0;
}
stock void Help_ResetClientToDefaultColor(Handle hPlugin, int client, bool bResetRed, bool bResetGreen, bool bResetBlue, bool bResetAlpha, bool bForceReset=false)
{
bool bResetChannel[4];
bResetChannel[0] = bResetRed;
bResetChannel[1] = bResetGreen;
bResetChannel[2] = bResetBlue;
bResetChannel[3] = bResetAlpha;
int iColor[4];
for(int i=0;i<4;i++)
{
// Ignore it by default.
iColor[i] = -1;
// Don't touch this channel?
if(!bResetChannel[i])
continue;
// That channel was last set by this plugin. That's fine. Reset it.
if(bForceReset || !g_hLastAccessedPlugin[client][i] || g_hLastAccessedPlugin[client][i] == hPlugin || !IsValidPlugin(g_hLastAccessedPlugin[client][i]))
{
iColor[i] = g_iDefaultColor[client][i];
g_fColor[client][i] = float(g_iDefaultColor[client][i]);
g_hLastAccessedPlugin[client][i] = null;
}
}
// Actually change the color.
SetEntityRenderMode(client, RENDER_TRANSCOLOR);
Entity_SetRenderColor(client, iColor[0], iColor[1], iColor[2], iColor[3]);
} | 412 | 0.839625 | 1 | 0.839625 | game-dev | MEDIA | 0.382142 | game-dev,desktop-app | 0.896315 | 1 | 0.896315 |
EphemeralSpace/ephemeral-space | 1,912 | Content.Client/Atmos/Monitor/AtmosAlarmableVisualsSystem.cs | using Content.Shared.Atmos.Monitor;
using Content.Shared.Power;
using Robust.Client.GameObjects;
using Robust.Client.Graphics;
namespace Content.Client.Atmos.Monitor;
public sealed class AtmosAlarmableVisualsSystem : VisualizerSystem<AtmosAlarmableVisualsComponent>
{
protected override void OnAppearanceChange(EntityUid uid, AtmosAlarmableVisualsComponent component, ref AppearanceChangeEvent args)
{
if (args.Sprite == null || !SpriteSystem.LayerMapTryGet((uid, args.Sprite), component.LayerMap, out var layer, false))
return;
if (!args.AppearanceData.TryGetValue(PowerDeviceVisuals.Powered, out var poweredObject) ||
poweredObject is not bool powered)
{
return;
}
if (component.HideOnDepowered != null)
{
foreach (var visLayer in component.HideOnDepowered)
{
if (SpriteSystem.LayerMapTryGet((uid, args.Sprite), visLayer, out var powerVisibilityLayer, false))
SpriteSystem.LayerSetVisible((uid, args.Sprite), powerVisibilityLayer, powered);
}
}
if (component.SetOnDepowered != null && !powered)
{
foreach (var (setLayer, powerState) in component.SetOnDepowered)
{
if (SpriteSystem.LayerMapTryGet((uid, args.Sprite), setLayer, out var setStateLayer, false))
SpriteSystem.LayerSetRsiState((uid, args.Sprite), setStateLayer, new RSI.StateId(powerState));
}
}
if (args.AppearanceData.TryGetValue(AtmosMonitorVisuals.AlarmType, out var alarmTypeObject)
&& alarmTypeObject is AtmosAlarmType alarmType
&& powered
&& component.AlarmStates.TryGetValue(alarmType, out var state))
{
SpriteSystem.LayerSetRsiState((uid, args.Sprite), layer, new RSI.StateId(state));
}
}
}
| 412 | 0.824323 | 1 | 0.824323 | game-dev | MEDIA | 0.954461 | game-dev | 0.891231 | 1 | 0.891231 |
sm64js/sm64js | 55,208 | src/game/Interaction.js | import * as _Linker from "./Linker"
import * as _Area from "./Area"
import { ACT_IDLE, ACT_PANTING, ACT_STANDING_AGAINST_WALL, ACT_CROUCHING, ACT_DISAPPEARED,
ACT_DIVE, ACT_DIVE_SLIDE,
ACT_FLAG_AIR, ACT_FLAG_ATTACKING, ACT_FLAG_DIVING, ACT_FLAG_HANGING,
ACT_FLAG_IDLE, ACT_FLAG_INTANGIBLE, ACT_FLAG_INVULNERABLE, ACT_FLAG_METAL_WATER,
ACT_FLAG_ON_POLE, ACT_FLAG_RIDING_SHELL, ACT_FLAG_SWIMMING,
ACT_FLYING, ACT_GETTING_BLOWN,
ACT_GRAB_POLE_FAST, ACT_GRAB_POLE_SLOW,
ACT_GROUND_POUND, ACT_GROUND_POUND_LAND, ACT_GROUP_CUTSCENE, ACT_GROUP_MASK,
ACT_ID_MASK, ACT_IN_CANNON, ACT_JUMP_KICK, ACT_MOVE_PUNCHING,
ACT_PICKING_UP, ACT_PICKING_UP_BOWSER, ACT_PUNCHING, ACT_READING_SIGN,
ACT_RIDING_HOOT, ACT_SHOT_FROM_CANNON, ACT_SLIDE_KICK, ACT_SLIDE_KICK_SLIDE,
ACT_TWIRL_LAND, ACT_TWIRLING, ACT_WALKING, ACT_WATER_JUMP, ACT_WATER_PUNCH,
ACT_DECELERATING, ACT_READING_AUTOMATIC_DIALOG,
ACT_TELEPORT_FADE_IN, ACT_TELEPORT_FADE_OUT, ACT_EMERGE_FROM_PIPE,
ACT_UNLOCKING_KEY_DOOR, ACT_PULLING_DOOR, ACT_PUSHING_DOOR,
ACT_ENTERING_STAR_DOOR, ACT_UNLOCKING_STAR_DOOR,
ACT_STAR_DANCE_EXIT, ACT_STAR_DANCE_NO_EXIT, ACT_STAR_DANCE_WATER,
ACT_FALL_AFTER_STAR_GRAB, ACT_JUMBO_STAR_CUTSCENE,
INPUT_A_PRESSED, INPUT_B_PRESSED, INPUT_INTERACT_OBJ_GRABBABLE,
MARIO_KICKING, MARIO_PUNCHING, MARIO_TRIPPING, MARIO_UNKNOWN_08,
MARIO_METAL_CAP, MARIO_VANISH_CAP, MARIO_WING_CAP, MARIO_CAP_ON_HEAD,
MARIO_CAP_IN_HAND, ACT_PUTTING_ON_CAP,
drop_and_set_mario_action, resolve_and_return_wall_collisions, sBackwardKnockbackActions,
mario_set_forward_vel, set_mario_action, sForwardKnockbackActions,
ACT_SHOCKED, ACT_WATER_SHOCKED, ACT_LAVA_BOOST, ACT_BURNING_JUMP, ACT_BURNING_FALL,
MARIO_UNKNOWN_18,
update_mario_sound_and_camera,
ACT_BACKWARD_AIR_KB,
ACT_SOFT_BACKWARD_GROUND_KB,
ACT_FORWARD_AIR_KB,
ACT_SOFT_FORWARD_GROUND_KB,
MARIO_NORMAL_CAP,
ACT_WAITING_FOR_DIALOG,
ACT_GRABBED
} from "./Mario"
import { WARP_OP_WARP_OBJECT, WARP_OP_WARP_FLOOR } from "./LevelUpdate"
import { SOUND_MARIO_EEUH, SOUND_MARIO_WAAAOOOW, SOUND_OBJ_BULLY_METAL,
SOUND_MENU_STAR_SOUND, SOUND_MARIO_OOOF, SOUND_MARIO_ON_FIRE,
SOUND_MARIO_ATTACKED, SOUND_GENERAL_FLAME_OUT
} from "../include/sounds"
import {
DIALOG_022, DIALOG_023, DIALOG_024, DIALOG_025, DIALOG_026, DIALOG_027, DIALOG_028, DIALOG_029
} from "../text/us/dialogs"
import * as MarioConstants from "../include/mario_constants"
import { oInteractType, oInteractStatus, oMarioPoleUnk108, oMarioPoleYawVel, oMarioPolePos,
oInteractionSubtype, oDamageOrCoinValue, oPosX, oPosY, oPosZ, oMoveAngleYaw,
oBehParams, oForwardVel, oMarioBurnTimer, STAR_INDEX_100_COINS
} from "../include/object_constants"
import { atan2s, sqrtf } from "../engine/math_util"
import { sins, coss, int16, s16 } from "../utils"
// import { bhv } from "./BehaviorData"
// import { MODEL_NONE } from "../include/model_ids"
import { SURFACE_DEATH_PLANE, SURFACE_VERTICAL_WIND, SURFACE_BURNING } from "../include/surface_terrains"
import { level_trigger_warp } from "./LevelUpdate"
import { COURSE_IS_MAIN_COURSE } from "../levels/course_defines"
import { CameraInstance as Camera } from "./Camera"
import * as CAMERA from "./Camera" // for constants
import { obj_set_held_state, spawn_object } from "./ObjectHelpers"
import { stop_shell_music } from "./SoundInit"
import { play_sound } from "../audio/external"
import { save_file_get_flags, SAVE_FLAG_UNLOCKED_UPSTAIRS_DOOR,
SAVE_FLAG_UNLOCKED_BASEMENT_DOOR, SAVE_FLAG_HAVE_KEY_1, SAVE_FLAG_HAVE_KEY_2,
SAVE_FLAG_UNLOCKED_50_STAR_DOOR,
SAVE_FLAG_UNLOCKED_BITDW_DOOR,
SAVE_FLAG_UNLOCKED_BITFS_DOOR,
SAVE_FLAG_UNLOCKED_CCM_DOOR,
SAVE_FLAG_UNLOCKED_JRB_DOOR,
SAVE_FLAG_UNLOCKED_PSS_DOOR,
SAVE_FLAG_UNLOCKED_WF_DOOR,
save_file_clear_flags,
SAVE_FLAG_CAP_ON_KLEPTO,
SAVE_FLAG_CAP_ON_UKIKI,
save_file_collect_star_or_key,
save_file_get_total_star_count,
} from "./SaveFile"
import { MODEL_NONE } from "../include/model_ids"
import { AreaInstance as Area } from "./Area"
import { COURSE_MAX, COURSE_MIN } from "../include/course_table"
export const INTERACT_HOOT /* 0x00000001 */ = (1 << 0)
export const INTERACT_GRABBABLE /* 0x00000002 */ = (1 << 1)
export const INTERACT_DOOR /* 0x00000004 */ = (1 << 2)
export const INTERACT_DAMAGE /* 0x00000008 */ = (1 << 3)
export const INTERACT_COIN /* 0x00000010 */ = (1 << 4)
export const INTERACT_CAP /* 0x00000020 */ = (1 << 5)
export const INTERACT_POLE /* 0x00000040 */ = (1 << 6)
export const INTERACT_KOOPA /* 0x00000080 */ = (1 << 7)
export const INTERACT_UNKNOWN_08 /* 0x00000100 */ = (1 << 8)
export const INTERACT_BREAKABLE /* 0x00000200 */ = (1 << 9)
export const INTERACT_STRONG_WIND /* 0x00000400 */ = (1 << 10)
export const INTERACT_WARP_DOOR /* 0x00000800 */ = (1 << 11)
export const INTERACT_STAR_OR_KEY /* 0x00001000 */ = (1 << 12)
export const INTERACT_WARP /* 0x00002000 */ = (1 << 13)
export const INTERACT_CANNON_BASE /* 0x00004000 */ = (1 << 14)
export const INTERACT_BOUNCE_TOP /* 0x00008000 */ = (1 << 15)
export const INTERACT_WATER_RING /* 0x00010000 */ = (1 << 16)
export const INTERACT_BULLY /* 0x00020000 */ = (1 << 17)
export const INTERACT_FLAME /* 0x00040000 */ = (1 << 18)
export const INTERACT_KOOPA_SHELL /* 0x00080000 */ = (1 << 19)
export const INTERACT_BOUNCE_TOP2 /* 0x00100000 */ = (1 << 20)
export const INTERACT_MR_BLIZZARD /* 0x00200000 */ = (1 << 21)
export const INTERACT_HIT_FROM_BELOW /* 0x00400000 */ = (1 << 22)
export const INTERACT_TEXT /* 0x00800000 */ = (1 << 23)
export const INTERACT_TORNADO /* 0x01000000 */ = (1 << 24)
export const INTERACT_WHIRLPOOL /* 0x02000000 */ = (1 << 25)
export const INTERACT_CLAM_OR_BUBBA /* 0x04000000 */ = (1 << 26)
export const INTERACT_BBH_ENTRANCE /* 0x08000000 */ = (1 << 27)
export const INTERACT_SNUFIT_BULLET /* 0x10000000 */ = (1 << 28)
export const INTERACT_SHOCK /* 0x20000000 */ = (1 << 29)
export const INTERACT_IGLOO_BARRIER /* 0x40000000 */ = (1 << 30)
export const INTERACT_UNKNOWN_31 /* 0x80000000 */ = (1 << 31)
// INTERACT_WARP
export const INT_SUBTYPE_FADING_WARP = 0x00000001
// Damaging interactions
export const INT_SUBTYPE_DELAY_INVINCIBILITY = 0x00000002
export const INT_SUBTYPE_BIG_KNOCKBACK = 0x00000008 /* Used by Bowser, sets Mario's forward velocity to 40 on hit */
// INTERACT_GRABBABLE
export const INT_SUBTYPE_GRABS_MARIO = 0x00000004 /* Also makes the object heavy */
export const INT_SUBTYPE_HOLDABLE_NPC = 0x00000010 /* Allows the object to be gently dropped, and sets vertical speed to 0 when dropped with no forwards velocity */
export const INT_SUBTYPE_DROP_IMMEDIATELY = 0x00000040 /* This gets set by grabbable NPCs that talk to Mario to make him drop them after the dialog is finished */
export const INT_SUBTYPE_KICKABLE = 0x00000100
export const INT_SUBTYPE_NOT_GRABBABLE = 0x00000200 /* Used by Heavy-Ho to allow it to throw Mario, without Mario being able to pick it up */
// INTERACT_DOOR
export const INT_SUBTYPE_STAR_DOOR = 0x00000020
//INTERACT_BOUNCE_TOP
export const INT_SUBTYPE_TWIRL_BOUNCE = 0x00000080
// INTERACT_STAR_OR_KEY
export const INT_SUBTYPE_NO_EXIT = 0x00000400
export const INT_SUBTYPE_GRAND_STAR = 0x00000800
// INTERACT_TEXT
export const INT_SUBTYPE_SIGN = 0x00001000
export const INT_SUBTYPE_NPC = 0x00004000
// INTERACT_CLAM_OR_BUBBA
export const INT_SUBTYPE_EATS_MARIO = 0x00002000
export const INT_GROUND_POUND_OR_TWIRL = (1 << 0) // 0x01
export const INT_PUNCH = (1 << 1) // 0x02
export const INT_KICK = (1 << 2) // 0x04
export const INT_TRIP = (1 << 3) // 0x08
export const INT_SLIDE_KICK = (1 << 4) // 0x10
export const INT_FAST_ATTACK_OR_SHELL = (1 << 5) // 0x20
export const INT_HIT_FROM_ABOVE = (1 << 6) // 0x40
export const INT_HIT_FROM_BELOW = (1 << 7) // 0x80
export const INT_ATTACK_NOT_FROM_BELOW =
(INT_GROUND_POUND_OR_TWIRL | INT_PUNCH | INT_KICK | INT_TRIP | INT_SLIDE_KICK
| INT_FAST_ATTACK_OR_SHELL | INT_HIT_FROM_ABOVE)
export const INT_ANY_ATTACK =
(INT_GROUND_POUND_OR_TWIRL | INT_PUNCH | INT_KICK | INT_TRIP | INT_SLIDE_KICK
| INT_FAST_ATTACK_OR_SHELL | INT_HIT_FROM_ABOVE | INT_HIT_FROM_BELOW)
export const INT_ATTACK_NOT_WEAK_FROM_ABOVE =
(INT_GROUND_POUND_OR_TWIRL | INT_PUNCH | INT_KICK | INT_TRIP | INT_HIT_FROM_BELOW)
export const INT_STATUS_ATTACK_MASK = 0x000000FF
export const INT_STATUS_HOOT_GRABBED_BY_MARIO = (1 << 0) /* 0x00000001 */
export const INT_STATUS_MARIO_UNK1 = (1 << 1) /* 0x00000002 */
export const INT_STATUS_MARIO_UNK2 = (1 << 2) /* 0x00000004 */
export const INT_STATUS_MARIO_DROP_OBJECT = (1 << 3) /* 0x00000008 */
export const INT_STATUS_MARIO_UNK4 = (1 << 4) /* 0x00000010 */
export const INT_STATUS_MARIO_UNK5 = (1 << 5) /* 0x00000020 */
export const INT_STATUS_MARIO_UNK6 = (1 << 6) /* 0x00000040 */
export const INT_STATUS_MARIO_UNK7 = (1 << 7) /* 0x00000080 */
export const INT_STATUS_GRABBED_MARIO = (1 << 11) /* 0x00000800 */
export const INT_STATUS_ATTACKED_MARIO = (1 << 13) /* 0x00002000 */
export const INT_STATUS_WAS_ATTACKED = (1 << 14) /* 0x00004000 */
export const INT_STATUS_INTERACTED = (1 << 15) /* 0x00008000 */
export const INT_STATUS_TRAP_TURN = (1 << 20) /* 0x00100000 */
export const INT_STATUS_HIT_MINE = (1 << 21) /* 0x00200000 */
export const INT_STATUS_STOP_RIDING = (1 << 22) /* 0x00400000 */
export const INT_STATUS_TOUCHED_BOB_OMB = (1 << 23) /* 0x00800000 */
export const ATTACK_PUNCH = 1
export const ATTACK_KICK_OR_TRIP = 2
export const ATTACK_FROM_ABOVE = 3
export const ATTACK_GROUND_POUND_OR_TWIRL = 4
export const ATTACK_FAST_ATTACK = 5
export const ATTACK_FROM_BELOW = 6
let sDelayInvincTimer = 0
let sInvulnerable = 0
let sJustTeleported = 0
let sDisplayingDoorText = 0
const check_death_barrier = (m) => {
if (m.pos[1] < m.floorHeight + 2048) {
if (level_trigger_warp(m, WARP_OP_WARP_FLOOR) == 20 && !(m.flags & MARIO_UNKNOWN_18)) {
play_sound(SOUND_MARIO_WAAAOOOW, m.marioObj.gfx.cameraToObject)
}
}
}
const check_lava_boost = (m) => {
if (!(m.action & ACT_FLAG_RIDING_SHELL) && m.pos[1] < m.floorHeight + 10.0) {
if (!(m.flags & MARIO_METAL_CAP)) {
m.hurtCounter += (m.flags & MARIO_CAP_ON_HEAD) ? 12 : 18
}
update_mario_sound_and_camera(m)
drop_and_set_mario_action(m, ACT_LAVA_BOOST, 0)
}
}
export const mario_handle_special_floors = (m) => {
if ((m.action & ACT_GROUP_MASK) == ACT_GROUP_CUTSCENE) {
return
}
if (m.floor != null) {
const floorType = m.floor.type
switch (floorType) {
case SURFACE_DEATH_PLANE:
case SURFACE_VERTICAL_WIND:
check_death_barrier(m)
break
}
if (!(m.action & ACT_FLAG_AIR) && !(m.action & ACT_FLAG_SWIMMING)) {
switch (floorType) {
case SURFACE_BURNING:
check_lava_boost(m)
break
}
}
}
}
const reset_mario_pitch = (m) => {
if (m.action == ACT_WATER_JUMP || m.action == ACT_SHOT_FROM_CANNON || m.action == ACT_FLYING) {
Camera.set_camera_mode(m.area.camera, m.area.camera.defMode, 1)
m.faceAngle[0] = 0
}
}
const interact_coin = (m, o) => {
m.numCoins += o.rawData[oDamageOrCoinValue]
m.healCounter += 4 * o.rawData[oDamageOrCoinValue]
o.rawData[oInteractStatus] = INT_STATUS_INTERACTED
if (COURSE_IS_MAIN_COURSE(gLinker.Area.gCurrCourseNum) && m.numCoins - o.rawData[oDamageOrCoinValue] < 100 && m.numCoins >= 100) {
gLinker.bhv_spawn_star_no_level_exit(STAR_INDEX_100_COINS)
}
return false
}
const interact_star_or_key = (m, /*interactType,*/ o) => {
let /*u32*/ starIndex
let /*u32*/ starGrabAction = ACT_STAR_DANCE_EXIT
let /*u32*/ noExit = (o.rawData[oInteractionSubtype] & INT_SUBTYPE_NO_EXIT) != 0
let /*u32*/ grandStar = (o.rawData[oInteractionSubtype] & INT_SUBTYPE_GRAND_STAR) != 0
if (m.health >= 0x100) {
mario_stop_riding_and_holding(m)
// #if ENABLE_RUMBLE
// queue_rumble_data(5, 80);
// #endif
if (!noExit) {
m.hurtCounter = 0
m.healCounter = 0
if (m.capTimer > 1) {
m.capTimer = 1
}
}
if (noExit) {
starGrabAction = ACT_STAR_DANCE_NO_EXIT
}
if (m.action & ACT_FLAG_SWIMMING) {
starGrabAction = ACT_STAR_DANCE_WATER
}
if (m.action & ACT_FLAG_METAL_WATER) {
starGrabAction = ACT_STAR_DANCE_WATER
}
if (m.action & ACT_FLAG_AIR) {
starGrabAction = ACT_FALL_AFTER_STAR_GRAB
}
spawn_object(o, MODEL_NONE, gLinker.behaviors.bhvStarKeyCollectionPuffSpawner);
o.oInteractStatus = INT_STATUS_INTERACTED
m.interactObj = o
m.usedObj = o
starIndex = (o.rawData[oBehParams] >> 24) & 0x1F;
save_file_collect_star_or_key(m.numCoins, starIndex);
m.numStars =
save_file_get_total_star_count(Area.gCurrSaveFileNum - 1, COURSE_MIN - 1, COURSE_MAX - 1);
// if (!noExit) {
// drop_queued_background_music();
// fadeout_level_music(126);
// }
play_sound(SOUND_MENU_STAR_SOUND, m.marioObj.gfx.cameraToObject)
update_mario_sound_and_camera(m)
if (grandStar) {
return set_mario_action(m, ACT_JUMBO_STAR_CUTSCENE, 0)
}
return set_mario_action(m, starGrabAction, noExit + 2 * grandStar)
}
return false
}
export const interact_warp = (m, o) => {
let action
if (o.rawData[oInteractionSubtype] & INT_SUBTYPE_FADING_WARP) {
action = m.action
if (action == ACT_TELEPORT_FADE_IN) {
sJustTeleported = true;
} else if (!sJustTeleported) {
if (action == ACT_IDLE || action == ACT_PANTING || action == ACT_STANDING_AGAINST_WALL
|| action == ACT_CROUCHING) {
m.interactObj = o
m.usedObj = o
sJustTeleported = true;
return set_mario_action(m, ACT_TELEPORT_FADE_OUT, 0)
}
}
} else {
if (m.action != ACT_EMERGE_FROM_PIPE) {
o.rawData[oInteractStatus] = INT_STATUS_INTERACTED
m.interactObj = o
m.usedObj = o
// play_sound(o.collisionData == warp_pipe_seg3_collision_03009AC8
// ? SOUND_MENU_ENTER_PIPE
// : SOUND_MENU_ENTER_HOLE,
// m.marioObj.gfx.cameraToObject)
mario_stop_riding_object(m)
return set_mario_action(m, ACT_DISAPPEARED, (WARP_OP_WARP_OBJECT << 16) + 2)
}
}
return false
}
export const interact_warp_door = (m, o) => {
let doorAction = 0
let saveFlags = save_file_get_flags(
SAVE_FLAG_UNLOCKED_UPSTAIRS_DOOR | SAVE_FLAG_HAVE_KEY_1 | SAVE_FLAG_HAVE_KEY_2 |
SAVE_FLAG_UNLOCKED_BASEMENT_DOOR
) // DEBUG add SAVE_FLAGs here
let warpDoorId = o.rawData[oBehParams] >> 24
let actionArg
if (m.action == ACT_WALKING || m.action == ACT_DECELERATING) {
if (warpDoorId == 1 && !(saveFlags & SAVE_FLAG_UNLOCKED_UPSTAIRS_DOOR)) {
if (!(saveFlags & SAVE_FLAG_HAVE_KEY_2)) {
if (!sDisplayingDoorText) {
set_mario_action(m, ACT_READING_AUTOMATIC_DIALOG,
(saveFlags & SAVE_FLAG_HAVE_KEY_1) ? DIALOG_023 : DIALOG_022)
}
sDisplayingDoorText = 1
return false
}
doorAction = ACT_UNLOCKING_KEY_DOOR
}
if (warpDoorId == 2 && !(saveFlags & SAVE_FLAG_UNLOCKED_BASEMENT_DOOR)) {
if (!(saveFlags & SAVE_FLAG_HAVE_KEY_1)) {
if (!sDisplayingDoorText) {
// Moat door skip was intended confirmed
set_mario_action(m, ACT_READING_AUTOMATIC_DIALOG,
(saveFlags & SAVE_FLAG_HAVE_KEY_2) ? DIALOG_023 : DIALOG_022)
}
sDisplayingDoorText = 1
return false
}
doorAction = ACT_UNLOCKING_KEY_DOOR
}
if (m.action == ACT_WALKING || m.action == ACT_DECELERATING) {
actionArg = should_push_or_pull_door(m, o) + 0x00000004
if (doorAction == 0) {
if (actionArg & 0x00000001) {
doorAction = ACT_PULLING_DOOR
} else {
doorAction = ACT_PUSHING_DOOR
}
}
m.interactObj = o
m.usedObj = o
return set_mario_action(m, doorAction, actionArg)
}
}
return false
}
export const get_door_save_file_flag = (door) => {
let saveFileFlag = 0
let requiredNumStars = door.rawData[oBehParams] >> 24
let isCcmDoor = door.rawData[oPosX] < 0.0
let isPssDoor = door.rawData[oPosY] > 500.0
switch (requiredNumStars) {
case 1:
if (isPssDoor) {
saveFileFlag = SAVE_FLAG_UNLOCKED_PSS_DOOR
} else {
saveFileFlag = SAVE_FLAG_UNLOCKED_WF_DOOR
}
break
case 3:
if (isCcmDoor) {
saveFileFlag = SAVE_FLAG_UNLOCKED_CCM_DOOR
} else {
saveFileFlag = SAVE_FLAG_UNLOCKED_JRB_DOOR
}
break
case 8:
saveFileFlag = SAVE_FLAG_UNLOCKED_BITDW_DOOR
break
case 30:
saveFileFlag = SAVE_FLAG_UNLOCKED_BITFS_DOOR
break
case 50:
saveFileFlag = SAVE_FLAG_UNLOCKED_50_STAR_DOOR
break
}
return saveFileFlag
}
export const interact_door = (m, o) => {
let /*s16*/ requiredNumStars = o.rawData[oBehParams] >> 24
let /*s16*/ numStars = save_file_get_total_star_count(Area.gCurrSaveFileNum - 1, COURSE_MIN - 1, COURSE_MAX - 1)
if (m.action == ACT_WALKING || m.action == ACT_DECELERATING) {
if (numStars >= requiredNumStars) {
let /*u32*/ actionArg = should_push_or_pull_door(m, o)
let /*u32*/ enterDoorAction
let /*u32*/ doorSaveFileFlag
if (actionArg & 0x00000001) {
enterDoorAction = ACT_PULLING_DOOR
} else {
enterDoorAction = ACT_PUSHING_DOOR
}
doorSaveFileFlag = get_door_save_file_flag(o)
m.interactObj = o
m.usedObj = o
if (o.rawData[oInteractionSubtype] & INT_SUBTYPE_STAR_DOOR) {
enterDoorAction = ACT_ENTERING_STAR_DOOR
}
if (doorSaveFileFlag != 0 && !(save_file_get_flags() & doorSaveFileFlag)) {
enterDoorAction = ACT_UNLOCKING_STAR_DOOR
}
return set_mario_action(m, enterDoorAction, actionArg)
} else if (!sDisplayingDoorText) {
let /*u32*/ text = DIALOG_022.str
switch (requiredNumStars) {
case 1:
text = DIALOG_024.str
break
case 3:
text = DIALOG_025.str
break
case 8:
text = DIALOG_026.str
break
case 30:
text = DIALOG_027.str
break
case 50:
text = DIALOG_028.str
break
case 70:
text = DIALOG_029.str
break
}
text += requiredNumStars - numStars
sDisplayingDoorText = 1
return set_mario_action(m, ACT_READING_AUTOMATIC_DIALOG, text)
}
} else if (m.action == ACT_IDLE && sDisplayingDoorText == 1 && requiredNumStars == 70) {
m.interactObj = o
m.usedObj = o
return set_mario_action(m, ACT_ENTERING_STAR_DOOR, should_push_or_pull_door(m, o))
}
return false
}
const interact_cannon_base = (m, o) => {
if (m.action != ACT_IN_CANNON) {
mario_stop_riding_and_holding(m)
o.rawData[oInteractStatus] = INT_STATUS_INTERACTED
m.interactObj = o
m.usedObj = o
return set_mario_action(m, ACT_IN_CANNON, 0)
}
return false
}
const interact_bounce_top = (m, o) => {
let interaction
if (m.flags & MARIO_METAL_CAP) {
interaction = INT_FAST_ATTACK_OR_SHELL
} else {
interaction = determine_interaction(m, o)
}
if (interaction & INT_ATTACK_NOT_FROM_BELOW) {
attack_object(o, interaction)
bounce_back_from_attack(m, interaction)
if (interaction & INT_HIT_FROM_ABOVE) {
if (o.rawData[oInteractionSubtype] & INT_SUBTYPE_TWIRL_BOUNCE) {
throw "need to implement twirl bounce"
} else {
bounce_off_object(m, o, 30.0)
}
}
} else if (take_damage_and_knock_back(m, o)) {
return true
}
if (!(o.rawData[oInteractionSubtype] & INT_SUBTYPE_DELAY_INVINCIBILITY)) {
sDelayInvincTimer = 1
}
return false
}
const interact_damage = (m, o) => {
if (take_damage_and_knock_back(m, o)) return true
if (!(o.rawData[oInteractionSubtype] & INT_SUBTYPE_DELAY_INVINCIBILITY)) {
sDelayInvincTimer = 1
}
return false
}
const interact_breakable = (m, o) => {
const interaction = determine_interaction(m, o)
if (interaction & INT_ATTACK_NOT_WEAK_FROM_ABOVE) {
attack_object(o, interaction)
bounce_back_from_attack(m, interaction)
m.interactObj = o
switch (interaction) {
case INT_HIT_FROM_ABOVE:
bounce_off_object(m, o, 30.0) //! Not in the 0x8F mask
break
case INT_HIT_FROM_BELOW:
hit_object_from_below(m, o)
break
}
return true
}
return false
}
const interact_mr_blizzard = (m, o) => {
if (take_damage_and_knock_back(m, o)) {
return true
}
if (!(o.rawData[oInteractionSubtype] & INT_SUBTYPE_DELAY_INVINCIBILITY)) {
sDelayInvincTimer = 1
}
return false
}
const interact_hit_from_below = (m, o) => {
let interaction
if (m.flags & MARIO_METAL_CAP) {
interaction = INT_FAST_ATTACK_OR_SHELL
} else {
interaction = determine_interaction(m, o)
}
if (interaction & INT_ANY_ATTACK) {
// queue_rumble_data(5, 80)
attack_object(o, interaction)
bounce_back_from_attack(m, interaction)
if (interaction & INT_HIT_FROM_BELOW) {
hit_object_from_below(m, o)
}
if (interaction & INT_HIT_FROM_ABOVE) {
if (o.rawData[oInteractionSubtype] & INT_SUBTYPE_TWIRL_BOUNCE) {
bounce_off_object(m, o, 80.0)
reset_mario_pitch(m)
// play_sound(SOUND_MARIO_TWIRL_BOUNCE, m.marioObj.gfx.cameraToObject)
return drop_and_set_mario_action(m, ACT_TWIRLING, 0)
} else {
bounce_off_object(m, o, 30.0)
}
}
} else if (take_damage_and_knock_back(m, o)) {
return true
}
if (!(o.rawData[oInteractionSubtype] & INT_SUBTYPE_DELAY_INVINCIBILITY)) {
sDelayInvincTimer = true
}
return false
}
export const interact_cap = (m, o) => {
let /*u32*/capFlag = get_mario_cap_flag(o)
let /*u16*/capMusic = 0
let /*u16*/capTime = 0
if (m.action != ACT_GETTING_BLOWN && capFlag != 0) {
m.interactObj = o
o.rawData[oInteractStatus] = INT_STATUS_INTERACTED
m.flags &= ~MARIO_CAP_ON_HEAD & ~MARIO_CAP_IN_HAND
m.flags |= capFlag
switch (capFlag) {
case MARIO_VANISH_CAP:
capTime = 600
// capMusic = SEQUENCE_ARGS(4, SEQ_EVENT_POWERUP)
break
case MARIO_METAL_CAP:
capTime = 600
// capMusic = SEQUENCE_ARGS(4, SEQ_EVENT_METAL_CAP)
break
case MARIO_WING_CAP:
capTime = 1800
// capMusic = SEQUENCE_ARGS(4, SEQ_EVENT_POWERUP)
break
}
if (capTime > m.capTimer) {
m.capTimer = capTime
}
if ((m.action & ACT_FLAG_IDLE) || m.action == ACT_WALKING) {
m.flags |= MARIO_CAP_IN_HAND
set_mario_action(m, ACT_PUTTING_ON_CAP, 0)
} else {
m.flags |= MARIO_CAP_ON_HEAD
}
// play_sound(SOUND_MENU_STAR_SOUND, m.marioObj.gfx.cameraToObject)
// play_sound(SOUND_MARIO_HERE_WE_GO, m.marioObj.gfx.cameraToObject)
if (capMusic != 0) {
play_cap_music(capMusic)
}
return true
}
return false
}
const interact_grabbable = (m, o) => {
const script = o.behavior
if (o.rawData[oInteractionSubtype] & INT_SUBTYPE_KICKABLE) {
const interaction = determine_interaction(m, o)
if (interaction & (INT_KICK | INT_TRIP)) {
attack_object(o, interaction)
bounce_back_from_attack(m, interaction)
return false
}
}
if (o.rawData[oInteractionSubtype] & INT_SUBTYPE_GRABS_MARIO) {
if (check_object_grab_mario(m, o)) {
return true
}
}
if (able_to_grab_object(m, o)) {
if (!(o.rawData[oInteractionSubtype] & INT_SUBTYPE_NOT_GRABBABLE)) {
m.interactObj = o
m.input |= INPUT_INTERACT_OBJ_GRABBABLE
return true
}
}
if (script != gLinker.behaviors.bhvBowser) {
push_mario_out_of_object(m, o, -5.0)
}
return false
}
const mario_can_talk = (m, arg) => {
let val6
if ((m.action & ACT_FLAG_IDLE) != 0x00000000) {
return true
}
if (m.action == ACT_WALKING) {
if (arg) {
return true
}
val6 = m.marioObj.gfx.animInfo.animID
if (val6 == 0x0080 || val6 == 0x007F || val6 == 0x006C) {
return true
}
}
return false
}
const check_read_sign = (m, o) => {
if ((m.input & (INPUT_B_PRESSED | INPUT_A_PRESSED)) && mario_can_talk(m, 0) && object_facing_mario(m, o, 0x4000)) {
const facingDYaw = s16(s16(o.rawData[oMoveAngleYaw] + 0x8000) - m.faceAngle[1])
if (facingDYaw >= -0x4000 && facingDYaw <= 0x4000) {
const targetX = o.rawData[oPosX] + 105.0 * sins(o.rawData[oMoveAngleYaw])
const targetZ = o.rawData[oPosZ] + 105.0 * coss(o.rawData[oMoveAngleYaw])
m.marioObj.oMarioReadingSignDYaw = facingDYaw;
m.marioObj.oMarioReadingSignDPosX = targetX - m.pos[0]
m.marioObj.oMarioReadingSignDPosZ = targetZ - m.pos[2]
m.interactObj = o
m.usedObj = o
return set_mario_action(m, ACT_READING_SIGN, 0)
}
}
return false
}
const check_npc_talk = (m, o) => {
if ((m.input & (INPUT_B_PRESSED | INPUT_A_PRESSED)) && mario_can_talk(m, 1)) {
const facingDYaw = s16(mario_obj_angle_to_object(m, o) - m.faceAngle[1])
if (facingDYaw >= -0x4000 && facingDYaw <= 0x4000) {
o.rawData[oInteractStatus] = INT_STATUS_INTERACTED
m.interactObj = o
m.usedObj = o
push_mario_out_of_object(m, o, -10.0)
return set_mario_action(m, ACT_WAITING_FOR_DIALOG, 0)
}
}
push_mario_out_of_object(m, o, -10.0)
return false
}
const interact_text = (m, o) => {
let interact = 0
if (o.rawData[oInteractionSubtype] & INT_SUBTYPE_SIGN) {
interact = check_read_sign(m, o)
} else if (o.rawData[oInteractionSubtype] & INT_SUBTYPE_NPC) {
interact = check_npc_talk(m, o)
} else {
push_mario_out_of_object(m, o, 2.0)
}
return interact
}
const check_object_grab_mario = (m, o) => { // commented out because game broke aaa
if ((!(m.action & (ACT_FLAG_AIR | ACT_FLAG_INVULNERABLE | ACT_FLAG_ATTACKING)) || !sInvulnerable) && (o.rawData[oInteractionSubtype] & INT_SUBTYPE_GRABS_MARIO)) {
if (object_facing_mario(m, o, 0x2AAA)) {
mario_stop_riding_and_holding(m)
o.rawData[oInteractStatus] = INT_STATUS_INTERACTED | INT_STATUS_GRABBED_MARIO
m.faceAngle[1] = o.rawData[oMoveAngleYaw]
m.interactObj = o
m.usedObj = o
update_mario_sound_and_camera(m)
play_sound(SOUND_MARIO_OOOF, m.marioObj.gfx.cameraToObject)
return set_mario_action(m, ACT_GRABBED, 0)
}
}
}
const interact_pole = (m, o) => {
const actionId = m.action & ACT_ID_MASK
if (actionId >= 0x80 && actionId < 0x0A0) {
if (!(m.prevAction & ACT_FLAG_ON_POLE) || m.usedObj != o) {
const lowSpeed = m.forwardVel <= 10.0
const marioObj = m.marioObj
m.interactObj = o
m.usedObj = o
m.vel[1] = 0.0
m.forwardVel = 0.0
marioObj.rawData[oMarioPoleUnk108] = 0
marioObj.rawData[oMarioPoleYawVel] = 0
marioObj.rawData[oMarioPolePos] = m.pos[1] - o.rawData[oPosY]
if (lowSpeed) {
return set_mario_action(m, ACT_GRAB_POLE_SLOW, 0)
}
marioObj.rawData[oMarioPoleYawVel] = parseInt((m.forwardVel * 0x100) + 0x1000)
reset_mario_pitch(m)
return set_mario_action(m, ACT_GRAB_POLE_FAST, 0)
}
}
return false
}
const interact_flame = (m, o) => {
let burningAction = ACT_BURNING_JUMP
if (!sInvulnerable && !(m.flags & MARIO_METAL_CAP) && !(m.flags & MARIO_VANISH_CAP)
&& !(o.rawData[oInteractionSubtype] & INT_SUBTYPE_DELAY_INVINCIBILITY)) {
//queue_rumble_data(5, 80)
o.rawData[oInteractStatus] = INT_STATUS_INTERACTED
m.interactObj = o
if ((m.action & (ACT_FLAG_SWIMMING | ACT_FLAG_METAL_WATER))
|| m.waterLevel - m.pos[1] > 50.0) {
play_sound(SOUND_GENERAL_FLAME_OUT, m.marioObj.gfx.cameraToObject);
} else {
m.marioObj.rawData[oMarioBurnTimer] = 0
update_mario_sound_and_camera(m)
play_sound(SOUND_MARIO_ON_FIRE, m.marioObj.gfx.cameraToObject);
if ((m.action & ACT_FLAG_AIR) && m.vel[1] <= 0.0) {
burningAction = ACT_BURNING_FALL
}
return drop_and_set_mario_action(m, burningAction, 1)
}
}
return false
}
const init_bully_collision_data = (data, posX, posZ, forwardVel, yaw, conversionRatio, radius) => {
if (forwardVel < 0.0) {
forwardVel *= -1.0
yaw += 0x8000
}
data.radius = radius
data.conversionRatio = conversionRatio
data.posX = posX
data.posZ = posZ
data.velX = forwardVel * sins(yaw)
data.velZ = forwardVel * coss(yaw)
}
const transfer_bully_speed = (obj, obj2) => {
let rx = obj2.posX - obj.posX
let rz = obj2.posX - obj.posZ
//! Bully NaN crash
let projectedV1 = (rx * obj.velX + rz * obj.velZ) / (rx * rx + rz * rz)
let projectedV2 = (-rx * obj.velX - rz * obj.velZ) / (rx * rx + rz * rz)
// Kill speed along r. Convert one object's speed along r and transfer it to
// the other object.
obj2.velX += obj2.conversionRatio * projectedV1 * rx - projectedV2 * -rx
obj2.velZ += obj2.conversionRatio * projectedV1 * rz - projectedV2 * -rz
obj.velX += -projectedV1 * rx + obj.conversionRatio * projectedV2 * -rx
obj.velZ += -projectedV1 * rz + obj.conversionRatio * projectedV2 * -rz
//! Bully battery
}
const bully_knock_back_mario = (mario) => {
let marioData = {}
let bullyData = {}
let newMarioYaw
let newBullyYaw
let bonkAction = 0
let bully = mario.interactObj
//! Conversion ratios multiply to more than 1 (could allow unbounded speed
// with bonk cancel - but this isn't important for regular bully battery)
let bullyToMarioRatio = bully.hitboxRadius * 3 / 53
let marioToBullyRatio = 53.0 / bully.hitboxRadius
init_bully_collision_data(marioData, mario.pos[0], mario.pos[2], mario.forwardVel, mario.faceAngle[1], bullyToMarioRatio, 52.0)
init_bully_collision_data(bullyData, bully.rawData[oPosX], bully.rawData[oPosZ], bully.rawData[oForwardVel], bully.rawData[oMoveAngleYaw], bullyToMarioRatio, bully.hitboxRadius + 2.0)
if (mario.forwardVel != 0.0) {
transfer_bully_speed(marioData, bullyData)
} else {
transfer_bully_speed(bullyData, marioData)
}
newMarioYaw = atan2s(marioData.velZ, marioData.velX)
newBullyYaw = atan2s(bullyData.velZ, bullyData.velX)
let marioDYaw = newMarioYaw - mario.faceAngle[1]
let bullyDYaw = newBullyYaw - bully.rawData[oMoveAngleYaw]
mario.faceAngle[1] = newMarioYaw
mario.forwardVel = sqrtf(marioData.velX * marioData.velX + marioData.velZ * marioData.velZ)
mario.pos[0] = marioData.posX
mario.pos[2] = marioData.posZ
if (marioDYaw < -0x4000 || marioDYaw > 0x4000) {
mario.faceAngle[1] += 0x8000
mario.forwardVel *= -1.0
if (mario.action & ACT_FLAG_AIR) {
bonkAction = ACT_BACKWARD_AIR_KB
} else {
bonkAction = ACT_SOFT_BACKWARD_GROUND_KB
}
} else {
if (mario.action & ACT_FLAG_AIR) {
bonkAction = ACT_FORWARD_AIR_KB
} else {
bonkAction = ACT_SOFT_FORWARD_GROUND_KB
}
}
return bonkAction
}
const interact_bully = (m, o) => {
let interaction
if (m.flags & MARIO_METAL_CAP) {
interaction = INT_FAST_ATTACK_OR_SHELL
} else {
interaction = determine_interaction(m, o)
}
m.interactObj = o
if (interaction & INT_ATTACK_NOT_FROM_BELOW) {
push_mario_out_of_object(m, o, 5.0)
m.forwardVel = -16.0
o.rawData[oMoveAngleYaw] = m.faceAngle[1]
o.rawData[oForwardVel] = 3392.0 / o.hitboxRadius
attack_object(o, interaction)
bounce_back_from_attack(m, interaction)
return true
} else if (!sInvulnerable && !(m.flags & MARIO_VANISH_CAP) && !(o.rawData[oInteractionSubtype] & INT_SUBTYPE_DELAY_INVINCIBILITY)) {
o.rawData[oInteractStatus] = INT_STATUS_INTERACTED
m.invincTimer = 2
update_mario_sound_and_camera(m)
play_sound(SOUND_MARIO_EEUH, m.marioObj.gfx.cameraToObject)
play_sound(SOUND_OBJ_BULLY_METAL, m.marioObj.gfx.cameraToObject)
push_mario_out_of_object(m, o, 5.0)
drop_and_set_mario_action(m, bully_knock_back_mario(m), 0)
// queue_rumble_data(5, 80)
// for if you guys figure out rumble pak :)
return true
}
return false
}
const interact_shock = (m, o) => {
if (!sInvulnerable && !(m.flags & MARIO_VANISH_CAP)
&& !(o.rawData[oInteractionSubtype] & INT_SUBTYPE_DELAY_INVINCIBILITY)) {
const actionArg = (m.action & (ACT_FLAG_AIR | ACT_FLAG_ON_POLE | ACT_FLAG_HANGING)) == 0
o.rawData[oInteractStatus] = INT_STATUS_INTERACTED | INT_STATUS_ATTACKED_MARIO
m.interactObj = o
take_damage_from_interact_object(m)
play_sound(SOUND_MARIO_ATTACKED, m.marioObj.gfx.cameraToObject)
//queue_rumble_data(70, 60)
if (m.action & (ACT_FLAG_SWIMMING | ACT_FLAG_METAL_WATER)) {
return drop_and_set_mario_action(m, ACT_WATER_SHOCKED, 0)
} else {
update_mario_sound_and_camera(m)
return drop_and_set_mario_action(m, ACT_SHOCKED, actionArg)
}
}
if (!(o.rawData[oInteractionSubtype] & INT_SUBTYPE_DELAY_INVINCIBILITY)) {
sDelayInvincTimer = true
}
return false
}
const able_to_grab_object = (m, o) => {
const action = m.action
if (action == ACT_DIVE_SLIDE || action == ACT_DIVE) {
if (!(o.rawData[oInteractionSubtype] & INT_SUBTYPE_GRABS_MARIO)) {
return true
}
} else if (action == ACT_PUNCHING || action == ACT_MOVE_PUNCHING) {
if (m.actionArg < 2) {
return true
}
}
return false
}
export const mario_obj_angle_to_object = (m, o) => {
const dx = o.rawData[oPosX] - m.pos[0]
const dz = o.rawData[oPosZ] - m.pos[2]
return atan2s(dz, dx)
}
const push_mario_out_of_object = (m, o, padding) => {
const minDistance = o.hitboxRadius + m.marioObj.hitboxRadius + padding
const offsetX = m.pos[0] - o.rawData[oPosX]
const offsetZ = m.pos[2] - o.rawData[oPosZ]
const distance = Math.sqrt(offsetX * offsetX + offsetZ * offsetZ)
if (distance < minDistance) {
let pushAngle
if (distance == 0.0) {
pushAngle = m.faceAngle[1]
} else {
pushAngle = atan2s(offsetZ, offsetX)
}
const newMarioX = { value: o.rawData[oPosX] + minDistance * sins(pushAngle) }
const newMarioZ = { value: o.rawData[oPosZ] + minDistance * coss(pushAngle) }
const newMarioY = { value: m.pos[1] }
gLinker.SurfaceCollision.find_wall_collision(newMarioX, newMarioY, newMarioZ, 60.0, 50.0)
m.pos[1] = newMarioY.value
const floorWrapper = {}
gLinker.SurfaceCollision.find_floor(newMarioX.value, m.pos[1], newMarioZ.value, floorWrapper)
if (floorWrapper.floor != null) {
//! Doesn't update mario's referenced floor (allows oob death when
// an object pushes you into a steep slope while in a ground action)
m.pos[0] = newMarioX.value
m.pos[2] = newMarioZ.value
}
}
}
const attack_object = (o, interaction) => {
let attackType = 0
switch (interaction) {
case INT_GROUND_POUND_OR_TWIRL:
attackType = ATTACK_GROUND_POUND_OR_TWIRL
break
case INT_PUNCH:
attackType = ATTACK_PUNCH
break
case INT_KICK:
case INT_TRIP:
attackType = ATTACK_KICK_OR_TRIP
break
case INT_SLIDE_KICK:
case INT_FAST_ATTACK_OR_SHELL:
attackType = ATTACK_FAST_ATTACK
break
case INT_HIT_FROM_ABOVE:
attackType = ATTACK_FROM_ABOVE
break
case INT_HIT_FROM_BELOW:
attackType = ATTACK_FROM_BELOW
break
}
o.rawData[oInteractStatus] = attackType + (INT_STATUS_INTERACTED | INT_STATUS_WAS_ATTACKED)
return attackType
}
export const mario_stop_riding_object = (m) => {
if (m.riddenObj) {
m.riddenObj.rawData[oInteractStatus] = INT_STATUS_STOP_RIDING
stop_shell_music()
m.riddenObj = null
}
}
export const mario_grab_used_object = (m) => {
if (!m.heldObj) {
m.heldObj = m.usedObj
obj_set_held_state(m.heldObj, gLinker.behaviors.bhvCarrySomething3)
}
}
export const mario_drop_held_object = (m) => {
if (m.heldObj != null) {
if (m.heldObj.behavior == gLinker.behaviors.bhvKoopaShellUnderwater) {
stop_shell_music()
}
obj_set_held_state(m.heldObj, gLinker.behaviors.bhvCarrySomething4)
// ! When dropping an object instead of throwing it, it will be put at Mario's
// y-positon instead of the HOLP's y-position. This fact is often exploited when
// cloning objects.
m.heldObj.rawData[oPosX] = m.marioBodyState.heldObjLastPosition[0]
m.heldObj.rawData[oPosY] = m.pos[1]
m.heldObj.rawData[oPosZ] = m.marioBodyState.heldObjLastPosition[2]
m.heldObj.rawData[oMoveAngleYaw] = m.faceAngle[1]
m.heldObj = null
}
}
export const mario_throw_held_object = (m) => {
if (m.heldObj != null) {
if (m.heldObj.behavior == gLinker.behaviors.bhvKoopaShellUnderwater) {
stop_shell_music()
}
obj_set_held_state(m.heldObj, gLinker.behaviors.bhvCarrySomething5)
m.heldObj.rawData[oPosX] = m.marioBodyState.heldObjLastPosition[0] + 32.0 * sins(m.faceAngle[1])
m.heldObj.rawData[oPosY] = m.marioBodyState.heldObjLastPosition[1]
m.heldObj.rawData[oPosZ] = m.marioBodyState.heldObjLastPosition[2] + 32.0 * coss(m.faceAngle[1])
m.heldObj.rawData[oMoveAngleYaw] = m.faceAngle[1]
m.heldObj = null
}
}
export const mario_stop_riding_and_holding = (m) => {
mario_drop_held_object(m)
mario_stop_riding_object(m)
if (m.action == ACT_RIDING_HOOT) {
m.usedObj.rawData[oInteractStatus] = 0
m.usedObj.rawData[oHootMarioReleaseTime] = window.gGlobalTimer
}
}
export const mario_retrieve_cap = () => {
const gMarioState = gLinker.LevelUpdate.gMarioState
mario_drop_held_object(gMarioState)
save_file_clear_flags(SAVE_FLAG_CAP_ON_KLEPTO | SAVE_FLAG_CAP_ON_UKIKI)
gMarioState.flags &= ~MARIO_CAP_ON_HEAD
gMarioState.flags |= MARIO_NORMAL_CAP | MARIO_CAP_IN_HAND
}
////////////////////////////////////////////////////
const bounce_off_object = (m, o, velY) => {
m.pos[1] = o.rawData[oPosY] + o.hitboxHeight
m.vel[1] = velY
m.flags &= ~MARIO_UNKNOWN_08
//play_sound(SOUND_ACTION_BOUNCE_OFF_OBJECT, m . marioObj . .gfx.cameraToObject)
}
const hit_object_from_below = (m, o) => {
m.vel[1] = 0.0
Camera.set_camera_shake_from_hit(CAMERA.SHAKE_HIT_FROM_BELOW)
}
const bounce_back_from_attack = (m, interaction) => {
if (interaction & (INT_PUNCH | INT_KICK | INT_TRIP)) {
if (m.action == ACT_PUNCHING) {
m.action = ACT_MOVE_PUNCHING
}
if (m.action & ACT_FLAG_AIR) {
mario_set_forward_vel(m, -16.0)
} else {
mario_set_forward_vel(m, -48.0)
}
Camera.set_camera_shake_from_hit(CAMERA.SHAKE_ATTACK)
m.particleFlags |= MarioConstants.PARTICLE_TRIANGLE
}
if (interaction & (INT_PUNCH | INT_KICK | INT_TRIP | INT_FAST_ATTACK_OR_SHELL)) {
//play_sound(SOUND_ACTION_HIT_2, m . marioObj . .gfx.cameraToObject)
}
}
const should_push_or_pull_door = (m, o) => {
let dx = o.rawData[oPosX] - m.pos[0]
let dz = o.rawData[oPosZ] - m.pos[2]
let dYaw = s16(o.rawData[oMoveAngleYaw] - atan2s(dz, dx))
return (dYaw >= -0x4000 && dYaw <= 0x4000) ? 0x00000001 : 0x00000002
}
/**
* Returns the type of cap Mario is wearing.
*/
export const get_mario_cap_flag = (capObject) => {
const script = capObject.behavior
if (script == gLinker.behaviors.bhvNormalCap) {
return MARIO_NORMAL_CAP
} else if (script == gLinker.behaviors.bhvMetalCap) {
return MARIO_METAL_CAP
} else if (script == gLinker.behaviors.bhvWingCap) {
return MARIO_WING_CAP
} else if (script == gLinker.behaviors.bhvVanishCap) {
return MARIO_VANISH_CAP
}
return false
}
/**
* Returns true if the passed in object has a moving angle yaw
* in the angular range given towards Mario.
*/
const object_facing_mario = (m, o, angleRange) => {
let dx = m.pos[0] - o.rawData[oPosX]
let dz = m.pos[2] - o.rawData[oPosZ]
let angleToMario = atan2s(dz, dx)
let dAngle = s16(angleToMario - o.rawData[oMoveAngleYaw])
if (-angleRange <= dAngle && dAngle <= angleRange) {
return true
}
return false
}
const determine_interaction = (m, o) => {
let interaction = 0
const action = m.action
let dYawToObject = mario_obj_angle_to_object(m, o) - m.faceAngle[1]
dYawToObject = dYawToObject > 32767 ? dYawToObject - 65536 : dYawToObject
dYawToObject = dYawToObject < -32768 ? dYawToObject + 65536 : dYawToObject
// hack: make water punch actually do something
if (m.action == ACT_WATER_PUNCH && o.rawData[oInteractType] & INTERACT_PLAYER) {
if (-0x2AAA <= dYawToObject && dYawToObject <= 0x2AAA) {
return INT_PUNCH
}
}
if (action & ACT_FLAG_ATTACKING) {
if (action == ACT_PUNCHING || action == ACT_MOVE_PUNCHING || action == ACT_JUMP_KICK) {
if (m.flags & MARIO_PUNCHING) {
// 120 degrees total, or 60 each way
if (-0x2AAA <= dYawToObject && dYawToObject <= 0x2AAA) {
interaction = INT_PUNCH
}
}
if (m.flags & MARIO_KICKING) {
// 120 degrees total, or 60 each way
if (-0x2AAA <= dYawToObject && dYawToObject <= 0x2AAA) {
interaction = INT_KICK
}
}
if (m.flags & MARIO_TRIPPING) {
// 180 degrees total, or 90 each way
if (true) {
interaction = INT_TRIP
}
}
} else if (action == ACT_GROUND_POUND || action == ACT_TWIRLING) {
if (m.vel[1] < 0.0) {
interaction = INT_GROUND_POUND_OR_TWIRL
}
} else if (action == ACT_GROUND_POUND_LAND || action == ACT_TWIRL_LAND) {
// Neither ground pounding nor twirling change Mario's vertical speed on landing.,
// so the speed check is nearly always true (perhaps not if you land while going upwards?)
// Additionally, actionState it set on each first thing in their action, so this is
// only true prior to the very first frame (i.e. active 1 frame prior to it run).
if (m.vel[1] < 0.0 && m.actionState == 0) {
interaction = INT_GROUND_POUND_OR_TWIRL
}
} else if (action == ACT_SLIDE_KICK || action == ACT_SLIDE_KICK_SLIDE) {
interaction = INT_SLIDE_KICK
} else if (action & ACT_FLAG_RIDING_SHELL) {
interaction = INT_FAST_ATTACK_OR_SHELL
} else if (m.forwardVel <= -26.0 || 26.0 <= m.forwardVel) {
interaction = INT_FAST_ATTACK_OR_SHELL
}
}
// Prior to this, the interaction type could be overwritten. This requires, however,
// that the interaction not be set prior. This specifically overrides turning a ground
// pound into just a bounce.
if (interaction == 0 && (action & ACT_FLAG_AIR)) {
if (m.vel[1] < 0.0) {
if (m.pos[1] > o.rawData[oPosY]) {
interaction = INT_HIT_FROM_ABOVE
}
} else {
if (m.pos[1] < o.rawData[oPosY]) {
interaction = INT_HIT_FROM_BELOW
}
}
}
return interaction
}
const determine_knockback_action = (m) => {
const angleToObject = mario_obj_angle_to_object(m, m.interactObj)
let facingDYaw = int16( angleToObject - m.faceAngle[1] )
const remainingHealth = m.health - 0x40 * m.hurtCounter
let terrainIndex = 0, strengthIndex = 0
if (m.action & (ACT_FLAG_SWIMMING | ACT_FLAG_METAL_WATER)) {
terrainIndex = 2
} else if (m.action & (ACT_FLAG_AIR | ACT_FLAG_ON_POLE | ACT_FLAG_HANGING)) {
terrainIndex = 1
}
if (remainingHealth < 0x100) {
strengthIndex = 2
} else if (m.interactObj.rawData[oDamageOrCoinValue] >= 4) {
strengthIndex = 2
} else if (m.interactObj.rawData[oDamageOrCoinValue] >= 2) {
strengthIndex = 1
}
m.faceAngle[1] = angleToObject
if (terrainIndex == 2) {
if (m.forwardVel < 28) mario_set_forward_vel(m, 28)
if (m.pos[1] >= m.interactObj.rawData[oPosY]) {
if (m.vel[1] < 20.0) m.vel[1] = 20.0
} else {
if (m.vel[1] > 0.0) m.vel[1] = 0.0
}
} else {
if (m.forwardVel < 16) mario_set_forward_vel(m, 16)
}
let bonkAction
if (-0x4000 <= facingDYaw && facingDYaw <= 0x4000) {
m.forwardVel *= -1.0
bonkAction = sBackwardKnockbackActions[terrainIndex][strengthIndex]
} else {
m.faceAngle[1] += 0x8000
bonkAction = sForwardKnockbackActions[terrainIndex][strengthIndex]
}
return bonkAction
}
const take_damage_from_interact_object = (m) => {
const damage = m.interactObj.rawData[oDamageOrCoinValue]
let shake
if (damage >= 4) {
shake = CAMERA.SHAKE_LARGE_DAMAGE
} else if (damage >= 2) {
shake = CAMERA.SHAKE_MED_DAMAGE
} else {
shake = CAMERA.SHAKE_SMALL_DAMAGE
}
if (!(m.flags & MARIO_CAP_ON_HEAD)) {
damage += (damage + 1) / 2
}
if (m.flags & MARIO_METAL_CAP) {
damage = 0
}
m.hurtCounter += 4 * damage
Camera.set_camera_shake_from_hit(shake)
return damage
}
export const take_damage_and_knock_back = (m, o) => {
if (!sInvulnerable && !(m.flags & MARIO_VANISH_CAP)
&& !(o.rawData[oInteractionSubtype] & INT_SUBTYPE_DELAY_INVINCIBILITY)) {
o.rawData[oInteractStatus] = INT_STATUS_INTERACTED | INT_STATUS_ATTACKED_MARIO
m.interactObj = o
const damage = take_damage_from_interact_object(m)
if (o.rawData[oInteractionSubtype] & INT_SUBTYPE_BIG_KNOCKBACK) m.forwardVel = 40.0
if (o.rawData[oDamageOrCoinValue] > 0); //play sound
//update mario sound and camera
return drop_and_set_mario_action(m, determine_knockback_action(m, o.rawData[oDamageOrCoinValue]), damage)
}
return false
}
const check_kick_or_punch_wall = (m) => {
if (m.flags & (MARIO_PUNCHING | MARIO_KICKING | MARIO_TRIPPING)) {
const detector = [0,0,0];
detector[0] = m.pos[0] + 50.0 * sins(m.faceAngle[1]);
detector[2] = m.pos[2] + 50.0 * coss(m.faceAngle[1]);
detector[1] = m.pos[1];
if (resolve_and_return_wall_collisions(detector, 80.0, 5.0) != null) {
if (m.action != ACT_MOVE_PUNCHING || m.forwardVel >= 0.0) {
if (m.action == ACT_PUNCHING) {
m.action = ACT_MOVE_PUNCHING;
}
mario_set_forward_vel(m, -48.0);
// play_sound(SOUND_ACTION_HIT_2, m.marioObj..gfx.cameraToObject);
m.particleFlags |= MarioConstants.PARTICLE_TRIANGLE;
} else if (m.action & ACT_FLAG_AIR) {
mario_set_forward_vel(m, -16.0);
// play_sound(SOUND_ACTION_HIT_2, m.marioObj..gfx.cameraToObject);
m.particleFlags |= MarioConstants.PARTICLE_TRIANGLE;
}
}
}
}
const sInteractionHandlers = [
{ interactType: INTERACT_COIN, handler: interact_coin },
{ interactType: INTERACT_WATER_RING, handler: null },
{ interactType: INTERACT_STAR_OR_KEY, handler: interact_star_or_key },
{ interactType: INTERACT_BBH_ENTRANCE, handler: null },
{ interactType: INTERACT_WARP, handler: interact_warp },
{ interactType: INTERACT_WARP_DOOR, handler: interact_warp_door },
{ interactType: INTERACT_DOOR, handler: interact_door },
{ interactType: INTERACT_CANNON_BASE, handler: interact_cannon_base },
{ interactType: INTERACT_IGLOO_BARRIER, handler: null },
{ interactType: INTERACT_TORNADO, handler: null },
{ interactType: INTERACT_WHIRLPOOL, handler: null },
{ interactType: INTERACT_STRONG_WIND, handler: null },
{ interactType: INTERACT_FLAME, handler: interact_flame },
{ interactType: INTERACT_SNUFIT_BULLET, handler: null },
{ interactType: INTERACT_CLAM_OR_BUBBA, handler: null },
{ interactType: INTERACT_BULLY, handler: interact_bully },
{ interactType: INTERACT_SHOCK, handler: interact_shock },
{ interactType: INTERACT_BOUNCE_TOP2, handler: null },
{ interactType: INTERACT_MR_BLIZZARD, handler: interact_mr_blizzard },
{ interactType: INTERACT_HIT_FROM_BELOW, handler: interact_hit_from_below },
{ interactType: INTERACT_BOUNCE_TOP, handler: interact_bounce_top },
{ interactType: INTERACT_DAMAGE, handler: interact_damage },
{ interactType: INTERACT_POLE, handler: interact_pole },
{ interactType: INTERACT_HOOT, handler: null },
{ interactType: INTERACT_BREAKABLE, handler: interact_breakable },
{ interactType: INTERACT_KOOPA, handler: null },
{ interactType: INTERACT_KOOPA_SHELL, handler: null },
{ interactType: INTERACT_UNKNOWN_08, handler: null },
{ interactType: INTERACT_CAP, handler: interact_cap },
{ interactType: INTERACT_GRABBABLE, handler: interact_grabbable },
{ interactType: INTERACT_TEXT, handler: interact_text },
]
const mario_get_collided_object = (m, interactType) => {
for (let i = 0; i < m.marioObj.collidedObjs.length; i++) {
const object = m.marioObj.collidedObjs[i]
if (object.rawData[oInteractType] == interactType) {
return object
}
}
}
export const mario_check_object_grab = (m) => {
let result = 0
let script
if (m.input & INPUT_INTERACT_OBJ_GRABBABLE) {
script = m.interactObj.behavior
if (script == gLinker.behaviors.bhvBowser) {
let facingDYaw = s16(m.faceAngle[1] - m.interactObj.oMoveAngleYaw)
if (facingDYaw >= -0x5555 && facingDYaw <= 0x5555) {
m.faceAngle[1] = m.interactObj.oMoveAngleYaw
m.usedObj = m.interactObj
result = set_mario_action(m, ACT_PICKING_UP_BOWSER, 0)
}
} else {
let facingDYaw = s16(mario_obj_angle_to_object(m, m.interactObj) - m.faceAngle[1])
if (facingDYaw >= -0x2AAA && facingDYaw <= 0x2AAA) {
m.usedObj = m.interactObj
if (!(m.action & ACT_FLAG_AIR)) {
set_mario_action(
m, (m.action & ACT_FLAG_DIVING) ? ACT_DIVE_PICKING_UP : ACT_PICKING_UP, 0);
}
result = 1
}
}
}
return result
}
export const mario_process_interactions = (m) => {
sDelayInvincTimer = 0
sInvulnerable = (m.action & ACT_FLAG_INVULNERABLE) || m.invincTimer != 0
if (!(m.action & ACT_FLAG_INTANGIBLE) && m.collidedObjInteractTypes != 0) {
for (let i = 0; i < sInteractionHandlers.length; i++) {
const { interactType, handler } = sInteractionHandlers[i]
if (m.collidedObjInteractTypes & interactType) {
if (!handler) throw "need to implement interact handler for type: " + interactType + " all types: " + m.collidedObjInteractTypes
const object = mario_get_collided_object(m, interactType)
m.collidedObjInteractTypes &= ~interactType
if (!(object.rawData[oInteractStatus] & INT_STATUS_INTERACTED)) {
if (handler(m, object)) break
}
}
}
}
if (m.invincTimer > 0 && !sDelayInvincTimer) {
m.invincTimer -= 1
}
check_kick_or_punch_wall(m);
m.flags &= ~MARIO_PUNCHING & ~MARIO_KICKING & ~MARIO_TRIPPING
if (!(m.marioObj.collidedObjInteractTypes & (INTERACT_WARP_DOOR | INTERACT_DOOR))) sDisplayingDoorText = false;
if (!(m.marioObj.collidedObjInteractTypes & INTERACT_WARP)) sJustTeleported = false;
}
| 412 | 0.925818 | 1 | 0.925818 | game-dev | MEDIA | 0.919582 | game-dev | 0.540304 | 1 | 0.540304 |
KwaiVideoTeam/las | 1,329 | client/las.js/test/functional/main.js | const assert = require('assert');
import Las from '../../src';
import Manifest from '../mocks/test-manifest.json';
let player;
const v = document.getElementsByTagName('video');
if (v.length) {
player = v[0];
} else {
player = document.createElement('video');
player.setAttribute('controls', 'controls');
player.setAttribute('autoplay', 'autoplay');
player.setAttribute('muted', true);
player.setAttribute('width', '500');
player.setAttribute('height', '300');
document.body.appendChild(player);
}
player.muted = true;
describe('las.js main test', () => {
window.jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000;
let las;
let i = 0;
beforeEach(done => {
las = new Las();
las.attachMedia(player)
las.on('error', e => {
assert.ok(false, `kernel error: ${e.code}`);
});
las.load(Manifest);
setTimeout(() => {
done();
}, 10000);
});
afterEach(done => {
las.destroy();
assert.ok(!player.getAttribute('src'), 'clear video src');
las = null;
setTimeout(() => {
done();
}, 0);
});
it('base', () => {
assert.ok(!player.error, `video error`);
assert.ok(player.currentTime > 0, `video currentTime:${player.currentTime}`)
});
}); | 412 | 0.687986 | 1 | 0.687986 | game-dev | MEDIA | 0.525998 | game-dev,web-frontend | 0.501057 | 1 | 0.501057 |
RVAGameJams/learn2love | 8,495 | pages/02-13-breakout-part-3.md | # Breakout (part 3): inputs
## Review
In the previous section we reconstructed our entities to make room for bricks and additional functionality.
We haven't completed any new items on our checklist:
- The objective of the game is to destroy all the bricks on the screen
- The player controls a "paddle" entity that hits a ball
- The ball destroys the bricks
- **✔** The ball needs to stay within the boundaries of the screen
- If the ball touches the bottom of the screen, the game ends
So let's come up with a system to handle user input and get the paddle moving.
## Input service
Inside **main.lua** there is some functionality for this that we are going to remove and rewrite starting with a new file that specifically handles all the user input.
This kind of file is typically called a service because it abstracts away tedious functionality into an easy-to-use service.
I encourage you to write out the service instead of copying and pasting.
Read through each function and try to understand what each one does.
```lua
-- input.lua
-- This table is the service and will contain some functions
-- that can be accessed from entities or the main.lua.
local input = {}
-- Map specific user inputs to game actions
local press_functions = {}
local release_functions = {}
-- For moving paddle left
input.left = false
-- For moving paddle right
input.right = false
-- Keep track of whether game is pause
input.paused = false
-- Look up in the map for actions that correspond to specific key presses
input.press = function(pressed_key)
if press_functions[pressed_key] then
press_functions[pressed_key]()
end
end
-- Look up in the map for actions that correspond to specific key releases
input.release = function(released_key)
if release_functions[released_key] then
release_functions[released_key]()
end
end
-- Handle window focusing/unfocusing
input.toggle_focus = function(focused)
if not focused then
input.paused = true
end
end
press_functions.left = function()
input.left = true
end
press_functions.right = function()
input.right = true
end
press_functions.escape = function()
love.event.quit()
end
press_functions.space = function()
input.paused = not input.paused
end
release_functions.left = function()
input.left = false
end
release_functions.right = function()
input.right = false
end
return input
```
The input table is what gets returned, meaning when we `require('input')` in another file, we get back that table and its contents.
Inside the input there are three boolean properties that get toggled by user input: `input.left`, `input.right`, and `input.paused`.
Along with these three properties, there are three functions exposed to us to make use of: `input.press`, `input.release`, and `input.toggle_focus`, all of which we will invoke from our callbacks in **main.lua**:
```lua
-- main.lua
local entities = require('entities')
local input = require('input')
local world = require('world')
love.draw = function()
for _, entity in ipairs(entities) do
if entity.draw then entity:draw() end
end
end
love.focus = function(focused)
input.toggle_focus(focused)
end
love.keypressed = function(pressed_key)
input.press(pressed_key)
end
love.keyreleased = function(released_key)
input.release(released_key)
end
love.update = function(dt)
if not input.paused then
for _, entity in ipairs(entities) do
if entity.update then entity:update(dt) end
end
world:update(dt)
end
end
```
In `love.update` we skip updates if `input.paused` is `true`.
However if the game is **not** paused then it will loop through the entity list, calling `entity.update` if the entity has an update function.
With this added functionality, we can append an `entity.update` function into our existing paddle code:
```lua
-- entities/paddle.lua
entity.update = function(self)
-- Don't move if both keys are pressed. Just return
-- instead of going through the rest of the function.
if input.left and input.right then
return
end
local self_x, self_y = self.body:getPosition()
if input.left then
self.body:setPosition(self_x - 10, self_y)
elseif input.right then
self.body:setPosition(self_x + 10, self_y)
end
end
```
The left and right arrows will now move the paddle!
There isn't much else to say here in the way of input.
A bit unrelated to the actual input, but more so the paddle functionality is it moves off screen and doesn't adhere to the boundaries?
Why is that?
If you remember when we created the paddle, it is a static entity.
It doesn't have the ability to move on its own or by the effect of other entities.
This will cause us some problems later (and we're learning the hard way)!
Rather than forcing the paddle with an invisible push, we force a new position for the paddle when we call `body:setPosition` inside the paddle's `entity.update` function.
It's like we're teleporting it on top of whatever space we want with a keystroke, ignoring all physics and collision.
This is simpler to code and gets around the fact the paddle's static body won't respond to force.
To fix this, we can artificially set the boundary on the paddle by checking if it is out of bounds before moving it.
```lua
-- entities/paddle.lua
entity.update = function(self)
-- Don't move if both keys are pressed. Just return
-- instead of going through the rest of the function.
if input.left and input.right then
return
end
local self_x, self_y = self.body:getPosition()
if input.left then
local new_x = math.max(self_x - 10, 108)
self.body:setPosition(new_x, self_y)
elseif input.right then
local new_x = math.min(self_x + 10, 700)
self.body:setPosition(new_x, self_y)
end
end
```
Calling `math.max` means we will set the new x-position to either `self_x - 10` or `100`, whichever number is bigger.
This prevents us from getting a number so small it runs off too far to the left.
`math.min` does the opposite and takes care of the right side of the screen.
One issue you may or may not notice is movement isn't always a uniform speed, and depending on the speed of your computer the paddle may appear to go faster or slower.
Remember the article on [delta time](02-05-delta-time.md)?
We need to scale the distance travelled to match the amount of time that has passed.
Conveniently, we are getting the delta time from `love.update` already.
Take a closer look at it:
```lua
-- main.lua
love.update = function(dt)
if not input.paused then
for _, entity in ipairs(entities) do
-- Delta time is being passed
-- to the entity.update function here
-- |
-- |
-- V
if entity.update then entity:update(dt) end
end
world:update(dt)
end
end
```
Which means we can do this:
```lua
-- entities/paddle.lua
entity.update = function(self, dt)
-- Don't move if both keys are pressed. Just return
-- instead of going through the rest of the function.
if input.left and input.right then
return
end
local self_x, self_y = self.body:getPosition()
if input.left then
local new_x = math.max(self_x - (400 * dt), 100)
self.body:setPosition(new_x, self_y)
elseif input.right then
local new_x = math.min(self_x + (400 * dt), 700)
self.body:setPosition(new_x, self_y)
end
end
```
The number `400` is arbitrary and can be whatever speed you want the paddle to move at.
`dt` is a small number so it needs to be multiplied by a large number like 400 to match a speed similar to what we were seeing before when we simply were adding and subtracting `10`.
If you missed anything or are having issues, here's a copy of the completed source code for this section:
https://github.com/RVAGameJams/learn2love/tree/master/code/breakout-3
In the next section we will work on the physics more to give the ball movement a more realistic feel.
We will also implement the ability to destroy bricks using the world collision callbacks.
## Exercises
- Despite having a restitution of 1, the ball is losing momentum as it collides with other objects. This is due to friction. How can that be fixed?
- When the game is paused, make it display text on the screen so the player knows the game isn't just frozen. Hint: you'll need one of the draw functions from [love.graphics](https://love2d.org/wiki/love.graphics) to print the text.
The answers to these exercises will be in the next section's source code.
| 412 | 0.784944 | 1 | 0.784944 | game-dev | MEDIA | 0.867852 | game-dev | 0.876477 | 1 | 0.876477 |
ProjectEQ/projecteqquests | 3,796 | freeporteast/Lenka_Stoutheart.lua | -- items: 13818, 12146, 13814, 13922, 13923
function event_say(e)
local fac = e.other:GetFaction(e.self);
if(e.message:findi("hail") and (fac <= 5)) then
e.self:Say("Hi, kid! You seem to be a stranger in these parts. Heed my words, this city is dangerous to new blood!");
eq.signal(382254,1); -- NPC: Bronto_Thudfoot
elseif(e.message:findi("hail") and (fac > 5)) then
e.self:Say("Run while ye still can!! The Wolves o' the North will not tolerate yer presence!");
elseif(e.message:findi("toala sent me")) then
e.self:Say("She does not even have the courtesy to come herself. Some old friend!! Listen, some rogue in this city broke into the [Beast] and stole a pouch containing a voucher ticket for a part I need to repair the Beast. I can't get the part back without the ticket. I did not see the rogue. I did not sleep on the Beast that night. Bronto was there. Ask him if he saw the rogue.");
elseif(e.message:findi("what beast")) then
e.self:Say("You're joking, right? You have never heard of the Blue Beast?!! She is the fastest ship in Norrath. She made the [Kunark run] in under three weeks. She was designed by [Bronto].");
elseif(e.message:findi("kunark run")) then
e.self:Say("The Kunark run is the most dangerous run between Freeport and [Firiona Vie], in Kunark. If the seas don't rip your hull to splinters and the pirates and sea wyrms don't kill you, you can make a quick run back and forth, avoiding any unwanted inspections.");
elseif(e.message:findi("Firiona Vie")) then
e.self:Say("Firiona Vie is an elven outpost on the continent of Kunark. Every so often I run supplies to and from there. Do not even think about asking me to take you there. It will be months before I can make improvements on the Blue Beast to make it impervious to aerial attacks.");
elseif(e.message:findi("journal strongbox")) then
e.self:Say("You must be from the Academy of Arcane Science. Well, kid, bad news. I was docked at the isle in the Ocean of Tears when I was boarded by the Freeport Militia. To say the least, I panicked and dropped all my cargo. It is still there. Mostly illegal alcohol, but the strongbox is still out there, too. Directly out from the dock.");
eq.set_global("strongbox","1",7,"H1");
end
end
function event_trade(e)
local item_lib = require("items");
if(item_lib.check_turn_in(e.trade, {item1 = 13818})) then -- Boat Beakon
e.self:Say("Oh!! You must work for that Erudite named Palatos. I guess he won't have to spend anymore money drinking in Freeport. Here. Here is the portrait I kept until he could get me a new boat beacon.");
e.other:SummonItem(12146); -- A'kanon's Portrait
e.other:Ding();
e.other:Faction(320,1,0); -- Faction: Wolves of the North
e.other:Faction(327,1,0); -- Faction: Shamen of Justice
e.other:Faction(265,1,0); -- Faction: Heretics
e.other:Faction(267,1,0); -- Faction: High Guard of Erudin
e.other:AddEXP(100);
elseif(item_lib.check_turn_in(e.trade, {item1 = 13814})) then -- L.S. Pouch
e.self:Say("You found my pouch! Thanks kid. Let me buy you A drink and this is for the good work. Hmmmm. It looks as though they took my voucher. Darn it! Hey... It looks like they were using my bag to hold items they were stealing. Here you go. You can have it. It looks like junk.");
e.other:SummonItem(eq.ChooseRandom(13922,13923)); -- Snapped Pole or Moggok's Right Eye
e.other:Ding();
e.other:Faction(320,2,0); -- Faction: Wolves of the North
e.other:Faction(327,2,0); -- Faction: Shamen of Justice
e.other:Faction(328,2,0); -- Faction: Merchants of Halas
e.other:Faction(311,2,0); -- Faction: Steel Warriors
e.other:Faction(305,-2,0); -- Faction: Rogues of the White Rose
e.other:AddEXP(200);
e.other:GiveCash(0,2,0,0);
end
item_lib.return_items(e.self, e.other, e.trade)
end
| 412 | 0.817513 | 1 | 0.817513 | game-dev | MEDIA | 0.989275 | game-dev | 0.691218 | 1 | 0.691218 |
RaspberryPiFoundation/python-curriculum | 9,230 | hr-HR/lessons/CodeCraft/project-resources/codecraft/codecraft.py | #!/bin/python3
#############
# CodeCraft #
#############
#---
#Game functions
#---
#moves the player left 1 tile.
def moveLeft():
global playerX
if(playerX > 0):
playerX -= 1
drawPlayer()
#moves the player right 1 tile.
def moveRight():
global playerX, MAPWIDTH
if(playerX < MAPWIDTH - 1):
playerX += 1
drawPlayer()
#moves the player up 1 tile.
def moveUp():
global playerY
if(playerY > 0):
playerY -= 1
drawPlayer()
#moves the player down 1 tile.
def moveDown():
global playerY, MAPHEIGHT
if(playerY < MAPHEIGHT - 1):
playerY += 1
drawPlayer()
#picks up the resource at the player's position.
def pickUp():
global playerX, playerY
drawing = True
currentTile = world[playerX][playerY]
#if the user doesn't already have too many...
if inventory[currentTile] < MAXTILES:
#player now has 1 more of this resource
inventory[currentTile] += 1
#the player is now standing on dirt
world[playerX][playerY] = DIRT
#draw the new DIRT tile
drawResource(playerX, playerY)
#redraw the inventory with the extra resource.
drawInventory()
#place a resource at the player's current position
def place(resource):
print('placing: ', names[resource])
#only place if the player has some left...
if inventory[resource] > 0:
#find out the resourcee at the player's current position
currentTile = world[playerX][playerY]
#pick up the resource the player's standing on
#(if it's not DIRT)
if currentTile is not DIRT:
inventory[currentTile] += 1
#place the resource at the player's current position
world[playerX][playerY] = resource
#add the new resource to the inventory
inventory[resource] -= 1
#update the display (world and inventory)
drawResource(playerX, playerY)
drawInventory()
print(' Placing', names[resource], 'complete')
#...and if they have none left...
else:
print(' You have no', names[resource], 'left')
#craft a new resource
def craft(resource):
print('Crafting: ', names[resource])
#if the resource can be crafted...
if resource in crafting:
#keeps track of whether we have the resources
#to craft this item
canBeMade = True
#for each item needed to craft the resource
for i in crafting[resource]:
#...if we don't have enough...
if crafting[resource][i] > inventory[i]:
#...we can't craft it!
canBeMade = False
break
#if we can craft it (we have all needed resources)
if canBeMade == True:
#take each item from the inventory
for i in crafting[resource]:
inventory[i] -= crafting[resource][i]
#add the crafted item to the inventory
inventory[resource] += 1
print(' Crafting', names[resource], 'complete')
#...otherwise the resource can't be crafted...
else:
print(' Can\'t craft', names[resource])
#update the displayed inventory
drawInventory()
#creates a function for placing each resource
def makeplace(resource):
return lambda: place(resource)
#attaches a 'placing' function to each key press
def bindPlacingKeys():
for k in placekeys:
screen.onkey(makeplace(k), placekeys[k])
#creates a function for crafting each resource
def makecraft(resource):
return lambda: craft(resource)
#attaches a 'crafting' function to each key press
def bindCraftingKeys():
for k in craftkeys:
screen.onkey(makecraft(k), craftkeys[k])
#draws a resource at the position (y,x)
def drawResource(y, x):
#this variable stops other stuff being drawn
global drawing
#only draw if nothing else is being drawn
if drawing == False:
#something is now being drawn
drawing = True
#draw the resource at that position in the tilemap, using the correct image
rendererT.goto( (y * TILESIZE) + 20, height - (x * TILESIZE) - 20 )
#draw tile with correct texture
texture = textures[world[y][x]]
rendererT.shape(texture)
rendererT.stamp()
screen.update()
#nothing is now being drawn
drawing = False
#draws the player on the world
def drawPlayer():
playerT.goto( (playerX * TILESIZE) + 20, height - (playerY * TILESIZE) -20 )
#draws the world map
def drawWorld():
#loop through each row
for row in range(MAPHEIGHT):
#loop through each column in the row
for column in range(MAPWIDTH):
#draw the tile at the current position
drawResource(column, row)
#draws the inventory to the screen
def drawInventory():
#this variable stops other stuff being drawn
global drawing
#only draw if nothing else is being drawn
if drawing == False:
#something is now being drawn
drawing = True
#use a rectangle to cover the current inventory
rendererT.color(BACKGROUNDCOLOUR)
rendererT.goto(0,0)
rendererT.begin_fill()
#rendererT.setheading(0)
for i in range(2):
rendererT.forward(inventory_height - 60)
rendererT.right(90)
rendererT.forward(width)
rendererT.right(90)
rendererT.end_fill()
rendererT.color('')
#display the 'place' and 'craft' text
for i in range(1,num_rows+1):
rendererT.goto(20, (height - (MAPHEIGHT * TILESIZE)) - 20 - (i * 100))
rendererT.write("place")
rendererT.goto(20, (height - (MAPHEIGHT * TILESIZE)) - 40 - (i * 100))
rendererT.write("craft")
#set the inventory position
xPosition = 70
yPostition = height - (MAPHEIGHT * TILESIZE) - 80
itemNum = 0
for i, item in enumerate(resources):
#add the image
rendererT.goto(xPosition, yPostition)
rendererT.shape(textures[item])
rendererT.stamp()
#add the number in the inventory
rendererT.goto(xPosition, yPostition - TILESIZE)
rendererT.write(inventory[item])
#add key to place
rendererT.goto(xPosition, yPostition - TILESIZE - 20)
rendererT.write(placekeys[item])
#add key to craft
if crafting.get(item) != None:
rendererT.goto(xPosition, yPostition - TILESIZE - 40)
rendererT.write(craftkeys[item])
#move along to place the next inventory item
xPosition += 50
itemNum += 1
#drop down to the next row every 10 items
if itemNum % INVWIDTH == 0:
xPosition = 70
itemNum = 0
yPostition -= TILESIZE + 80
drawing = False
#generate the instructions, including crafting rules
def generateInstructions():
instructions.append('Crafting rules:')
#for each resource that can be crafted...
for rule in crafting:
#create the crafting rule text
craftrule = names[rule] + ' = '
for resource, number in crafting[rule].items():
craftrule += str(number) + ' ' + names[resource] + ' '
#add the crafting rule to the instructions
instructions.append(craftrule)
#display the instructions
yPos = height - 20
for item in instructions:
rendererT.goto( MAPWIDTH*TILESIZE + 40, yPos)
rendererT.write(item)
yPos-=20
#generate a random world
def generateRandomWorld():
#loop through each row
for row in range(MAPHEIGHT):
#loop through each column in that row
for column in range(MAPWIDTH):
#pick a random number between 0 and 10
randomNumber = random.randint(0,10)
#WATER if the random number is a 1 or a 2
if randomNumber in [1,2]:
tile = WATER
#GRASS if the random number is a 3 or a 4
elif randomNumber in [3,4]:
tile = GRASS
#otherwise it's DIRT
else:
tile = DIRT
#set the position in the tilemap to the randomly chosen tile
world[column][row] = tile
#---
#Code starts running here
#---
#import the modules and variables needed
import turtle
import random
from variables import *
from math import ceil
TILESIZE = 20
#the number of inventory resources per row
INVWIDTH = 8
drawing = False
#create a new 'screen' object
screen = turtle.Screen()
#calculate the width and height
width = (TILESIZE * MAPWIDTH) + max(200,INVWIDTH * 50)
num_rows = int(ceil((len(resources) / INVWIDTH)))
inventory_height = num_rows * 120 + 40
height = (TILESIZE * MAPHEIGHT) + inventory_height
screen.setup(width, height)
screen.setworldcoordinates(0,0,width,height)
screen.bgcolor(BACKGROUNDCOLOUR)
screen.listen()
#register the player image
screen.register_shape(playerImg)
#register each of the resource images
for texture in textures.values():
screen.register_shape(texture)
#create a new player object
playerT = turtle.Turtle()
playerT.hideturtle()
playerT.shape(playerImg)
playerT.penup()
playerT.speed(0)
#create another turtle to do the graphics drawing
rendererT = turtle.Turtle()
rendererT.hideturtle()
rendererT.penup()
rendererT.speed(0)
rendererT.setheading(90)
#create a world of random resources.
world = [ [DIRT for w in range(MAPHEIGHT)] for h in range(MAPWIDTH) ]
#map the keys for moving and picking up to the correct functions.
screen.onkey(moveUp, 'w')
screen.onkey(moveDown, 's')
screen.onkey(moveLeft, 'a')
screen.onkey(moveRight, 'd')
screen.onkey(pickUp, 'space')
#set up the keys for placing and crafting each resource
bindPlacingKeys()
bindCraftingKeys()
#these functions are defined above
generateRandomWorld()
drawWorld()
drawInventory()
generateInstructions()
drawPlayer()
playerT.showturtle()
| 412 | 0.519805 | 1 | 0.519805 | game-dev | MEDIA | 0.908061 | game-dev | 0.645196 | 1 | 0.645196 |
ParadoxGameConverters/paradoxGameConverters | 48,593 | Vic2ToHoI4/Source/HOI4World/HoI4WarCreator.cpp | /*Copyright (c) 2018 The Paradox Game Converters Project
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 "HoI4WarCreator.h"
#include "Events.h"
#include "HoI4Faction.h"
#include "HoI4Focus.h"
#include "HoI4World.h"
#include "MapData.h"
#include "../Mappers/ProvinceDefinitions.h"
#include "../V2World/Party.h"
#include "../V2World/World.h"
#include "Log.h"
HoI4WarCreator::HoI4WarCreator(const HoI4::World* world, const HoI4::MapData& theMapData):
genericFocusTree(new HoI4FocusTree),
theWorld(world),
AggressorFactions(),
WorldTargetMap(),
provincePositions(),
provinceToOwnerMap()
{
ofstream AILog;
if (theConfiguration.getDebug())
{
AILog.open("AI-log.txt");
}
genericFocusTree->addGenericFocusTree(world->getMajorIdeologies());
determineProvinceOwners();
addAllTargetsToWorldTargetMap();
double worldStrength = calculateWorldStrength(AILog);
set<shared_ptr<HoI4Faction>> factionsAtWar;
LOG(LogLevel::Info) << "Generating major wars";
generateMajorWars(AILog, factionsAtWar, world->getMajorIdeologies(), world, theMapData);
LOG(LogLevel::Info) << "Generating additional wars";
generateAdditionalWars(AILog, factionsAtWar, worldStrength, theMapData);
if (theConfiguration.getDebug())
{
AILog.close();
}
}
void HoI4WarCreator::addAllTargetsToWorldTargetMap()
{
for (auto greatPower: theWorld->getGreatPowers())
{
addTargetsToWorldTargetMap(greatPower);
}
}
void HoI4WarCreator::addTargetsToWorldTargetMap(shared_ptr<HoI4Country> country)
{
if (country->getGovernmentIdeology() != "democratic")
{
int maxGCWars = 0;
for (auto GC: getDistancesToGreatPowers(country))
{
if (maxGCWars < 2)
{
string HowToTakeGC = HowToTakeLand(GC.second, country, 3);
if (HowToTakeGC == "noactionneeded" || HowToTakeGC == "factionneeded" || HowToTakeGC == "morealliesneeded")
{
if (GC.second != country)
{
auto relations = country->getRelations(GC.second->getTag());
if ((relations) && ((*relations)->getRelations() < 0))
{
vector<shared_ptr<HoI4Country>> tempvector;
if (WorldTargetMap.find(GC.second) == WorldTargetMap.end())
{
tempvector.push_back(country);
WorldTargetMap.insert(make_pair(GC.second, tempvector));
}
if (WorldTargetMap.find(GC.second) != WorldTargetMap.end())
{
tempvector = WorldTargetMap.find(GC.second)->second;
if (find(tempvector.begin(), tempvector.end(), country) == tempvector.end())
tempvector.push_back(country);
WorldTargetMap[GC.second] = tempvector;
}
maxGCWars++;
}
}
}
}
}
}
}
map<double, shared_ptr<HoI4Country>> HoI4WarCreator::getDistancesToGreatPowers(shared_ptr<HoI4Country> country)
{
map<double, shared_ptr<HoI4Country>> GCDistance;
for (auto GC: theWorld->getGreatPowers())
{
set<string> Allies = country->getAllies();
if (std::find(Allies.begin(), Allies.end(), GC->getTag()) == Allies.end())
{
auto distance = getDistanceBetweenCountries(country, GC);
if (distance && (*distance < 2200))
{
GCDistance.insert(make_pair(*distance, GC));
}
}
}
return GCDistance;
}
double HoI4WarCreator::calculateWorldStrength(ofstream& AILog) const
{
double worldStrength = 0.0;
for (auto Faction: theWorld->getFactions())
{
worldStrength += GetFactionStrength(Faction, 3);
}
if (theConfiguration.getDebug())
{
AILog << "Total world strength: " << worldStrength << "\n\n";
}
return worldStrength;
}
void HoI4WarCreator::generateMajorWars(ofstream& AILog, set<shared_ptr<HoI4Faction>>& factionsAtWar, const std::set<std::string>& majorIdeologies, const HoI4::World* world, const HoI4::MapData& theMapData)
{
if (theConfiguration.getDebug())
{
AILog << "Creating major wars\n";
}
for (auto country: theWorld->getCountries())
{
if (isImportantCountry(country.second))
{
vector<shared_ptr<HoI4Faction>> newFactionsAtWar;
if (country.second->getGovernmentIdeology() == "fascism")
{
newFactionsAtWar = fascistWarMaker(country.second, AILog, world, theMapData);
}
else if (country.second->getGovernmentIdeology() == "communism")
{
newFactionsAtWar = communistWarCreator(country.second, majorIdeologies, AILog, theMapData);
}
else if (country.second->getGovernmentIdeology() == "absolutist")
{
newFactionsAtWar = absolutistWarCreator(country.second, theMapData);
}
else if (country.second->getGovernmentIdeology() == "radical")
{
newFactionsAtWar = radicalWarCreator(country.second, theMapData);
}
else if (country.second->getGovernmentIdeology() == "democratic")
{
newFactionsAtWar = democracyWarCreator(country.second);
}
factionsAtWar.insert(newFactionsAtWar.begin(), newFactionsAtWar.end());
}
}
}
double HoI4WarCreator::calculatePercentOfWorldAtWar(ofstream& AILog, const set<shared_ptr<HoI4Faction>>& factionsAtWar, double worldStrength) const
{
double countriesAtWarStrength = 0.0;
for (auto faction : factionsAtWar)
{
countriesAtWarStrength += GetFactionStrength(faction, 3);
}
double percentOfWorldAtWar = countriesAtWarStrength / worldStrength;
if (theConfiguration.getDebug())
{
AILog << "Fraction of world at war " << percentOfWorldAtWar << "\n";
}
return percentOfWorldAtWar;
}
void HoI4WarCreator::generateAdditionalWars(ofstream& AILog, set<shared_ptr<HoI4Faction>>& factionsAtWar, double worldStrength, const HoI4::MapData& theMapData)
{
auto countriesEvilnessSorted = findEvilCountries();
for (int i = countriesEvilnessSorted.size() - 1; i >= 0; i--)
{
if (!isImportantCountry(countriesEvilnessSorted[i]))
{
if (theConfiguration.getDebug())
{
auto name = countriesEvilnessSorted[i]->getSourceCountry()->getName("english");
if (name)
{
AILog << "Checking for war in " + *name << "\n";
}
}
vector<shared_ptr<HoI4Faction>> newCountriesatWar;
newCountriesatWar = neighborWarCreator(countriesEvilnessSorted[i], AILog, theMapData);
for (auto addedFactions : newCountriesatWar)
{
if (std::find(factionsAtWar.begin(), factionsAtWar.end(), addedFactions) == factionsAtWar.end())
{
factionsAtWar.insert(addedFactions);
}
}
}
}
}
bool HoI4WarCreator::isImportantCountry(shared_ptr<HoI4Country> country)
{
if (country->isGreatPower() || country->isHuman())
{
return true;
}
return false;
}
vector<shared_ptr<HoI4Country>> HoI4WarCreator::findEvilCountries() const
{
map<double, shared_ptr<HoI4Country>> countryEvilness;
vector<shared_ptr<HoI4Country>> countriesEvilnessSorted;
for (auto country : theWorld->getCountries())
{
double evilness = 0.5;
if (country.second->getGovernmentIdeology() == "fascism")
evilness += 5;
if (country.second->getGovernmentIdeology() == "absolutist")
evilness += 3;
if (country.second->getGovernmentIdeology() == "communist")
evilness += 3;
if (country.second->getGovernmentIdeology() == "anarcho_liberal")
evilness += 3;
auto countryrulingparty = country.second->getRulingParty();
if (countryrulingparty.getWarPolicy() == "jingoism")
evilness += 3;
else if (countryrulingparty.getWarPolicy() == "pro_military")
evilness += 2;
else if (countryrulingparty.getWarPolicy() == "anti_military")
evilness -= 1;
if (evilness > 2)
{
countryEvilness.insert(make_pair(evilness, country.second));
}
}
//put them into a vector so we know their order
for (auto iterator = countryEvilness.begin(); iterator != countryEvilness.end(); ++iterator)
{
countriesEvilnessSorted.push_back(iterator->second);
}
return countriesEvilnessSorted;
}
void HoI4WarCreator::setSphereLeaders(const Vic2::World* sourceWorld)
{
for (auto greatPower: theWorld->getGreatPowers())
{
auto relations = greatPower->getRelations();
for (auto relation : relations)
{
if (relation.second->getSphereLeader())
{
string tag = relation.second->getTag();
auto spheredcountry = theWorld->getCountries().find(tag);
if (spheredcountry != theWorld->getCountries().end())
{
spheredcountry->second->setSphereLeader(greatPower->getTag());
}
}
}
}
}
string HoI4WarCreator::HowToTakeLand(shared_ptr<HoI4Country> TargetCountry, shared_ptr<HoI4Country> AttackingCountry, double time)
{
string type;
if (TargetCountry != AttackingCountry)
{
auto targetFaction = findFaction(TargetCountry);
auto myFaction = findFaction(AttackingCountry);
//right now assumes you are stronger then them
double myFactionDisStrength = GetFactionStrengthWithDistance(AttackingCountry, myFaction->getMembers(), time);
double enemyFactionDisStrength = GetFactionStrengthWithDistance(TargetCountry, targetFaction->getMembers(), time);
//lets check if I am stronger then their faction
if (AttackingCountry->getStrengthOverTime(time) >= GetFactionStrength(targetFaction, static_cast<int>(time)))
{
//we are stronger, and dont even need ally help
//ADD CONQUEST GOAL
type = "noactionneeded";
}
else
{
//lets check if my faction is stronger
if (myFactionDisStrength >= enemyFactionDisStrength)
{
//ADD CONQUEST GOAL
type = "factionneeded";
}
else
{
//FIXME
//hmm I am still weaker, maybe need to look for allies?
type = "morealliesneeded";
if (GetFactionStrengthWithDistance(AttackingCountry, myFaction->getMembers(), time) >= GetFactionStrengthWithDistance(TargetCountry, targetFaction->getMembers(), time))
{
//ADD CONQUEST GOAL
}
else
{
//Time to Try Coup
type = "coup";
}
}
}
}
return type;
}
vector<shared_ptr<HoI4Country>> HoI4WarCreator::GetMorePossibleAllies(const shared_ptr<HoI4Country> CountryThatWantsAllies)
{
int maxcountries = 0;
vector<shared_ptr<HoI4Country>> newPossibleAllies;
set<string> currentAllies = CountryThatWantsAllies->getAllies();
vector<shared_ptr<HoI4Country>> CountriesWithin1000Miles; //Rename to actual distance
for (auto country : theWorld->getCountries())
{
if (country.second->getProvinceCount() != 0)
{
auto country2 = country.second;
auto distance = getDistanceBetweenCountries(CountryThatWantsAllies, country2);
if (distance && (*distance <= 1000) && (country2 != CountryThatWantsAllies))
{
if (std::find(currentAllies.begin(), currentAllies.end(), country2->getTag()) == currentAllies.end())
{
CountriesWithin1000Miles.push_back(country2);
}
}
}
}
string yourIdeology = CountryThatWantsAllies->getGovernmentIdeology();
//look for all capitals within a distance of Berlin to Tehran
for (unsigned int i = 0; i < CountriesWithin1000Miles.size(); i++)
{
string allyIdeology = CountriesWithin1000Miles[i]->getGovernmentIdeology();
//possible government matches
if (
(allyIdeology == yourIdeology) /* ||
// add other possible combinations here, but maybe coordinate with HoI4World::governmentsAllowFaction()
*/
)
{
if (maxcountries < 2)
{
//FIXME
//check if we are friendly at all?
auto relationsWithPossibleAlly = CountryThatWantsAllies->getRelations(CountriesWithin1000Miles[i]->getTag());
//for now can only ally with people not in a faction, and must be worth adding
if (relationsWithPossibleAlly)
{
int relationsValue = (*relationsWithPossibleAlly)->getRelations();
if ((relationsValue >= -50) && (findFaction(CountriesWithin1000Miles[i])->getMembers().size() <= 1))
{
//ok we dont hate each other, lets check how badly we need each other, well I do, the only reason I am here is im trying to conquer a neighbor and am not strong enough!
//if (GetFactionStrength(findFaction(country)) < 20000) //maybe also check if he has any fascist/comm neighbors he doesnt like later?
//well that ally is weak, he probably wants some friends
if ((relationsValue >= -50) && (relationsValue < 0))
{
//will take some NF to ally
newPossibleAllies.push_back(CountriesWithin1000Miles[i]);
maxcountries++;
}
if (relationsValue >= 0)
{
//well we are positive, 1 NF to add to ally should be fine
newPossibleAllies.push_back(CountriesWithin1000Miles[i]);
maxcountries++;
}
/*else if (relationsValue > 0)
{
//we are friendly, add 2 NF for ally? Good way to decide how many alliances there will be
newPossibleAllies.push_back(country);
i++;
}*/
}
}
}
}
}
return newPossibleAllies;
}
optional<double> HoI4WarCreator::getDistanceBetweenCountries(shared_ptr<HoI4Country> country1, shared_ptr<HoI4Country> country2)
{
if (!bothCountriesHaveCapitals(country1, country2))
{
return {};
}
pair<int, int> country1Position = getCapitalPosition(country1);
pair<int, int> country2Position = getCapitalPosition(country2);
return getDistanceBetweenPoints(country1Position, country2Position);
}
bool HoI4WarCreator::bothCountriesHaveCapitals(shared_ptr<HoI4Country> Country1, shared_ptr<HoI4Country> Country2) const
{
return (Country1->getCapitalStateNum() != 0) && (Country2->getCapitalStateNum() != 0);
}
pair<int, int> HoI4WarCreator::getCapitalPosition(shared_ptr<HoI4Country> country)
{
auto capitalState = country->getCapitalState();
int capitalProvince = capitalState->getVPLocation();
return getProvincePosition(capitalProvince);
}
pair<int, int> HoI4WarCreator::getProvincePosition(int provinceNum)
{
if (provincePositions.size() == 0)
{
establishProvincePositions();
}
auto itr = provincePositions.find(provinceNum);
return itr->second;
}
void HoI4WarCreator::establishProvincePositions()
{
ifstream positionsFile("positions.txt");
if (!positionsFile.is_open())
{
LOG(LogLevel::Error) << "Could not open positions.txt";
exit(-1);
}
string line;
while (getline(positionsFile, line))
{
processPositionLine(line);
}
positionsFile.close();
}
void HoI4WarCreator::processPositionLine(const string& line)
{
vector<string> tokenizedLine = tokenizeLine(line);
addProvincePosition(tokenizedLine);
}
void HoI4WarCreator::addProvincePosition(const vector<string>& tokenizedLine)
{
int province = stoi(tokenizedLine[0]);
int x = stoi(tokenizedLine[2]);
int y = stoi(tokenizedLine[4]);
provincePositions.insert(make_pair(province, make_pair(x, y)));
}
vector<string> HoI4WarCreator::tokenizeLine(const string& line)
{
vector<string> parts;
stringstream ss(line);
string tok;
while (getline(ss, tok, ';'))
{
parts.push_back(tok);
}
return parts;
}
double HoI4WarCreator::getDistanceBetweenPoints(pair<int, int> point1, pair<int, int> point2) const
{
int xDistance = abs(point2.first - point1.first);
if (xDistance > 2625)
{
xDistance = 5250 - xDistance;
}
int yDistance = point2.second - point1.second;
return sqrt(pow(xDistance, 2) + pow(yDistance, 2));
}
double HoI4WarCreator::GetFactionStrengthWithDistance(shared_ptr<HoI4Country> HomeCountry, vector<shared_ptr<HoI4Country>> Faction, double time)
{
double strength = 0.0;
for (auto country: Faction)
{
double distanceMulti = 1;
if (country != HomeCountry)
{
auto distance = getDistanceBetweenCountries(HomeCountry, country);
if (distance)
{
if (*distance < 300)
distanceMulti = 1;
else if (*distance < 500)
distanceMulti = 0.9;
else if (*distance < 750)
distanceMulti = 0.8;
else if (*distance < 1000)
distanceMulti = 0.7;
else if (*distance < 1500)
distanceMulti = 0.5;
else if (*distance < 2000)
distanceMulti = 0.3;
else
distanceMulti = 0.2;
}
}
strength += country->getStrengthOverTime(time) * distanceMulti;
}
return strength;
}
shared_ptr<HoI4Faction> HoI4WarCreator::findFaction(shared_ptr<HoI4Country> CheckingCountry)
{
for (auto faction : theWorld->getFactions())
{
auto FactionMembers = faction->getMembers();
if (std::find(FactionMembers.begin(), FactionMembers.end(), CheckingCountry) != FactionMembers.end())
{
//if country is in faction list, it is part of that faction
return faction;
}
}
vector<shared_ptr<HoI4Country>> myself;
myself.push_back(CheckingCountry);
return make_shared<HoI4Faction>(CheckingCountry, myself);
}
map<string, shared_ptr<HoI4Country>> HoI4WarCreator::getNeighbors(shared_ptr<HoI4Country> checkingCountry, const HoI4::MapData& theMapData)
{
map<string, shared_ptr<HoI4Country>> neighbors = getImmediateNeighbors(checkingCountry, theMapData);
if (neighbors.size() == 0)
{
neighbors = getNearbyCountries(checkingCountry);
}
return neighbors;
}
map<string, shared_ptr<HoI4Country>> HoI4WarCreator::getImmediateNeighbors(shared_ptr<HoI4Country> checkingCountry, const HoI4::MapData& theMapData)
{
map<string, shared_ptr<HoI4Country>> neighbors;
for (auto province: checkingCountry->getProvinces())
{
for (int provinceNumber: theMapData.getNeighbors(province))
{
if (!provinceDefinitions::isLandProvince(province))
{
continue;
}
auto provinceToOwnerItr = provinceToOwnerMap.find(provinceNumber);
if (provinceToOwnerItr == provinceToOwnerMap.end())
{
continue;
}
string ownerTag = provinceToOwnerItr->second;
auto ownerCountry = theWorld->getCountries().find(ownerTag)->second;
if (ownerCountry != checkingCountry)
{
neighbors.insert(make_pair(ownerTag, ownerCountry));
}
}
}
return neighbors;
}
map<string, shared_ptr<HoI4Country>> HoI4WarCreator::getNearbyCountries(shared_ptr<HoI4Country> checkingCountry)
{
map<string, shared_ptr<HoI4Country>> neighbors;
for (auto countryItr: theWorld->getCountries())
{
auto country = countryItr.second;
if (country->getCapitalStateNum() != 0)
{
//IMPROVE
//need to get further neighbors, as well as countries without capital in an area
auto distance = getDistanceBetweenCountries(checkingCountry, country);
if (distance && (*distance <= 500) && (country->getProvinceCount() > 0))
{
neighbors.insert(countryItr);
}
}
}
return neighbors;
}
void HoI4WarCreator::determineProvinceOwners()
{
for (auto state: theWorld->getStates())
{
for (auto province: state.second->getProvinces())
{
string owner = state.second->getOwner();
provinceToOwnerMap.insert(make_pair(province, owner));
}
}
}
double HoI4WarCreator::GetFactionStrength(const shared_ptr<HoI4Faction> Faction, int years) const
{
double strength = 0;
for (auto country : Faction->getMembers())
{
strength += country->getStrengthOverTime(years);
}
return strength;
}
vector<shared_ptr<HoI4Faction>> HoI4WarCreator::fascistWarMaker(shared_ptr<HoI4Country> Leader, ofstream& AILog, const HoI4::World* world, const HoI4::MapData& theMapData)
{
vector<shared_ptr<HoI4Faction>> CountriesAtWar;
auto name = Leader->getSourceCountry()->getName("english");
if (name)
{
LOG(LogLevel::Info) << "Calculating AI for " + *name;
}
else
{
LOG(LogLevel::Info) << "Calculating AI";
}
//too many lists, need to clean up
vector<shared_ptr<HoI4Country>> Targets;
vector<shared_ptr<HoI4Country>> Anschluss;
vector<shared_ptr<HoI4Country>> Sudeten;
vector<shared_ptr<HoI4Country>> EqualTargets;
vector<shared_ptr<HoI4Country>> DifficultTargets;
//getting country provinces and its neighbors
auto AllNeighbors = getNeighbors(Leader, theMapData);
map<string, shared_ptr<HoI4Country>> CloseNeighbors;
//gets neighbors that are actually close to you
for (auto neigh: AllNeighbors)
{
if (neigh.second->getCapitalStateNum() != 0)
{
//IMPROVE
//need to get further neighbors, as well as countries without capital in an area
auto distance = getDistanceBetweenCountries(Leader, neigh.second);
if (distance && (distance <= 500))
{
CloseNeighbors.insert(neigh);
}
}
}
set<string> Allies = Leader->getAllies();
//should add method to look for cores you dont own
//should add method to look for more allies
//lets look for weak neighbors
if (name)
{
LOG(LogLevel::Info) << "Doing Neighbor calcs for " + *name;
}
else
{
LOG(LogLevel::Info) << "Doing Neighbor calcs";
}
for (auto neigh : CloseNeighbors)
{
//lets check to see if they are not our ally and not a great country
if (std::find(Allies.begin(), Allies.end(), neigh.second->getTag()) == Allies.end() && !neigh.second->isGreatPower())
{
volatile double enemystrength = neigh.second->getStrengthOverTime(1.5);
volatile double mystrength = Leader->getStrengthOverTime(1.5);
//lets see their strength is at least < 20%
if (neigh.second->getStrengthOverTime(1.5) < Leader->getStrengthOverTime(1.5)*0.2 && findFaction(neigh.second)->getMembers().size() == 1)
{
//they are very weak
Anschluss.push_back(neigh.second);
}
//if not, lets see their strength is at least < 60%
else if (neigh.second->getStrengthOverTime(1.5) < Leader->getStrengthOverTime(1.5)*0.6 && neigh.second->getStrengthOverTime(1.5) > Leader->getStrengthOverTime(1.5)*0.2 && findFaction(neigh.second)->getMembers().size() == 1)
{
//they are weak and we can get 1 of these countries in sudeten deal
Sudeten.push_back(neigh.second);
}
//if not, lets see their strength is at least = to ours%
else if (neigh.second->getStrengthOverTime(1.5) < Leader->getStrengthOverTime(1.5))
{
//EqualTargets.push_back(neigh);
EqualTargets.push_back(neigh.second);
}
//if not, lets see their strength is at least < 120%
else if (neigh.second->getStrengthOverTime(1.5) < Leader->getStrengthOverTime(1.5)*1.2)
{
//StrongerTargets.push_back(neigh);
DifficultTargets.push_back(neigh.second);
}
}
}
//string that contains all events
string Events;
string s;
map<string, vector<HoI4Country*>> TargetMap;
vector<shared_ptr<HoI4Country>> anchlussnan;
vector<shared_ptr<HoI4Country>> sudatennan;
vector<shared_ptr<HoI4Country>> nan;
vector<shared_ptr<HoI4Country>> fn;
vector<shared_ptr<HoI4Country>> man;
vector<shared_ptr<HoI4Country>> coup;
//look through every anchluss and see its difficulty
for (auto target : Anschluss)
{
string type;
//outputs are for HowToTakeLand()
//noactionneeded - Can take target without any help
//factionneeded - can take target and faction with attackers faction helping
//morealliesneeded - can take target with more allies, comes with "newallies" in map
//coup - cant take over, need to coup
type = HowToTakeLand(target, Leader, 1.5);
if (type == "noactionneeded")
{
//too many vectors, need to clean up
nan.push_back(target);
}
}
//gives us generic focus tree start
auto FocusTree = genericFocusTree->makeCustomizedCopy(*Leader);
FocusTree->addFascistAnnexationBranch(Leader, nan, theWorld->getEvents());
nan.clear();
for (auto target : Sudeten)
{
string type;
//outputs are
//noactionneeded - Can take target without any help
//factionneeded - can take target and faction with attackers faction helping
//morealliesneeded - can take target with more allies, comes with "newallies" in map
//coup - cant take over, need to coup
type = HowToTakeLand(target, Leader, 2.5);
if (type == "noactionneeded")
{
nan.push_back(target);
}
}
//find neighboring states to take in sudeten deal
vector<vector<int>> demandedStates;
for (unsigned int i = 0; i < nan.size(); i++)
{
set<int> borderStates = findBorderState(Leader, nan[i], world, theMapData);
demandedStates.push_back(sortStatesByCapitalDistance(borderStates, Leader, world));
}
FocusTree->addFascistSudetenBranch(Leader, nan, demandedStates, theWorld);
nan.clear();
//events for allies
auto newAllies = GetMorePossibleAllies(Leader);
if (theConfiguration.getCreateFactions())
{
if (newAllies.size() > 0 && Leader->getFaction() == nullptr)
{
vector<shared_ptr<HoI4Country>> self;
self.push_back(Leader);
auto newFaction = make_shared<HoI4Faction>(Leader, self);
Leader->setFaction(newFaction);
}
}
vector<shared_ptr<HoI4Faction>> FactionsAttackingMe;
if (WorldTargetMap.find(Leader) != WorldTargetMap.end())
{
for (auto country: WorldTargetMap.find(Leader)->second)
{
auto attackingFaction = findFaction(country);
if (find(FactionsAttackingMe.begin(), FactionsAttackingMe.end(), attackingFaction) == FactionsAttackingMe.end())
{
FactionsAttackingMe.push_back(attackingFaction);
}
}
double FactionsAttackingMeStrength = 0;
for (auto attackingFaction: FactionsAttackingMe)
{
FactionsAttackingMeStrength += GetFactionStrengthWithDistance(Leader, attackingFaction->getMembers(), 3);
}
if (theConfiguration.getDebug())
{
if (name)
{
AILog << "\t" << *name << " is under threat, there are " << FactionsAttackingMe.size() << " faction(s) attacking them, I have a strength of " << GetFactionStrength(findFaction(Leader), 3) << " and they have a strength of " << FactionsAttackingMeStrength << "\n";
}
else
{
AILog << "\t" << "A country is under threat, there are " << FactionsAttackingMe.size() << " faction(s) attacking them, I have a strength of " << GetFactionStrength(findFaction(Leader), 3) << " and they have a strength of " << FactionsAttackingMeStrength << "\n";
}
}
if (FactionsAttackingMeStrength > GetFactionStrength(findFaction(Leader), 3))
{
vector<HoI4Country*> GCAllies;
int maxGCAlliance = 0;
for (auto GC: theWorld->getGreatPowers())
{
auto allyName = GC->getSourceCountry()->getName("english");
auto relations = Leader->getRelations(GC->getTag());
if ((relations) && ((*relations)->getRelations() > 0) && (maxGCAlliance < 1))
{
if (theConfiguration.getDebug())
{
if (name)
{
if (allyName)
{
AILog << "\t" << *name << " can attempt to ally " << *allyName << "\n";
}
else
{
AILog << "\t" << *name << " can attempt to ally a country\n";
}
}
else
{
if (allyName)
{
AILog << "\t" << "A country can attempt to ally " << *allyName << "\n";
}
else
{
AILog << "\t" << "A country can attempt to ally a country\n";
}
}
}
if (theConfiguration.getCreateFactions())
{
if (GC->getFaction() == nullptr)
{
vector<shared_ptr<HoI4Country>> self;
self.push_back(GC);
auto newFaction = make_shared<HoI4Faction>(GC, self);
GC->setFaction(newFaction);
}
theWorld->getEvents()->createFactionEvents(Leader, GC);
}
newAllies.push_back(GC);
maxGCAlliance++;
}
}
}
}
//Declaring war with Great Country
map<double, shared_ptr<HoI4Country>> GCDistance;
vector<shared_ptr<HoI4Country>> GCDistanceSorted;
//get great countries with a distance
for (auto GC: theWorld->getGreatPowers())
{
auto distance = getDistanceBetweenCountries(Leader, GC);
if (distance)
{
GCDistance.insert(make_pair(*distance, GC));
}
}
//put them into a vector so we know their order
for (auto iterator = GCDistance.begin(); iterator != GCDistance.end(); ++iterator)
{
GCDistanceSorted.push_back(iterator->second);
}
vector<shared_ptr<HoI4Country>> GCTargets;
for (auto GC: GCDistanceSorted)
{
string HowToTakeGC = HowToTakeLand(GC, Leader, 3);
if (HowToTakeGC == "noactionneeded" || HowToTakeGC == "factionneeded" || HowToTakeGC == "morealliesneeded")
{
auto relations = Leader->getRelations(GC->getTag());
if ((GC != Leader) && (relations) && ((*relations)->getRelations() < 0))
{
if (GCTargets.size() < maxGCWars)
{
GCTargets.push_back(GC);
}
}
}
}
FocusTree->addGPWarBranch(Leader, newAllies, GCTargets, "Fascist", theWorld->getEvents());
Leader->addNationalFocus(FocusTree);
return CountriesAtWar;
}
vector<shared_ptr<HoI4Faction>> HoI4WarCreator::communistWarCreator(shared_ptr<HoI4Country> Leader, const std::set<std::string>& majorIdeologies, ofstream& AILog, const HoI4::MapData& theMapData)
{
vector<shared_ptr<HoI4Faction>> CountriesAtWar;
//communism still needs great country war events
auto name = Leader->getSourceCountry()->getName("english");
if (name)
{
LOG(LogLevel::Info) << "Calculating AI for " + *name;
LOG(LogLevel::Info) << "Calculating Neighbors for " + *name;
}
else
{
LOG(LogLevel::Info) << "Calculating AI for a country";
LOG(LogLevel::Info) << "Calculating Neighbors for a country";
}
auto AllNeighbors = getNeighbors(Leader, theMapData);
map<string, shared_ptr<HoI4Country>> Neighbors;
for (auto neigh: AllNeighbors)
{
if (neigh.second->getCapitalStateNum() != 0)
{
//IMPROVE
//need to get further neighbors, as well as countries without capital in an area
auto distance = getDistanceBetweenCountries(Leader, neigh.second);
if (distance && (distance <= 400))
{
Neighbors.insert(neigh);
}
}
}
set<string> Allies = Leader->getAllies();
vector<shared_ptr<HoI4Country>> Targets;
map<string, vector<shared_ptr<HoI4Country>>> NationalFocusesMap;
vector<shared_ptr<HoI4Country>> coups;
vector<shared_ptr<HoI4Country>> forcedtakeover;
//if (Permanant Revolution)
//Decide between Anti - Democratic Focus, Anti - Monarch Focus, or Anti - Fascist Focus(Look at all great powers and get average relation between each ideology, the one with the lowest average relation leads to that focus).
//Attempt to ally with other Communist Countries(with Permanant Revolution)
if (name)
{
LOG(LogLevel::Info) << "Doing Neighbor calcs for " + *name;
}
else
{
LOG(LogLevel::Info) << "Doing Neighbor calcs for a country";
}
for (auto neigh : Neighbors)
{
//lets check to see if they are our ally and not a great country
if (std::find(Allies.begin(), Allies.end(), neigh.second->getTag()) == Allies.end() && !neigh.second->isGreatPower())
{
double com = 0;
auto neighFaction = findFaction(neigh.second);
for (auto party : neigh.second->getIdeologySupport())
{
if ((party.first == "socialist") || (party.first == "communist") || (party.first == "anarcho_liberal"))
com += party.second;
}
if (com > 25 && neigh.second->getRulingParty().getIdeology() != "communist" && HowToTakeLand(neigh.second, Leader, 2.5) == "coup")
{
//look for neighboring countries to spread communism too(Need 25 % or more Communism support), Prioritizing those with "Communism Allowed" Flags, prioritizing those who are weakest
// Method() Influence Ideology and Attempt Coup
coups.push_back(neigh.second);
}
else if (neighFaction->getMembers().size() == 1 && neigh.second->getRulingParty().getIdeology() != "communist")
{
// Then look for neighboring countries to spread communism by force, prioritizing weakest first
forcedtakeover.push_back(neigh.second);
// Depending on Anti - Ideology Focus, look for allies in alternate ideologies to get to ally with to declare war against Anti - Ideology Country.
}
}
}
//if (Socialism in One State)
// Events / Focuses to increase Industrialization and defense of the country, becomes Isolationist
// Eventually gets events to drop Socialism in One state and switch to permanant revolution(Maybe ? )
string s;
map<string, vector<shared_ptr<HoI4Country>>> TargetMap;
vector<shared_ptr<HoI4Country>> nan;
vector<shared_ptr<HoI4Country>> fn;
vector<shared_ptr<HoI4Country>> man;
vector<shared_ptr<HoI4Country>> coup;
for (auto target : forcedtakeover)
{
string type;
//outputs are
//noactionneeded - Can take target without any help
//factionneeded - can take target and faction with attackers faction helping
//morealliesneeded - can take target with more allies, comes with "newallies" in map
//coup - cant take over, need to coup
type = HowToTakeLand(target, Leader, 2.5);
if (type == "noactionneeded")
nan.push_back(target);
else if (type == "factionneeded")
fn.push_back(target);
else if (type == "morealliesneeded")
man.push_back(target);
else if (type == "coup")
coup.push_back(target);
}
//insert these values in targetmap for use later possibly?
TargetMap.insert(make_pair("noactionneeded", nan));
TargetMap.insert(make_pair("factionneeded", fn));
TargetMap.insert(make_pair("morealliesneeded", man));
TargetMap.insert(make_pair("coup", coup));
vector<shared_ptr<HoI4Country>> TargetsByTech;
bool first = true;
//FIXME
//Right now just uses everyone in forcedtakover, doesnt use nan, fn, ect...
for (auto country : forcedtakeover)
{
if (first)
{
TargetsByTech.push_back(country);
first = false;
}
else
{
//makes sure not a coup target
if (find(coups.begin(), coups.end(), country) == coups.end())
{
if (TargetsByTech.front()->getTechnologyCount() < country->getTechnologyCount())
{
TargetsByTech.insert(TargetsByTech.begin(), country);
}
else
TargetsByTech.push_back(country);
}
}
}
// Candidates for Get Allies foci
auto newAllies = GetMorePossibleAllies(Leader);
//Declaring war with Great Country
map<double, shared_ptr<HoI4Country>> GCDistance;
vector<shared_ptr<HoI4Country>> GCDistanceSorted;
for (auto GC : theWorld->getGreatPowers())
{
auto distance = getDistanceBetweenCountries(Leader, GC);
if (distance && (distance < 1200))
{
GCDistance.insert(make_pair(*distance, GC));
}
}
//put them into a vector so we know their order
for (auto iterator = GCDistance.begin(); iterator != GCDistance.end(); ++iterator)
{
GCDistanceSorted.push_back(iterator->second);
}
sort(GCDistanceSorted.begin(), GCDistanceSorted.end());
vector<shared_ptr<HoI4Country>> GCTargets;
for (auto GC : GCDistanceSorted)
{
string thetag = GC->getTag();
string HowToTakeGC = HowToTakeLand(GC, Leader, 3);
if (HowToTakeGC == "noactionneeded" || HowToTakeGC == "factionneeded")
{
if (GC != Leader)
GCTargets.push_back(GC);
}
if (HowToTakeGC == "morealliesneeded")
{
//TODO
}
}
int start = 0;
for (auto GC : GCTargets)
{
auto relations = Leader->getRelations(GC->getTag());
if ((relations) && ((*relations)->getRelations() < 0))
{
GCTargets.push_back(GC);
}
if (GCTargets.size() >= maxGCWars) break;
}
auto FocusTree = genericFocusTree->makeCustomizedCopy(*Leader);
FocusTree->addCommunistCoupBranch(Leader, forcedtakeover, majorIdeologies);
FocusTree->addCommunistWarBranch(Leader, TargetsByTech, theWorld->getEvents());
FocusTree->addGPWarBranch(Leader, newAllies, GCTargets, "Communist", theWorld->getEvents());
Leader->addNationalFocus(FocusTree);
return CountriesAtWar;
}
vector<shared_ptr<HoI4Faction>> HoI4WarCreator::democracyWarCreator(shared_ptr<HoI4Country> Leader)
{
vector<shared_ptr<HoI4Faction>> CountriesAtWar;
map<int, shared_ptr<HoI4Country>> CountriesToContain;
vector<shared_ptr<HoI4Country>> vCountriesToContain;
set<string> Allies = Leader->getAllies();
int v1 = rand() % 100;
v1 = v1 / 100;
auto FocusTree = genericFocusTree->makeCustomizedCopy(*Leader);
for (auto GC: theWorld->getGreatPowers())
{
auto relations = Leader->getRelations(GC->getTag());
if (relations)
{
double relationVal = (*relations)->getRelations();
if (relationVal < 100 && GC->getGovernmentIdeology() != "democratic" && std::find(Allies.begin(), Allies.end(), GC->getTag()) == Allies.end())
{
CountriesAtWar.push_back(findFaction(Leader));
CountriesToContain.insert(make_pair(static_cast<int>(relationVal + v1), GC));
}
}
}
for (auto country : CountriesToContain)
{
vCountriesToContain.push_back(country.second);
}
if (vCountriesToContain.size() > 0)
{
FocusTree->addDemocracyNationalFocuses(Leader, vCountriesToContain);
}
Leader->addNationalFocus(FocusTree);
return CountriesAtWar;
}
vector<shared_ptr<HoI4Faction>> HoI4WarCreator::absolutistWarCreator(shared_ptr<HoI4Country> country, const HoI4::MapData& theMapData)
{
auto focusTree = genericFocusTree->makeCustomizedCopy(*country);
auto name = country->getSourceCountry()->getName("english");
if (name)
{
LOG(LogLevel::Info) << "Doing neighbor calcs for " + *name;
}
else
{
LOG(LogLevel::Info) << "Doing neighbor calcs for a country";
}
auto weakNeighbors = findWeakNeighbors(country, theMapData);
auto weakColonies = findWeakColonies(country, theMapData);
focusTree->addAbsolutistEmpireNationalFocuses(country, weakColonies, weakNeighbors);
auto greatPowerTargets = getGreatPowerTargets(country);
auto CountriesAtWar = addGreatPowerWars(country, focusTree, greatPowerTargets);
addTradeEvents(country, greatPowerTargets);
country->addNationalFocus(focusTree);
return CountriesAtWar;
}
vector<shared_ptr<HoI4Faction>> HoI4WarCreator::neighborWarCreator(shared_ptr<HoI4Country> country, ofstream & AILog, const HoI4::MapData& theMapData)
{
// add small wars against neigbors for non-great powers
vector<shared_ptr<HoI4Faction>> countriesAtWar;
auto weakNeighbors = findWeakNeighbors(country, theMapData);
int numWarsWithNeighbors = 0;
vector<shared_ptr<HoI4Focus>> newFocuses;
if (theConfiguration.getDebug())
{
auto name = country->getSourceCountry()->getName("english");
if (name)
{
AILog << "Look for neighbors to attack for " + *name << "\n";
}
else
{
AILog << "Look for neighbors to attack for a country\n";
}
}
for (auto target : weakNeighbors)
{
auto focusTree = genericFocusTree->makeCustomizedCopy(*country);
if (numWarsWithNeighbors >= 2)
{
break;
}
int relations = 0;
auto relationsObj = country->getRelations(target->getTag());
if (relationsObj)
{
relations = (*relationsObj)->getRelations();
}
if (relations >= 0)
{
continue;
}
set<string> Allies = country->getAllies();
date startDate = date("1937.01.01");
startDate.increaseByMonths(relations / -4);
if (Allies.find(target->getTag()) == Allies.end())
{
auto possibleTargetName = target->getSourceCountry()->getName("english");
string targetName;
if (possibleTargetName)
{
targetName = *possibleTargetName;
}
else
{
LOG(LogLevel::Warning) << "Could not set target name in neighbor war creator";
targetName = "";
}
countriesAtWar.push_back(findFaction(country));
if (theConfiguration.getDebug())
{
AILog << "Creating focus to attack " + targetName << "\n";
}
focusTree->addNeighborWarBranch(country->getTag(), weakNeighbors, target, targetName, startDate, numWarsWithNeighbors);
numWarsWithNeighbors++;
}
}
if (numWarsWithNeighbors > 0)
{
auto focusTree = genericFocusTree->makeCustomizedCopy(*country);
for (auto newFocus: newFocuses)
{
focusTree->addFocus(newFocus);
}
country->addNationalFocus(focusTree);
}
return countriesAtWar;
}
vector<shared_ptr<HoI4Faction>> HoI4WarCreator::radicalWarCreator(shared_ptr<HoI4Country> country, const HoI4::MapData& theMapData)
{
return absolutistWarCreator(country, theMapData);
}
set<int> HoI4WarCreator::findBorderState(shared_ptr<HoI4Country> country, shared_ptr<HoI4Country> neighbor, const HoI4::World* world, const HoI4::MapData& theMapData)
{
set<int> demandedStates;
std::map<int,int> provinceToStateIdMapping = world->getProvinceToStateIDMap();
for (auto leaderprov : country->getProvinces())
{
for (int prov : theMapData.getNeighbors(leaderprov))
{
if (!provinceDefinitions::isLandProvince(prov))
{
continue;
}
if (provinceToOwnerMap.find(prov) != provinceToOwnerMap.end())
{
string owner = provinceToOwnerMap.find(prov)->second;
if (owner == neighbor->getTag())
{
demandedStates.insert(provinceToStateIdMapping[prov]);
}
}
}
}
return demandedStates;
}
vector<int> HoI4WarCreator::sortStatesByCapitalDistance(set<int> stateList, shared_ptr<HoI4Country> country, const HoI4::World* world)
{
multimap<double, int> statesWithDistance;
pair<int, int> capitalCoords = getCapitalPosition(country);
map<int, HoI4::State*> statesMapping = world->getStates();
for (int stateID : stateList)
{
HoI4::State* stateObj = statesMapping[stateID];
int provCapID = stateObj->getVPLocation();
pair<int, int> stateVPCoords = getProvincePosition(provCapID);
double distanceSquared = pow(capitalCoords.first - stateVPCoords.first, 2)
+ pow(capitalCoords.second - stateVPCoords.second, 2);
statesWithDistance.insert(pair<double, int>(distanceSquared, stateID));
}
vector<int> sortedStates;
for (pair<double, int> oneStateDistance : statesWithDistance)
{
sortedStates.push_back(oneStateDistance.second);
}
return sortedStates;
}
vector<shared_ptr<HoI4Country>> HoI4WarCreator::findWeakNeighbors(shared_ptr<HoI4Country> country, const HoI4::MapData& theMapData)
{
vector<shared_ptr<HoI4Country>> weakNeighbors;
auto allies = country->getAllies();
for (auto neighbor: findCloseNeighbors(country, theMapData))
{
if (allies.find(neighbor.second->getTag()) != allies.end())
{
continue;
}
if (neighbor.second->isGreatPower())
{
continue;
}
double enemystrength = neighbor.second->getStrengthOverTime(1.5);
double mystrength = country->getStrengthOverTime(1.5);
if (
(enemystrength < (mystrength * 0.5)) &&
(findFaction(neighbor.second)->getMembers().size() == 1)
)
{
weakNeighbors.push_back(neighbor.second);
}
}
return weakNeighbors;
}
map<string, shared_ptr<HoI4Country>> HoI4WarCreator::findCloseNeighbors(shared_ptr<HoI4Country> country, const HoI4::MapData& theMapData)
{
map<string, shared_ptr<HoI4Country>> closeNeighbors;
for (auto neighbor: getNeighbors(country, theMapData))
{
if ((neighbor.second->getCapitalStateNum() != 0) && (neighbor.first != ""))
{
auto distance = getDistanceBetweenCountries(country, neighbor.second);
if (distance && (*distance <= 500))
{
closeNeighbors.insert(neighbor);
}
}
}
return closeNeighbors;
}
vector<shared_ptr<HoI4Country>> HoI4WarCreator::findWeakColonies(shared_ptr<HoI4Country> country, const HoI4::MapData& theMapData)
{
vector<shared_ptr<HoI4Country>> weakColonies;
auto allies = country->getAllies();
for (auto neighbor: findFarNeighbors(country, theMapData))
{
if (allies.find(neighbor.second->getTag()) != allies.end())
{
continue;
}
if (neighbor.second->isGreatPower())
{
continue;
}
double enemystrength = neighbor.second->getStrengthOverTime(1.5);
double mystrength = country->getStrengthOverTime(1.5);
if (
(enemystrength < mystrength * 0.5) &&
(findFaction(neighbor.second)->getMembers().size() == 1)
)
{
weakColonies.push_back(neighbor.second);
}
}
return weakColonies;
}
map<string, shared_ptr<HoI4Country>> HoI4WarCreator::findFarNeighbors(shared_ptr<HoI4Country> country, const HoI4::MapData& theMapData)
{
map<string, shared_ptr<HoI4Country>> farNeighbors;
for (auto neighbor: getNeighbors(country, theMapData))
{
if (neighbor.second->getCapitalStateNum() != 0)
{
auto distance = getDistanceBetweenCountries(country, neighbor.second);
if (distance && (*distance > 500))
{
farNeighbors.insert(neighbor);
}
}
}
if (farNeighbors.size() == 0) // find all nearby countries
{
for (auto otherCountry: theWorld->getCountries())
{
if (otherCountry.second->getCapitalStateNum() != 0)
{
auto distance = getDistanceBetweenCountries(country, otherCountry.second);
if (distance && (*distance <= 1000) && (otherCountry.second->getProvinceCount() > 0))
{
farNeighbors.insert(otherCountry);
}
}
}
}
return farNeighbors;
}
vector<shared_ptr<HoI4Country>> HoI4WarCreator::getGreatPowerTargets(shared_ptr<HoI4Country> country)
{
vector<shared_ptr<HoI4Country>> greatPowerTargets;
for (auto greatPower: getGPsByDistance(country))
{
string prereqsNeeded = HowToTakeLand(greatPower.second, country, 3);
if (prereqsNeeded == "noactionneeded" || prereqsNeeded == "factionneeded")
{
if (greatPower.second != country)
{
greatPowerTargets.push_back(greatPower.second);
}
}
if (prereqsNeeded == "morealliesneeded")
{
}
}
return greatPowerTargets;
}
map<double, shared_ptr<HoI4Country>> HoI4WarCreator::getGPsByDistance(shared_ptr<HoI4Country> country)
{
map<double, shared_ptr<HoI4Country>> distanceToGPMap;
for (auto greatPower: theWorld->getGreatPowers())
{
auto distance = getDistanceBetweenCountries(country, greatPower);
if (distance && (*distance < 1200))
{
distanceToGPMap.insert(make_pair(*distance, greatPower));
}
}
return distanceToGPMap;
}
vector<shared_ptr<HoI4Faction>> HoI4WarCreator::addGreatPowerWars(shared_ptr<HoI4Country> country, shared_ptr<HoI4FocusTree> FocusTree, vector<shared_ptr<HoI4Country>>& greatPowerTargets)
{
vector<shared_ptr<HoI4Faction>> countriesAtWar;
int numWarsWithGreatPowers = 0;
for (auto target: greatPowerTargets)
{
if (numWarsWithGreatPowers >= 2)
{
break;
}
auto relations = country->getRelations(target->getTag());
if ((!relations) || ((*relations)->getRelations() >= 0))
{
continue;
}
set<string> Allies = country->getAllies();
if (Allies.find(target->getTag()) == Allies.end())
{
auto possibleTargetName = target->getSourceCountry()->getName("english");
string targetName;
if (possibleTargetName)
{
targetName = *possibleTargetName;
}
else
{
LOG(LogLevel::Warning) << "Could not set target name in great power war creator";
targetName = "";
}
countriesAtWar.push_back(findFaction(country));
shared_ptr<HoI4Focus> newFocus = make_shared<HoI4Focus>();
newFocus->id = "War" + target->getTag() + country->getTag();
newFocus->icon = "GFX_goal_generic_major_war";
newFocus->text = "War with " + targetName;//change to faction name later
newFocus->available = "= {\n";
newFocus->available += " has_war = no\n";
newFocus->available += " date > 1939.1.1\n";
newFocus->available += " }";
newFocus->xPos = 31 + numWarsWithGreatPowers * 2;
newFocus->yPos = 5;
newFocus->cost = 10;
newFocus->aiWillDo = "= {\n";
newFocus->aiWillDo += " factor = " + to_string(10 - numWarsWithGreatPowers * 5) + "\n";
newFocus->aiWillDo += " modifier = {\n";
newFocus->aiWillDo += " factor = 0\n";
newFocus->aiWillDo += " strength_ratio = { tag = " + target->getTag() + " ratio < 0.8 }\n";
newFocus->aiWillDo += " }";
if (greatPowerTargets.size() > 2) //make ai have this as a 0 modifier if they are at war
{
newFocus->aiWillDo += "\n";
newFocus->aiWillDo += " modifier = {\n";
newFocus->aiWillDo += " factor = 0\n";
newFocus->aiWillDo += " OR = {\n";
for (auto target2: greatPowerTargets)
{
if (target != target2)
{
newFocus->aiWillDo += " has_war_with = " + target2->getTag() + "\n";
}
}
newFocus->aiWillDo += " }\n";
newFocus->aiWillDo += " }";
}
newFocus->aiWillDo += "\n";
newFocus->aiWillDo += " }";
newFocus->bypass += "= {\n";
newFocus->bypass += " has_war_with = " + target->getTag() + "\n";
newFocus->bypass += " }";
newFocus->completionReward += "= {\n";
newFocus->completionReward += " add_named_threat = { threat = 5 name = " + newFocus->id + " }\n";
newFocus->completionReward += " declare_war_on = {\n";
newFocus->completionReward += " type = annex_everything\n";
newFocus->completionReward += " target = " + target->getTag() + "\n";
newFocus->completionReward += " }\n";
newFocus->completionReward += " }";
FocusTree->addFocus(newFocus);
numWarsWithGreatPowers++;
}
}
return countriesAtWar;
}
void HoI4WarCreator::addTradeEvents(shared_ptr<HoI4Country> country, const vector<shared_ptr<HoI4Country>>& greatPowerTargets)
{
for (auto greatPowerTarget: greatPowerTargets)
{
auto relations = country->getRelations(greatPowerTarget->getTag());
if ((!relations) || ((*relations)->getRelations() >= 0))
{
continue;
}
theWorld->getEvents()->createTradeEvent(country, greatPowerTarget);
}
} | 412 | 0.921908 | 1 | 0.921908 | game-dev | MEDIA | 0.959994 | game-dev | 0.87519 | 1 | 0.87519 |
Icydeath/ffxi-addons | 3,385 | ffxikeys/model/dialogue/use.lua | local NilDialogue = require('model/dialogue/nil')
local NilMenu = require('model/menu/nil')
local Trade = require('model/interaction/trade')
local Choice = require('model/interaction/choice')
local NilInteraction = require('model/interaction/nil')
local MenuFactory = require('model/menu/factory')
--------------------------------------------------------------------------------
local function ParseReward(pkt)
return packets.parse('incoming', pkt)['Param 1']
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local UseDialogue = NilDialogue:NilDialogue()
UseDialogue.__index = UseDialogue
--------------------------------------------------------------------------------
function UseDialogue:UseDialogue(target, player, item_id)
local o = NilDialogue:NilDialogue()
setmetatable(o, self)
o._target = target
o._player = player
o._item_id = item_id
o._type = 'UseDialogue'
o._menu = NilMenu:NilMenu()
o._interactions = {}
o._idx = 1
o._reward = nil
o._end = NilInteraction:NilInteraction()
o._end:SetSuccessCallback(function() o._on_success(o._reward) end)
o._end:SetFailureCallback(function() o._on_success() end)
setmetatable(o._interactions, { __index = function() return o._end end })
o:_AppendInteraction(NilInteraction:NilInteraction())
o:_AppendInteraction(Trade:Trade())
return o
end
--------------------------------------------------------------------------------
function UseDialogue:OnIncomingData(id, pkt)
local block = false
if id == 0x037 then
block = true
elseif id == 0x034 or id == 0x032 then
block = true
self._menu = MenuFactory.CreateUseMenu(pkt)
self:_AppendInteraction(Choice:Choice())
elseif id == 0x05C then
block = true
self._menu = MenuFactory.CreateExtraMenu(pkt, self._menu, self._item_id, 0)
self:_AppendInteraction(Choice:Choice())
elseif id == 0x02A then
block = false
self._reward = ParseReward(pkt)
end
return (self._interactions[self._idx]:OnIncomingData(id, pkt) or block)
end
--------------------------------------------------------------------------------
function UseDialogue:OnOutgoingData(id, pkt)
return self._interactions[self._idx]:OnOutgoingData(id, pkt)
end
--------------------------------------------------------------------------------
function UseDialogue:Start()
self:_OnSuccess()
end
--------------------------------------------------------------------------------
function UseDialogue:_AppendInteraction(interaction)
interaction:SetSuccessCallback(function() self:_OnSuccess() end)
interaction:SetFailureCallback(function() self._on_failure() end)
table.insert(self._interactions, interaction)
end
--------------------------------------------------------------------------------
function UseDialogue:_OnSuccess()
self._idx = self._idx + 1
local option = self._menu:OptionFor(self._item_id)
local menu_id = self._menu:Id()
local next = self._interactions[self._idx]
local data = { target = self._target, menu = menu_id, choice = option.option,
automated = option.automated, uk1 = option.uk1, player = self._player,
item_id = self._item_id }
next(data)
end
return UseDialogue | 412 | 0.783647 | 1 | 0.783647 | game-dev | MEDIA | 0.781343 | game-dev | 0.751349 | 1 | 0.751349 |
Dark-Basic-Software-Limited/Dark-Basic-Pro | 2,763 | SDK/BULLET/bullet-2.81-rev2613/src/BulletCollision/NarrowPhaseCollision/btRaycastCallback.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_RAYCAST_TRI_CALLBACK_H
#define BT_RAYCAST_TRI_CALLBACK_H
#include "BulletCollision/CollisionShapes/btTriangleCallback.h"
#include "LinearMath/btTransform.h"
struct btBroadphaseProxy;
class btConvexShape;
class btTriangleRaycastCallback: public btTriangleCallback
{
public:
//input
btVector3 m_from;
btVector3 m_to;
//@BP Mod - allow backface filtering and unflipped normals
enum EFlags
{
kF_None = 0,
kF_FilterBackfaces = 1 << 0,
kF_KeepUnflippedNormal = 1 << 1, // Prevents returned face normal getting flipped when a ray hits a back-facing triangle
kF_Terminator = 0xFFFFFFFF
};
unsigned int m_flags;
btScalar m_hitFraction;
btTriangleRaycastCallback(const btVector3& from,const btVector3& to, unsigned int flags=0);
virtual void processTriangle(btVector3* triangle, int partId, int triangleIndex);
virtual btScalar reportHit(const btVector3& hitNormalLocal, btScalar hitFraction, int partId, int triangleIndex ) = 0;
};
class btTriangleConvexcastCallback : public btTriangleCallback
{
public:
const btConvexShape* m_convexShape;
btTransform m_convexShapeFrom;
btTransform m_convexShapeTo;
btTransform m_triangleToWorld;
btScalar m_hitFraction;
btScalar m_triangleCollisionMargin;
btScalar m_allowedPenetration;
btTriangleConvexcastCallback (const btConvexShape* convexShape, const btTransform& convexShapeFrom, const btTransform& convexShapeTo, const btTransform& triangleToWorld, const btScalar triangleCollisionMargin);
virtual void processTriangle (btVector3* triangle, int partId, int triangleIndex);
virtual btScalar reportHit (const btVector3& hitNormalLocal, const btVector3& hitPointLocal, btScalar hitFraction, int partId, int triangleIndex) = 0;
};
#endif //BT_RAYCAST_TRI_CALLBACK_H
| 412 | 0.900297 | 1 | 0.900297 | game-dev | MEDIA | 0.9946 | game-dev | 0.960323 | 1 | 0.960323 |
Pico-Developer/PICO-Unreal-Integration-SDK | 2,295 | UE_4.27/Plugins/PICOXR/Source/PICOXRMotionTracking/Public/PXR_EyeTrackingComponent.h | // Copyright® 2015-2023 PICO Technology Co., Ltd. All rights reserved.
// This plugin incorporates portions of the Unreal® Engine. Unreal® is a trademark or registered trademark of Epic Games, Inc. in the United States of America and elsewhere.
// Unreal® Engine, Copyright 1998 – 2023, Epic Games, Inc. All rights reserved.
#pragma once
#include "CoreMinimal.h"
#include "Components/ActorComponent.h"
#include "Components/PoseableMeshComponent.h"
#include "PXR_MotionTrackingTypes.h"
#include "PXR_EyeTrackingComponent.generated.h"
struct FPXREyeBoneManager
{
public:
FPXREyeBoneManager()
: EyeIsMapped(false)
, MappedBoneName(NAME_None)
{
}
bool EyeIsMapped;
FName MappedBoneName;
FQuat InitialRotation;
};
UCLASS(Blueprintable, meta = (BlueprintSpawnableComponent, DisplayName = "PICO Eye Tracking Component"), ClassGroup = OculusHMD)
class PICOXRMOTIONTRACKING_API UPXR_EyeTrackingComponent : public UActorComponent
{
GENERATED_BODY()
public:
UPXR_EyeTrackingComponent();
virtual void BeginPlay() override;
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
virtual void TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
UFUNCTION(BlueprintCallable, Category = "PXR|EyeTracking")
void ResetEyeRotationValues();
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "PXR|EyeTracking")
FName ETTargetMeshComponentName;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "PXR|EyeTracking")
TMap<EPICOEye, FName> EyeToBoneMapping;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PXR|EyeTracking")
bool bUpdatePosition;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PXR|EyeTracking")
bool bUpdateRotation;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PXR|EyeTracking")
float ConfidenceThreshold;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PXR|EyeTracking")
bool bCanEyeDataInvalid;
private:
bool InitializeEyeTracking();
float WorldToMetersScale;
// Per eye, eye tracking data
TStaticArray<FPXREyeBoneManager, static_cast<uint32>(EPICOEye::COUNT)> PerEyeData;
UPROPERTY()
UPoseableMeshComponent* ETTargetMeshComponent;
static int ETComponentCount;
bool IsTracking;
FPXREyeTrackingState TrackingState;
};
| 412 | 0.827431 | 1 | 0.827431 | game-dev | MEDIA | 0.761155 | game-dev | 0.921986 | 1 | 0.921986 |
bailuk/AAT | 1,259 | aat-lib/src/main/java/ch/bailu/aat_lib/view/graph/SegmentNodePainter.java | package ch.bailu.aat_lib.view.graph;
import ch.bailu.aat_lib.gpx.GpxList;
import ch.bailu.aat_lib.gpx.GpxListWalker;
import ch.bailu.aat_lib.gpx.GpxPointNode;
import ch.bailu.aat_lib.gpx.GpxSegmentNode;
import ch.bailu.aat_lib.map.MapColor;
public class SegmentNodePainter extends GpxListWalker {
private float distance;
private final GraphPlotter plotter;
public SegmentNodePainter(GraphPlotter p, float offset) {
plotter = p;
distance = 0f - offset;
}
@Override
public boolean doList(GpxList track) {
return true;
}
@Override
public boolean doSegment(GpxSegmentNode segment) {
if (segment.getSegmentSize() > 0 && distance > 0f) {
GpxPointNode node = (GpxPointNode) segment.getFirstNode();
plotPoint(node, distance + node.getDistance());
}
distance += segment.getDistance();
return false;
}
@Override
public boolean doMarker(GpxSegmentNode marker) {
return false;
}
@Override
public void doPoint(GpxPointNode point) {}
private void plotPoint(GpxPointNode point, float distance) {
plotter.plotPoint(distance, (float) point.getAltitude(),
MapColor.NODE_NEUTRAL);
}
} | 412 | 0.789463 | 1 | 0.789463 | game-dev | MEDIA | 0.639394 | game-dev | 0.921585 | 1 | 0.921585 |
Thomvis/Construct | 6,943 | App/UnitTests/DDBCharacterDataSourceReaderTest.swift | //
// DndBeyondCharacterDataSourceReaderTest.swift
// UnitTests
//
// Created by Thomas Visser on 25/09/2019.
// Copyright © 2019 Thomas Visser. All rights reserved.
//
import Foundation
import XCTest
@testable import Construct
import Combine
import GameModels
import Dice
import Compendium
class DndBeyondCharacterDataSourceReaderTest: XCTestCase {
func testSarovin() async throws {
let dataSource = FileDataSource(path: Bundle(for: Self.self).path(forResource: "ddb_sarovin", ofType: "json")!)
let sut = DDBCharacterDataSourceReader(dataSource: dataSource)
let item = try await sut.items(realmId: CompendiumRealm.core.id).compactMap { $0.item }.first
let char = item as! Character
XCTAssertEqual(char.level, 3)
XCTAssertEqual(char.stats.name, "Sarovin a'Ryr")
XCTAssertEqual(char.stats.size, .medium)
XCTAssertEqual(char.stats.type?.input, "Aasimar")
XCTAssertEqual(char.stats.subtype, "Scourge")
XCTAssertEqual(char.stats.alignment, .lawfulNeutral)
XCTAssertEqual(char.stats.armorClass, 13)
XCTAssertEqual(char.stats.hitPointDice, 3.d(8) + 6)
XCTAssertEqual(char.stats.hitPoints, 24)
XCTAssertEqual(char.stats.movement, [.walk: 30])
XCTAssertEqual(char.stats.abilityScores, AbilityScores(strength: 10, dexterity: 13, constitution: 15, intelligence: 8, wisdom: 12, charisma: 17))
// FIXME: add other fields
}
func testRiverine() async throws {
let dataSource = FileDataSource(path: Bundle(for: Self.self).path(forResource: "ddb_riverine", ofType: "json")!)
let sut = DDBCharacterDataSourceReader(dataSource: dataSource)
let item = try await sut.items(realmId: CompendiumRealm.core.id).compactMap { $0.item }.first
let char = item as! Character
XCTAssertEqual(char.level, 3)
XCTAssertEqual(char.stats.name, "Riverine")
XCTAssertEqual(char.stats.size, .medium)
XCTAssertEqual(char.stats.type?.input, "Genasi")
XCTAssertEqual(char.stats.subtype, "Water")
XCTAssertEqual(char.stats.alignment, .neutralGood)
XCTAssertEqual(char.stats.armorClass, 15)
XCTAssertEqual(char.stats.hitPointDice, 3.d(8) + 3)
XCTAssertEqual(char.stats.hitPoints, 21)
XCTAssertEqual(char.stats.movement, [.walk: 30, .swim: 30])
XCTAssertEqual(char.stats.abilityScores, AbilityScores(strength: 10, dexterity: 14, constitution: 12, intelligence: 14, wisdom: 16, charisma: 8))
// FIXME: add other fields
}
func testMisty() async throws {
let dataSource = FileDataSource(path: Bundle(for: Self.self).path(forResource: "ddb_misty", ofType: "json")!)
let sut = DDBCharacterDataSourceReader(dataSource: dataSource)
let item = try await sut.items(realmId: CompendiumRealm.core.id).compactMap { $0.item }.first
let char = item as! Character
XCTAssertEqual(char.level, 4)
XCTAssertEqual(char.stats.name, "Misty Mountain")
XCTAssertEqual(char.stats.size, .medium)
XCTAssertEqual(char.stats.type?.input, "Tabaxi")
XCTAssertEqual(char.stats.subtype, nil)
XCTAssertEqual(char.stats.alignment, Alignment.neutralGood)
XCTAssertEqual(char.stats.armorClass, 14)
XCTAssertEqual(char.stats.hitPointDice, 4.d(8) + 4)
XCTAssertEqual(char.stats.hitPoints, 26)
XCTAssertEqual(char.stats.movement, [.walk: 30])
XCTAssertEqual(char.stats.abilityScores, AbilityScores(strength: 12, dexterity: 17, constitution: 13, intelligence: 9, wisdom: 14, charisma: 13))
// FIXME: add other fields
}
func testIshmadon() async throws {
let dataSource = FileDataSource(path: Bundle(for: Self.self).path(forResource: "ddb_ishmadon", ofType: "json")!)
let sut = DDBCharacterDataSourceReader(dataSource: dataSource)
let item = try await sut.items(realmId: CompendiumRealm.core.id).compactMap { $0.item }.first
let char = item as! Character
XCTAssertEqual(char.level, 4)
XCTAssertEqual(char.stats.name, "Ishmadon Molari")
XCTAssertEqual(char.stats.size, .medium)
XCTAssertEqual(char.stats.type?.input, "Dragonborn")
XCTAssertEqual(char.stats.subtype, nil)
XCTAssertEqual(char.stats.alignment, Alignment.chaoticGood)
XCTAssertEqual(char.stats.armorClass, 15)
XCTAssertEqual(char.stats.hitPointDice, 4.d(8) + 4)
XCTAssertEqual(char.stats.hitPoints, 25)
XCTAssertEqual(char.stats.movement, [.walk: 30])
XCTAssertEqual(char.stats.abilityScores, AbilityScores(strength: 12, dexterity: 14, constitution: 13, intelligence: 8, wisdom: 12, charisma: 17))
// FIXME: add other fields
}
func testThrall() async throws {
let dataSource = FileDataSource(path: Bundle(for: Self.self).path(forResource: "ddb_thrall", ofType: "json")!)
let sut = DDBCharacterDataSourceReader(dataSource: dataSource)
let item = try await sut.items(realmId: CompendiumRealm.core.id).compactMap { $0.item }.first
let char = item as! Character
XCTAssertEqual(char.level, 3)
XCTAssertEqual(char.stats.name, "Thrall 'Anak")
XCTAssertEqual(char.stats.size, .medium)
XCTAssertEqual(char.stats.type?.input, "Half-Orc")
XCTAssertEqual(char.stats.subtype, nil)
XCTAssertEqual(char.stats.alignment, nil)
XCTAssertEqual(char.stats.armorClass, 16)
XCTAssertEqual(char.stats.hitPointDice, 3.d(10) + 6)
XCTAssertEqual(char.stats.hitPoints, 24)
XCTAssertEqual(char.stats.movement, [.walk: 30])
XCTAssertEqual(char.stats.abilityScores, AbilityScores(strength: 17, dexterity: 14, constitution: 14, intelligence: 12, wisdom: 10, charisma: 8))
// FIXME: add other fields
}
func testBass() async throws {
let dataSource = FileDataSource(path: Bundle(for: Self.self).path(forResource: "ddb_bass", ofType: "json")!)
let sut = DDBCharacterDataSourceReader(dataSource: dataSource)
let item = try await sut.items(realmId: CompendiumRealm.core.id).compactMap { $0.item }.first
let char = item as! Character
XCTAssertEqual(char.level, 3)
XCTAssertEqual(char.stats.name, "Bass")
XCTAssertEqual(char.stats.size, .medium)
XCTAssertEqual(char.stats.type?.input, "Tiefling")
XCTAssertEqual(char.stats.subtype, nil)
XCTAssertEqual(char.stats.alignment, .chaoticNeutral)
XCTAssertEqual(char.stats.armorClass, 12)
XCTAssertEqual(char.stats.hitPointDice, 3.d(8) + 6)
XCTAssertEqual(char.stats.hitPoints, 18)
XCTAssertEqual(char.stats.movement, [.walk: 30])
XCTAssertEqual(char.stats.abilityScores, AbilityScores(strength: 8, dexterity: 13, constitution: 14, intelligence: 13, wisdom: 10, charisma: 17))
// FIXME: add other fields
}
}
| 412 | 0.756428 | 1 | 0.756428 | game-dev | MEDIA | 0.476575 | game-dev | 0.876135 | 1 | 0.876135 |
moneymod/moneymod | 3,697 | src/main/java/wtf/moneymod/client/impl/module/misc/AutoEz.java | package wtf.moneymod.client.impl.module.misc;
import com.mojang.realmsclient.gui.ChatFormatting;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.network.play.server.SPacketChat;
import wtf.moneymod.client.api.events.PacketEvent;
import wtf.moneymod.client.api.management.impl.FriendManagement;
import wtf.moneymod.client.api.setting.annotatable.Bounds;
import wtf.moneymod.client.api.setting.annotatable.Value;
import wtf.moneymod.client.impl.module.Module;
import wtf.moneymod.client.impl.utility.impl.misc.Timer;
import wtf.moneymod.client.impl.utility.impl.world.ChatUtil;
import wtf.moneymod.eventhandler.listener.Handler;
import wtf.moneymod.eventhandler.listener.Listener;
import java.util.Random;
@Module.Register( label = "AutoEz", desc = "Types ez in the chat after kill", cat = Module.Category.MISC )
public class AutoEz extends Module
{
private static EntityPlayer target;
String[] message = new String[]{ "Wow he died so fast lmfao", "rekt", "LOL AHAHHA NICE IQ", "THE STATE", "MONEYMODLESS AHAHAHAHAH", "Iq issue retard" };
String ezMessage = "Good Game! My Dick is Stuck In Car Exhaust Pipe It Hurts. Thanks To MoneyMod+3";
int kilStreak;
public static void setTarget( EntityPlayer player ) { target = player; }
@Value( "Helping!!!" ) public boolean prikol = true;
@Value( "KillStreak" ) public boolean killStreak = true;
@Value( "RandomHack" ) public boolean randomHack = false;
@Value( "Helping Delay" ) @Bounds( min = 0.1f, max = 10f ) public float pDelay = 1.f;
private Timer timer = new Timer( );
String[] randomHackMessage = new String[]{
"is a noob hahaha fobus on tope",
"Good fight! Konas owns me and all",
"I guess konas ca is too fast for you",
"you just got nae nae'd by konas",
"I was AFK!",
"you just got nae nae'd by wurst+",
};
@Override protected void onEnable( ) {
timer.reset( );
kilStreak = 0;
}
@Override protected void onDisable( ) {
timer.reset( );
kilStreak = 0;
}
@Override public void onTick( ) {
if (target != null && mc.player.getDistanceSq(target) < 150) {
if (target.isDead || target.getHealth() <= 0) {
mc.player.sendChatMessage((!randomHack ? "> " + target.getName() + " " + ezMessage + " [$]" : randomHackMessage[ new Random( ).nextInt( randomHackMessage.length ) ] ));
kilStreak+=1;
if (killStreak)
ChatUtil.INSTANCE.sendMessage(String.format("%s[%sKillStreak%s] %s kills!", ChatFormatting.YELLOW, ChatFormatting.GOLD,ChatFormatting.YELLOW, kilStreak));
}
target = null;
}
}
@Handler
public Listener< PacketEvent.Receive > onReceivePacket = new Listener< >( PacketEvent.Receive.class, event ->
{
if ( event.getPacket( ) instanceof SPacketChat ) {
String text;
final SPacketChat packet = (SPacketChat) event.getPacket( );
text = packet.getChatComponent( ).getFormattedText( );
if ( prikol ) {
for ( String name : FriendManagement.getInstance( ) ) {
if ( text.contains( String.format( "<%s>", name ) ) && text.toLowerCase( ).contains( "[$]" ) ) {
if ( timer.passed( ( long ) ( pDelay * 1000L ) ) ) {
mc.player.sendChatMessage( "> " + message[ new Random( ).nextInt( message.length ) ] );
timer.reset( );
break;
}
}
}
}
}
} );
}
| 412 | 0.883077 | 1 | 0.883077 | game-dev | MEDIA | 0.86741 | game-dev | 0.974824 | 1 | 0.974824 |
pathea-games/planetexplorers | 3,258 | Assets/PeLauncher/PeLauncher.cs | using UnityEngine;
using System.Collections.Generic;
using System.Collections;
namespace Pathea
{
public class PeLauncher : MonoBehaviour
{
static PeLauncher instance;
public static PeLauncher Instance
{
get
{
if (null == instance)
{
instance = new GameObject("PeLauncher").AddComponent<PeLauncher>();
}
return instance;
}
}
class LaunchInfo
{
public LaunchInfo(float time, ILaunchable target)
{
mTime = time;
mTarget = target;
}
public float mTime;
public ILaunchable mTarget;
}
List<LaunchInfo> mList = new List<LaunchInfo>(10);
EndLaunch mEndLaunch = null;
void UpdateIndicator(float percent, string info)
{
Debug.Log(info + ", progress:" + percent);
UILoadScenceEffect.Instance.SetProgress((int)(100 * percent));
}
public bool isLoading = false;
IEnumerator Load()
{
float curTime = 0f;
float totalTime = 0f;
mList.ForEach(delegate(LaunchInfo launch)
{
totalTime += launch.mTime;
});
foreach (LaunchInfo launch in mList)
{
launch.mTarget.Launch();
curTime += launch.mTime;
UpdateIndicator(curTime / totalTime, launch.mTarget.GetType().ToString());
yield return 0;
}
isLoading = false;
while (true)
{
if (null == mEndLaunch || mEndLaunch())
{
break;
}
//Debug.Log("wait 1s to end launch");
yield return new WaitForSeconds(1f);
}
endLaunch = null;
yield return new WaitForSeconds(3f);
Destroy(gameObject);
UILoadScenceEffect.Instance.EnableProgress(false);
UILoadScenceEffect.Instance.BeginScence(null);
eventor.Dispatch(new LoadFinishedArg());
FastTravel.bTraveling = false;
}
#region public
public class LoadFinishedArg : PeEvent.EventArg
{
}
PeEvent.Event<LoadFinishedArg> mEventor = new PeEvent.Event<LoadFinishedArg>();
public PeEvent.Event<LoadFinishedArg> eventor
{
get
{
return mEventor;
}
}
public delegate bool EndLaunch();
public EndLaunch endLaunch
{
get
{
return mEndLaunch;
}
set
{
mEndLaunch = value;
}
}
public interface ILaunchable
{
void Launch();
}
public void Add(ILaunchable target, float time = 1f)
{
mList.Add(new LaunchInfo(time, target));
}
public void StartLoad()
{
isLoading = true;
UILoadScenceEffect.Instance.EnableProgress(true);
StartCoroutine(Load());
}
#endregion
}
} | 412 | 0.850553 | 1 | 0.850553 | game-dev | MEDIA | 0.723939 | game-dev | 0.978455 | 1 | 0.978455 |
Kengxxiao/Punishing_GrayRaven_Tab | 6,429 | lua/xui/xuiset/XUiPanelOtherSet.lua | XUiPanelOtherSet = XClass()
local XUiSafeAreaAdapter = CS.XUiSafeAreaAdapter
local SetConfigs = XSetConfigs
local SetManager
local MaxOff
function XUiPanelOtherSet:Ctor(ui, parent)
self.GameObject = ui.gameObject
self.Transform = ui.transform
self.Parent = parent
SetManager = XDataCenter.SetManager
MaxOff = CS.XGame.ClientConfig:GetFloat("SpecialScreenOff")
XTool.InitUiObject(self)
self:InitUi()
end
function XUiPanelOtherSet:InitUi()
self.TabObs = {}
self.TabObs[1] = self.TogGraphics_0
self.TabObs[2] = self.TogGraphics_1
self.TabObs[3] = self.TogGraphics_2
self.TabObs[4] = self.TogGraphics_3
self.TGroupResolution:Init(
self.TabObs,
function(tab)
self:TabSkip(tab)
end
)
local focusTypes = {}
focusTypes[1] = self.TogType1
focusTypes[2] = self.TogType2
self.TGroupFocusType:Init(
focusTypes,
function(index)
self:OnFocusTypeChanged(index)
end
)
self.TxtType1.text = CS.XGame.ClientConfig:GetString("FocusType1")
self.TxtType2.text = CS.XGame.ClientConfig:GetString("FocusType2")
self:AddListener()
end
function XUiPanelOtherSet:AddListener()
self.OnSliderValueCb = function(value)
self:OnSliderValueChanged(value)
end
self.OnTogFriEffectsValueCb = function(value)
self:OnTogFriEffectsValueChanged(value)
end
self.OnTogFriNumValueCb = function(value)
self:OnTogFriNumValueChanged(value)
end
self.Slider.onValueChanged:AddListener(self.OnSliderValueCb)
self.TogFriEffects.onValueChanged:AddListener(self.OnTogFriEffectsValueCb)
self.TogFriNum.onValueChanged:AddListener(self.OnTogFriNumValueCb)
end
function XUiPanelOtherSet:Getcache()
self.SelfNumState = XSaveTool.GetData(SetConfigs.SelfNum) or SetConfigs.SelfNumEnum.Middle
self.FriendNumState = XSaveTool.GetData(SetConfigs.FriendNum) or SetConfigs.FriendNumEnum.Close
self.FriendEffectEnumState = XSaveTool.GetData(SetConfigs.FriendEffect) or SetConfigs.FriendEffectEnum.Open
self.ScreenOffValue = XSaveTool.GetData(XSetConfigs.ScreenOff) or 0
self.TGroupResolution:SelectIndex(self.SelfNumState)
self.TogFriEffects.isOn = self.FriendEffectEnumState == SetConfigs.FriendNumEnum.Open
self.TogFriNum.isOn = self.FriendNumState == SetConfigs.FriendNumEnum.Open
local v = tonumber(self.ScreenOffValue)
self.IsFirstSlider = true
self.Slider.value = v
self.SaveSelfNumState = self.SelfNumState
self.SaveFriendNumState = self.FriendNumState
self.SaveFriendEffectEnumState = self.FriendEffectEnumState
self.SaveScreenOffValue = self.ScreenOffValue
self.FocusType = XDataCenter.SetManager.FocusType
self.TGroupFocusType:SelectIndex(self.FocusType)
end
function XUiPanelOtherSet:TabSkip(tab)
self.CurSelfNumKey = SetConfigs.SelfNumKeyIndexConfig[tab]
self.SelfNumState = tab
if self.IsPassTab then
self.IsPassTab = false
return
end
end
function XUiPanelOtherSet:ResetToDefault()
self.SelfNumState = SetConfigs.SelfNumEnum.Middle
self.FriendNumState = SetConfigs.FriendNumEnum.Close
self.FriendEffectEnumState = SetConfigs.FriendEffectEnum.Open
self.TogFriEffects.isOn = self.FriendEffectEnumState == SetConfigs.FriendNumEnum.Open
self.TogFriNum.isOn = self.FriendNumState == SetConfigs.FriendNumEnum.Open
self.IsPassTab = true
self.TGroupResolution:SelectIndex(self.SelfNumState)
self.ScreenOffValue = 0
self.Slider.value = 0
self.FocusType = SetConfigs.DefaultFocusType
self.TGroupFocusType:SelectIndex(self.FocusType)
end
function XUiPanelOtherSet:SaveChange()
self.SaveSelfNumState = self.SelfNumState
self.SaveFriendNumState = self.FriendNumState
self.SaveFriendEffectEnumState = self.FriendEffectEnumState
self.SaveScreenOffValue = self.ScreenOffValue
SetManager.SaveSelfNum(self.SelfNumState)
SetManager.SaveFriendNum(self.FriendNumState)
SetManager.SaveFriendEffect(self.FriendEffectEnumState)
SetManager.SaveScreenOff(self.ScreenOffValue)
SetManager.SetOwnFontSizeByTab(self.SelfNumState)
SetManager.SetAllyDamage(self.FriendNumState == SetConfigs.FriendNumEnum.Open)
SetManager.SetAllyEffect(self.FriendEffectEnumState == SetConfigs.FriendEffectEnum.Open)
XDataCenter.SetManager.SetFocusType(self.FocusType)
end
function XUiPanelOtherSet:CheckDataIsChange()
return self.SaveSelfNumState ~= self.SelfNumState or self.SaveFriendNumState ~= self.FriendNumState or
self.SaveFriendEffectEnumState ~= self.FriendEffectEnumState or
self.SaveScreenOffValue ~= self.ScreenOffValue or
self.FocusType ~= XDataCenter.SetManager.FocusType
end
function XUiPanelOtherSet:CancelChange(...)
self.ScreenOffValue = self.SaveScreenOffValue
self:SetSliderValueChanged(self.SaveScreenOffValue)
end
function XUiPanelOtherSet:OnSliderValueChanged(value)
if value < 0 then
return
end
if self.IsFirstSlider then
self.IsFirstSlider = false
return
end
self.ScreenOffValue = value
self:SetSliderValueChanged(value)
SetManager.SetAdaptorScreenChange()
end
function XUiPanelOtherSet:SetSliderValueChanged(value)
local value = tonumber(value)
XUiSafeAreaAdapter.SetSpecialScreenOff(value * MaxOff)
if self.Parent then
self.Parent:UpdateSpecialScreenOff()
end
end
function XUiPanelOtherSet:OnTogFriEffectsValueChanged(value)
local v = SetConfigs.FriendEffectEnum.Close
if value then
v = SetConfigs.FriendEffectEnum.Open
end
self.FriendEffectEnumState = v
end
function XUiPanelOtherSet:OnTogFriNumValueChanged(value)
local v = SetConfigs.FriendNumEnum.Close
if value then
v = SetConfigs.FriendNumEnum.Open
end
self.FriendNumState = v
end
function XUiPanelOtherSet:OnFocusTypeChanged(index)
if index == 0 then
return
end
self.FocusType = index
self.DescriptionType1.gameObject:SetActive(index == 1)
self.DescriptionType2.gameObject:SetActive(index == 2)
end
function XUiPanelOtherSet:ShowPanel()
self.GameObject:SetActive(true)
if self.Parent then
self.Adaptation.gameObject:SetActiveEx(not self.Parent.IsFight)
end
self:Getcache()
self.IsShow = true
end
function XUiPanelOtherSet:HidePanel()
self.IsShow = false
self.GameObject:SetActive(false)
end
| 412 | 0.828906 | 1 | 0.828906 | game-dev | MEDIA | 0.925458 | game-dev | 0.920463 | 1 | 0.920463 |
davedelong/Syzygy | 4,065 | SyzygyRuntime/Objective-C/property.m | //
// property.m
// SyzygyRuntime
//
// Created by Dave DeLong on 7/12/18.
// Copyright © 2018 Syzygy. All rights reserved.
//
#import "property.h"
void property_enumerateAttributes(objc_property_t p, void(^iterator)(const char *name, const char *value, BOOL *stop)) {
unsigned int count;
objc_property_attribute_t *attrs = property_copyAttributeList(p, &count);
BOOL stop = NO;
for (unsigned int i = 0; i < count && !stop; ++i) {
iterator(attrs[i].name, attrs[i].value, &stop);
}
free(attrs);
}
SEL property_getGetterName(objc_property_t p) {
SEL s = NULL;
char *customGetter = property_copyAttributeValue(p, "G");
if (customGetter != NULL) {
s = sel_registerName(customGetter);
free(customGetter);
}
if (s == NULL) {
s = sel_registerName(property_getName(p));
}
return s;
}
SEL property_getSetterName(objc_property_t p) {
SEL s = NULL;
// see if the property is readonly.
if (property_isReadonly(p) == NO) {
// not readonly; see if there's a custom setter
char *customSetter = property_copyAttributeValue(p, "S");
if (customSetter != NULL) {
s = sel_registerName(customSetter);
free(customSetter);
}
if (s == NULL) {
// no custom setter; derive setter from property name
NSMutableString *name = [NSMutableString string];
const char *pname = property_getName(p);
while (*pname == '_') {
[name appendString:@"_"];
pname++;
}
[name appendFormat:@"set%c%s:", toupper(*pname), pname+1];
s = sel_registerName([name UTF8String]);
}
}
return s;
}
objc_AssociationPolicy property_getAssociationPolicy(objc_property_t p) {
objc_AssociationPolicy policy = OBJC_ASSOCIATION_ASSIGN;
BOOL isNonatomic = NO;
char *nonatomic = property_copyAttributeValue(p, "N");
if (nonatomic != NULL) {
isNonatomic = YES;
free(nonatomic);
}
char *copy = property_copyAttributeValue(p, "C");
if (copy != NULL) {
policy = isNonatomic ? OBJC_ASSOCIATION_COPY_NONATOMIC : OBJC_ASSOCIATION_COPY;
free(copy);
} else {
char *strong = property_copyAttributeValue(p, "&");
if (strong != NULL) {
policy = isNonatomic ? OBJC_ASSOCIATION_RETAIN_NONATOMIC : OBJC_ASSOCIATION_RETAIN;
free(strong);
}
}
return policy;
}
BOOL property_isDynamic(objc_property_t p) {
BOOL isDynamic = NO;
char *dynamic = property_copyAttributeValue(p, "D");
if (dynamic != NULL) {
isDynamic = YES;
free(dynamic);
}
return isDynamic;
}
BOOL property_isWeak(objc_property_t p) {
BOOL isWeak = NO;
if (property_getAssociationPolicy(p) == OBJC_ASSOCIATION_ASSIGN) {
char *weak = property_copyAttributeValue(p, "W");
if (weak) {
isWeak = YES;
free(weak);
}
}
return isWeak;
}
BOOL property_isReadonly(objc_property_t p) {
BOOL isReadonly = NO;
char *readonly = property_copyAttributeValue(p, "R");
if (readonly != NULL) {
isReadonly = YES;
free(readonly);
}
return isReadonly;
}
Class property_getObjectClass(objc_property_t p) {
char *type = property_copyAttributeValue(p, "T");
if (type) {
unsigned long len = strlen(type);
if (type[0] == _C_ID && len > 3) {
// it's an object type with name embedded
NSString *class = [[NSString alloc] initWithBytes:type+2 length:len-3 encoding:NSASCIIStringEncoding];
Class klass = NSClassFromString(class);
if (klass != nil) {
free(type);
return klass;
}
}
if (type[0] == _C_ID || type[0] == _C_CLASS) {
free(type);
return [NSObject class];
}
free(type);
}
return nil;
}
| 412 | 0.903417 | 1 | 0.903417 | game-dev | MEDIA | 0.203246 | game-dev | 0.981717 | 1 | 0.981717 |
spessasus/spessasynth_core | 6,843 | src/synthesizer/audio_engine/engine_methods/controller_control/data_entry/awe32.ts | import { SpessaSynthWarn } from "../../../../../utils/loggin";
import { consoleColors } from "../../../../../utils/other";
import {
type GeneratorType,
generatorTypes
} from "../../../../../soundbank/basic_soundbank/generator_types";
import type { MIDIChannel } from "../../../engine_components/midi_channel";
/**
* SoundBlaster AWE32 NRPN generator mappings.
* http://archive.gamedev.net/archive/reference/articles/article445.html
* https://github.com/user-attachments/files/15757220/adip301.pdf
*/
const AWE_NRPN_GENERATOR_MAPPINGS: GeneratorType[] = [
generatorTypes.delayModLFO,
generatorTypes.freqModLFO,
generatorTypes.delayVibLFO,
generatorTypes.freqVibLFO,
generatorTypes.delayModEnv,
generatorTypes.attackModEnv,
generatorTypes.holdModEnv,
generatorTypes.decayModEnv,
generatorTypes.sustainModEnv,
generatorTypes.releaseModEnv,
generatorTypes.delayVolEnv,
generatorTypes.attackVolEnv,
generatorTypes.holdVolEnv,
generatorTypes.decayVolEnv,
generatorTypes.sustainVolEnv,
generatorTypes.releaseVolEnv,
generatorTypes.fineTune,
generatorTypes.modLfoToPitch,
generatorTypes.vibLfoToPitch,
generatorTypes.modEnvToPitch,
generatorTypes.modLfoToVolume,
generatorTypes.initialFilterFc,
generatorTypes.initialFilterQ,
generatorTypes.modLfoToFilterFc,
generatorTypes.modEnvToFilterFc,
generatorTypes.chorusEffectsSend,
generatorTypes.reverbEffectsSend
] as const;
/**
* Function that emulates AWE32 similarly to fluidsynth
* https://github.com/FluidSynth/fluidsynth/wiki/FluidFeatures
*
* Note: This makes use of findings by mrbumpy409:
* https://github.com/fluidSynth/fluidsynth/issues/1473
*
* The excellent test files are available here, also collected and converted by mrbumpy409:
* https://github.com/mrbumpy409/AWE32-midi-conversions
*/
export function handleAWE32NRPN(
this: MIDIChannel,
aweGen: number,
dataLSB: number,
dataMSB: number
) {
// Helper functions
const clip = (v: number, min: number, max: number) =>
Math.max(min, Math.min(max, v));
const msecToTimecents = (ms: number) =>
Math.max(-32768, 1200 * Math.log2(ms / 1000));
const hzToCents = (hz: number) => 6900 + 1200 * Math.log2(hz / 440);
let dataValue = (dataMSB << 7) | dataLSB;
// Center the value
// Though ranges reported as 0 to 127 only use LSB
dataValue -= 8192;
const generator = AWE_NRPN_GENERATOR_MAPPINGS[aweGen];
if (!generator) {
SpessaSynthWarn(
`Invalid AWE32 LSB: %c${aweGen}`,
consoleColors.unrecognized
);
}
let milliseconds, hertz, centibels, cents;
switch (generator) {
default:
// This should not happen
break;
// Delays
case generatorTypes.delayModLFO:
case generatorTypes.delayVibLFO:
case generatorTypes.delayVolEnv:
case generatorTypes.delayModEnv:
milliseconds = 4 * clip(dataValue, 0, 5900);
// Convert to timecents
this.setGeneratorOverride(generator, msecToTimecents(milliseconds));
break;
// Attacks
case generatorTypes.attackVolEnv:
case generatorTypes.attackModEnv:
milliseconds = clip(dataValue, 0, 5940);
// Convert to timecents
this.setGeneratorOverride(generator, msecToTimecents(milliseconds));
break;
// Holds
case generatorTypes.holdVolEnv:
case generatorTypes.holdModEnv:
milliseconds = clip(dataValue, 0, 8191);
// Convert to timecents
this.setGeneratorOverride(generator, msecToTimecents(milliseconds));
break;
// Decays and releases (share clips and units)
case generatorTypes.decayModEnv:
case generatorTypes.decayVolEnv:
case generatorTypes.releaseVolEnv:
case generatorTypes.releaseModEnv:
milliseconds = 4 * clip(dataValue, 0, 5940);
// Convert to timecents
this.setGeneratorOverride(generator, msecToTimecents(milliseconds));
break;
// Lfo frequencies
case generatorTypes.freqVibLFO:
case generatorTypes.freqModLFO:
hertz = 0.084 * dataLSB;
// Convert to abs cents
this.setGeneratorOverride(generator, hzToCents(hertz), true);
break;
// Sustains
case generatorTypes.sustainVolEnv:
case generatorTypes.sustainModEnv:
// 0.75 dB is 7.5 cB
centibels = dataLSB * 7.5;
this.setGeneratorOverride(generator, centibels);
break;
// Pitch
case generatorTypes.fineTune:
// Data is already centered
this.setGeneratorOverride(generator, dataValue, true);
break;
// Lfo to pitch
case generatorTypes.modLfoToPitch:
case generatorTypes.vibLfoToPitch:
cents = clip(dataValue, -127, 127) * 9.375;
this.setGeneratorOverride(generator, cents, true);
break;
// Env to pitch
case generatorTypes.modEnvToPitch:
cents = clip(dataValue, -127, 127) * 9.375;
this.setGeneratorOverride(generator, cents);
break;
// Mod lfo to vol
case generatorTypes.modLfoToVolume:
// 0.1875 dB is 1.875 cB
centibels = 1.875 * dataLSB;
this.setGeneratorOverride(generator, centibels, true);
break;
// Filter fc
case generatorTypes.initialFilterFc: {
// Minimum: 100 Hz -> 4335 cents
const fcCents = 4335 + 59 * dataLSB;
this.setGeneratorOverride(generator, fcCents, true);
break;
}
// Filter Q
case generatorTypes.initialFilterQ:
// Note: this uses the "modulator-ish" approach proposed by mrbumpy409
// Here https://github.com/FluidSynth/fluidsynth/issues/1473
centibels = 215 * (dataLSB / 127);
this.setGeneratorOverride(generator, centibels, true);
break;
// To filterFc
case generatorTypes.modLfoToFilterFc:
cents = clip(dataValue, -64, 63) * 56.25;
this.setGeneratorOverride(generator, cents, true);
break;
case generatorTypes.modEnvToFilterFc:
cents = clip(dataValue, -64, 63) * 56.25;
this.setGeneratorOverride(generator, cents);
break;
// Effects
case generatorTypes.chorusEffectsSend:
case generatorTypes.reverbEffectsSend:
this.setGeneratorOverride(
generator,
clip(dataValue, 0, 255) * (1000 / 255)
);
break;
}
}
| 412 | 0.560676 | 1 | 0.560676 | game-dev | MEDIA | 0.439508 | game-dev | 0.638364 | 1 | 0.638364 |
chriswhocodes/DemoFX | 1,811 | src/main/java/com/chrisnewland/demofx/measurement/Measurements.java | /*
* Copyright (c) 2015-2016 Chris Newland.
* Licensed under https://github.com/chriswhocodes/demofx/blob/master/LICENSE-BSD
*/
package com.chrisnewland.demofx.measurement;
import com.chrisnewland.demofx.DemoAnimationTimer;
public class Measurements
{
// 300s for demoFX3
private final static int INITIAL_SIZE = 300 * DemoAnimationTimer.SAMPLE_PER_SECOND;
private final Runtime RUNTIME = Runtime.getRuntime();
private final Series heapSize = new Series(INITIAL_SIZE);
private final Series heapUsed = new Series(INITIAL_SIZE);
private final Series fps = new Series(INITIAL_SIZE);
private boolean isMeasuring = true;
public void measure(long now, int framesPerSecond)
{
if (isMeasuring)
{
long heap = RUNTIME.totalMemory();
long free = RUNTIME.freeMemory();
long used = heap - free;
heapSize.add(now, heap);
heapUsed.add(now, used);
fps.add(now, framesPerSecond);
}
}
public Series getHeapSize()
{
return heapSize;
}
public Series getHeapUsed()
{
return heapUsed;
}
public Series getFps()
{
return fps;
}
public long getTotalFrameCount()
{
isMeasuring = false;
if (fps.size() > INITIAL_SIZE) {
System.out.println("Warning: too small initial size: " + INITIAL_SIZE + ", needed: " + fps.size());
}
long totalFPS = 0;
for (long currentFPS : fps.getValues())
{
totalFPS += currentFPS;
}
return totalFPS;
}
public long getDurationMillis()
{
return fps.getRangeTime().getMax();
}
public double getAverageFPS()
{
double totalFrames = getTotalFrameCount();
double duration = getDurationMillis();
double averageFPS = 0.0;
final double frameDuration = DemoAnimationTimer.UPDATE_STATS_MILLIS;
if (duration > 0L)
{
averageFPS = totalFrames / duration * frameDuration;
}
return averageFPS;
}
} | 412 | 0.636001 | 1 | 0.636001 | game-dev | MEDIA | 0.545103 | game-dev,audio-video-media | 0.867917 | 1 | 0.867917 |
jnhyatt/bevy_mod_async | 8,793 | src/async_asset.rs | use std::{
collections::HashMap,
pin::Pin,
task::{Context, Poll},
};
use bevy_asset::{AssetLoadError, AssetServer, RecursiveDependencyLoadState, UntypedAssetId};
use bevy_ecs::{
resource::Resource,
system::{Res, ResMut},
};
use futures::{FutureExt, Stream, StreamExt};
use tokio::sync::watch;
use tokio_stream::wrappers::WatchStream;
use crate::{TaskContext, WithWorld};
pub trait AsyncAssetTaskExt {
fn get_load_state(
&self,
id: impl Into<UntypedAssetId> + Send + 'static,
) -> impl Stream<Item = RecursiveDependencyLoadState>;
}
impl AsyncAssetTaskExt for TaskContext {
fn get_load_state(
&self,
id: impl Into<UntypedAssetId> + Send + 'static,
) -> impl Stream<Item = RecursiveDependencyLoadState> {
LoadStateStream::new(self.clone(), id.into())
}
}
/// Because we can't implement [PartialEq] on a foreign type, create our own trait that mirrors the interface
trait PartialEquality {
fn eq(&self, other: &Self) -> bool;
}
impl PartialEquality for AssetLoadError {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(
Self::RequestedHandleTypeMismatch {
path: l_path,
requested: l_requested,
actual_asset_name: l_actual_asset_name,
loader_name: l_loader_name,
},
Self::RequestedHandleTypeMismatch {
path: r_path,
requested: r_requested,
actual_asset_name: r_actual_asset_name,
loader_name: r_loader_name,
},
) => {
l_path == r_path
&& l_requested == r_requested
&& l_actual_asset_name == r_actual_asset_name
&& l_loader_name == r_loader_name
}
(
Self::MissingAssetLoader {
loader_name: l_loader_name,
asset_type_id: l_asset_type_id,
extension: l_extension,
asset_path: l_asset_path,
},
Self::MissingAssetLoader {
loader_name: r_loader_name,
asset_type_id: r_asset_type_id,
extension: r_extension,
asset_path: r_asset_path,
},
) => {
l_loader_name == r_loader_name
&& l_asset_type_id == r_asset_type_id
&& l_extension == r_extension
&& l_asset_path == r_asset_path
}
(
Self::MissingAssetLoaderForExtension(l0),
Self::MissingAssetLoaderForExtension(r0),
) => l0 == r0,
(Self::MissingAssetLoaderForTypeName(l0), Self::MissingAssetLoaderForTypeName(r0)) => {
l0 == r0
}
(
Self::MissingAssetLoaderForTypeIdError(l0),
Self::MissingAssetLoaderForTypeIdError(r0),
) => l0 == r0,
(Self::AssetReaderError(l0), Self::AssetReaderError(r0)) => l0 == r0,
(Self::MissingAssetSourceError(l0), Self::MissingAssetSourceError(r0)) => l0 == r0,
(
Self::MissingProcessedAssetReaderError(l0),
Self::MissingProcessedAssetReaderError(r0),
) => l0 == r0,
(
Self::DeserializeMeta {
path: l_path,
error: l_error,
},
Self::DeserializeMeta {
path: r_path,
error: r_error,
},
) => l_path == r_path && l_error == r_error,
(
Self::CannotLoadProcessedAsset { path: l_path },
Self::CannotLoadProcessedAsset { path: r_path },
) => l_path == r_path,
(
Self::CannotLoadIgnoredAsset { path: l_path },
Self::CannotLoadIgnoredAsset { path: r_path },
) => l_path == r_path,
(
Self::AssetLoaderPanic {
path: l_path,
loader_name: l_loader_name,
},
Self::AssetLoaderPanic {
path: r_path,
loader_name: r_loader_name,
},
) => l_path == r_path && l_loader_name == r_loader_name,
(Self::AssetLoaderError(l0), Self::AssetLoaderError(r0)) => {
l0.to_string() == r0.to_string()
}
(Self::AddAsyncError(l0), Self::AddAsyncError(r0)) => l0.to_string() == r0.to_string(),
(
Self::MissingLabel {
base_path: l_base_path,
label: l_label,
all_labels: l_all_labels,
},
Self::MissingLabel {
base_path: r_base_path,
label: r_label,
all_labels: r_all_labels,
},
) => l_base_path == r_base_path && l_label == r_label && l_all_labels == r_all_labels,
_ => core::mem::discriminant(self) == core::mem::discriminant(other),
}
}
}
impl PartialEquality for RecursiveDependencyLoadState {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Failed(l0), Self::Failed(r0)) => l0.eq(r0),
_ => core::mem::discriminant(self) == core::mem::discriminant(other),
}
}
}
/// Notifies interested parties of changes to asset load states. Iterates asset handles
/// registered in [`AssetSubscriptions`] and checks their load state, emitting an update to
/// all subscribers if the state has changed.
pub fn notify_asset_events(
mut subscriptions: ResMut<AssetSubscriptions>,
assets: Res<AssetServer>,
) {
let mut to_unsubscribe = Vec::new();
for (id, tx) in &subscriptions.handles {
let current = assets.recursive_dependency_load_state(*id);
if !current.eq(&tx.borrow()) {
if tx.send(current).is_err() {
// Channel is closed, unsubscribe this asset
to_unsubscribe.push(*id);
}
}
}
for id in to_unsubscribe {
subscriptions.handles.remove(&id);
}
}
/// Manages interest in assets. Maintains a [`tokio::sync::watch::Sender`] for each asset
/// handle a client has expressed interest in. [`AssetSubscriptions::subscribe_to`] is used
/// to express interest in the load state for a given asset.
#[derive(Resource)]
pub struct AssetSubscriptions {
handles: HashMap<UntypedAssetId, watch::Sender<RecursiveDependencyLoadState>>,
}
impl AssetSubscriptions {
/// Subscribe to all asset load events for an asset. The resulting channel will
/// immediately yield the current load state for the given asset, and subsequent changes
/// to the load state will generate additional change events.
pub fn subscribe_to(
&mut self,
id: UntypedAssetId,
init: RecursiveDependencyLoadState,
) -> watch::Receiver<RecursiveDependencyLoadState> {
let (tx, rx) = watch::channel(init);
self.handles.insert(id, tx);
rx
}
}
impl Default for AssetSubscriptions {
fn default() -> Self {
Self {
handles: Default::default(),
}
}
}
enum LoadStateStreamState {
AwaitingWorld(WithWorld<watch::Receiver<RecursiveDependencyLoadState>>),
HasStream(WatchStream<RecursiveDependencyLoadState>),
}
pub struct LoadStateStream {
state: LoadStateStreamState,
}
impl LoadStateStream {
pub fn new(cx: TaskContext, id: UntypedAssetId) -> Self {
let fut = cx.with_world(move |world| {
let assets = world.resource::<AssetServer>();
let init = assets.recursive_dependency_load_state(id);
world
.resource_mut::<AssetSubscriptions>()
.subscribe_to(id, init)
});
Self {
state: LoadStateStreamState::AwaitingWorld(fut),
}
}
}
impl Stream for LoadStateStream {
type Item = RecursiveDependencyLoadState;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
match &mut self.state {
LoadStateStreamState::AwaitingWorld(fut) => match fut.poll_unpin(cx) {
Poll::Ready(rx) => {
self.state = LoadStateStreamState::HasStream(WatchStream::new(rx));
self.poll_next(cx)
}
Poll::Pending => Poll::Pending,
},
LoadStateStreamState::HasStream(rx) => rx.poll_next_unpin(cx),
}
}
}
| 412 | 0.992022 | 1 | 0.992022 | game-dev | MEDIA | 0.338329 | game-dev | 0.977978 | 1 | 0.977978 |
KenYu910645/MapleStoryAutoLevelUp | 59,436 | src/legacy/mapleStoryAutoLevelUp_legacy.py | '''
Execute this script:
python mapleStoryAutoLevelUp.py --map cloud_balcony --monster brown_windup_bear,pink_windup_bear
'''
# Standard import
import time
import random
import argparse
import glob
import sys
#
import numpy as np
import cv2
# local import
from config.legacy.config_legacy import Config
from src.utils.logger import logger
from src.utils.common import find_pattern_sqdiff, draw_rectangle, screenshot, nms, load_image, get_mask
from KeyBoardController import KeyBoardController
from GameWindowCapturorSelector import GameWindowCapturor
class MapleStoryBot:
'''
MapleStoryBot
'''
def __init__(self, args):
self.cfg = Config # Configuration
self.args = args
self.status = "hunting" # 'resting', 'finding_rune', 'near_rune', 'solving_rune'
self.idx_routes = 0 # Index of route
self.hp_ratio = 1.0 # HP bar ratio
self.mp_ratio = 1.0 # MP bar ratio
self.exp_ratio = 1.0 # EXP bar ratio
self.monster_info = [] # monster information
self.fps = 0 # Frame per second
self.is_first_frame = True # Disable cached location for first frame
self.rune_detect_level = 0
# Coordinate (top-left coordinate)
self.loc_nametag = (0, 0) # nametag location on window
self.loc_camera = (0, 0) # camera location on map
self.loc_watch_dog = (0, 0) # watch dog
self.loc_player_global = (0, 0) # player location on map
self.loc_player = (0, 0) # player location on window
self.loc_player_minimap = (0, 0) # Player's location on minimap
self.loc_minimap = (0, 0)
# Images
self.frame = None # raw image
self.img_frame = None # game window frame
self.img_frame_gray = None # game window frame graysale
self.img_frame_debug = None
self.img_route = None # route map
self.img_route_debug = None
# Timers
self.t_last_frame = time.time() # Last frame timer, for fps calculation
self.t_last_switch_status = time.time() # Last status switches timer
self.t_watch_dog = time.time() # Last movement timer
self.t_last_teleport = time.time() # Last teleport timer
self.t_patrol_last_attack = time.time() # Last patrol attack timer
self.t_last_camera_missed = time.time() # Last camera loc missed
# Patrol mode
self.is_patrol_to_left = True
self.patrol_turn_point_cnt = 0
self.img_frame_gray_last = None
# Set status to hunting for start
self.switch_status("hunting")
map_dir = "minimaps" if self.cfg.is_use_minimap else "maps"
if args.patrol:
# Patrol mode doesn't need map or route
self.img_map = None
self.img_routes = []
self.img_route_rest = None
else:
# Load map for camera localization
if self.cfg.is_use_minimap:
self.img_map = load_image(f"{map_dir}/{args.map}/map.png",
cv2.IMREAD_COLOR)
else:
self.img_map = load_image(f"{map_dir}/{args.map}/map.png",
cv2.IMREAD_GRAYSCALE)
self.img_map_resized = cv2.resize(
self.img_map, (0, 0),
fx=self.cfg.localize_downscale_factor,
fy=self.cfg.localize_downscale_factor)
# Load route*.png images
route_files = sorted(glob.glob(f"{map_dir}/{args.map}/route*.png"))
route_files = [p for p in route_files if not p.endswith("route_rest.png")]
self.img_routes = [
cv2.cvtColor(load_image(p), cv2.COLOR_BGR2RGB) for p in route_files
]
# Load rest route
self.img_route_rest = cv2.cvtColor(
load_image(f"{map_dir}/{args.map}/route_rest.png"), cv2.COLOR_BGR2RGB)
# Upscale minimap route map for better debug visualization
if self.cfg.is_use_minimap:
img_routes_resized = []
for img_route in self.img_routes:
img_routes_resized.append(cv2.resize(
img_route, (0, 0),
fx=self.cfg.minimap_upscale_factor,
fy=self.cfg.minimap_upscale_factor,
interpolation=cv2.INTER_NEAREST))
self.img_routes = img_routes_resized
self.img_route_rest = cv2.resize(
self.img_route_rest, (0, 0),
fx=self.cfg.minimap_upscale_factor,
fy=self.cfg.minimap_upscale_factor,
interpolation=cv2.INTER_NEAREST)
# Load other images
self.img_nametag = load_image("name_tag.png")
self.img_nametag_gray = load_image("name_tag.png", cv2.IMREAD_GRAYSCALE)
self.img_rune_warning = load_image("rune/rune_warning.png", cv2.IMREAD_GRAYSCALE)
self.img_rune = load_image("rune/rune.png")
self.img_rune_gray = load_image("rune/rune.png", cv2.IMREAD_GRAYSCALE)
self.img_arrows = {
"left":
[load_image("rune/arrow_left_1.png"),
load_image("rune/arrow_left_2.png"),
load_image("rune/arrow_left_3.png"),],
"right":
[load_image("rune/arrow_right_1.png"),
load_image("rune/arrow_right_2.png"),
load_image("rune/arrow_right_3.png"),],
"up":
[load_image("rune/arrow_up_1.png"),
load_image("rune/arrow_up_2.png"),
load_image("rune/arrow_up_3.png")],
"down":
[load_image("rune/arrow_down_1.png"),
load_image("rune/arrow_down_2.png"),
load_image("rune/arrow_down_3.png"),],
}
# Load monsters images from monster/{monster_name}
self.monsters = {}
for monster_name in args.monsters.split(","):
imgs = []
for file in glob.glob(f"monster/{monster_name}/{monster_name}*.png"):
# Add original image
img = load_image(file)
imgs.append((img, get_mask(img, (0, 255, 0))))
# Add flipped image
img_flip = cv2.flip(img, 1)
imgs.append((img_flip, get_mask(img_flip, (0, 255, 0))))
if imgs:
self.monsters[monster_name] = imgs
else:
logger.error(f"No images found in monster/{monster_name}/{monster_name}*")
raise RuntimeError(f"No images found in monster/{monster_name}/{monster_name}*")
logger.info(f"Loaded monsters: {list(self.monsters.keys())}")
# Start keyboard controller thread
self.kb = KeyBoardController(self.cfg, args)
if args.disable_control:
self.kb.disable()
# Start game window capturing thread
logger.info("Waiting for game window to activate, please click on game window")
self.capture = GameWindowCapturor(self.cfg)
def get_minimap_location(self):
'''
get_minimap_location
'''
loc_minimap, score, is_cached = find_pattern_sqdiff(
self.img_frame, self.img_map)
return loc_minimap
def get_player_location_on_minimap(self):
"""
Get the player's location on the minimap by detecting a unique 4-pixel color.
Return the player's location in minimap coordinates.
"""
# Crop the minimap from the game screen
x0, y0 = self.loc_minimap
h, w, _ = self.img_route.shape
img_minimap = self.img_frame[y0:y0 + h//4, x0:x0 + w//4]
# Find pixels matching the player color
mask = cv2.inRange(img_minimap,
self.cfg.minimap_player_color,
self.cfg.minimap_player_color)
coords = cv2.findNonZero(mask)
if coords is None or len(coords) < 4:
logger.warning("Fail to locate player location on minimap")
return None
# Calculate the average location of the matching pixels
avg = coords.mean(axis=0)[0] # shape (1,2), so we take [0]
loc_player_minimap = (int(round(avg[0] * self.cfg.minimap_upscale_factor)),
int(round(avg[1] * self.cfg.minimap_upscale_factor)))
# Draw red circle to mark player's location on minimap
cv2.circle(self.img_route_debug, loc_player_minimap,
radius=4, color=(0, 255, 255), thickness=2)
return loc_player_minimap
def get_nearest_color_code_on_minimap(self):
'''
get_nearest_color_code_on_minimap
'''
x0, y0 = self.loc_player_minimap
h, w = self.img_route.shape[:2]
x_min = max(0, x0 - self.cfg.minimap_color_code_search_range)
x_max = min(w, x0 + self.cfg.minimap_color_code_search_range)
y_min = max(0, y0 - self.cfg.minimap_color_code_search_range)
y_max = min(h, y0 + self.cfg.minimap_color_code_search_range)
nearest = None
min_dist = float('inf')
for y in range(y_min, y_max):
for x in range(x_min, x_max):
pixel = tuple(self.img_route[y, x]) # (R, G, B)
if pixel in self.cfg.color_code:
dist = abs(x - x0) + abs(y - y0)
if dist < min_dist:
min_dist = dist
nearest = {
"pixel": (x, y),
"color": pixel,
"action": self.cfg.color_code[pixel],
"distance": dist
}
# Debug
draw_rectangle(
self.img_route_debug,
(x_min, y_min),
(self.cfg.minimap_color_code_search_range*2,
self.cfg.minimap_color_code_search_range*2),
(0, 0, 255), "Search Range",
)
# Draw a straigt line from map_loc_player to color_code["pixel"]
if nearest is not None:
cv2.line(
self.img_route_debug,
self.loc_player_minimap, # start point
nearest["pixel"], # end point
(0, 255, 0), # green line
1 # thickness
)
# Print color code on debug image
cv2.putText(
self.img_frame_debug,
f"Route Action: {nearest['action']}",
(720, 90),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255),
2, cv2.LINE_AA
)
cv2.putText(
self.img_frame_debug, f"Route Index: {self.idx_routes}",
(720, 120),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255),
2, cv2.LINE_AA
)
return nearest # if not found return none
def switch_status(self, new_status):
'''
Switch to new status and log the transition.
Parameters:
- new_status: string, the new status to switch to.
'''
# Ignore dummy transition
if self.status == new_status:
return
t_elapsed = round(time.time() - self.t_last_switch_status)
logger.info(f"[switch_status] From {self.status}({t_elapsed} sec) to {new_status}.")
self.status = new_status
self.t_last_switch_status = time.time()
def get_nearest_monster(self, is_left = True, overlap_threshold=0.5):
'''
get_nearest_monster
'''
if is_left:
x0 = self.loc_player[0] - self.cfg.magic_claw_range_x
else:
x0 = self.loc_player[0]
y0 = self.loc_player[1] - self.cfg.magic_claw_range_y//2
x1 = x0 + self.cfg.magic_claw_range_x
y1 = y0 + self.cfg.magic_claw_range_y
# Debug, magic claw hit box
draw_rectangle(
self.img_frame_debug, (x0, y0),
(self.cfg.magic_claw_range_y, self.cfg.magic_claw_range_x),
(0, 0, 255), "Attack Box"
)
nearest_monster = None
min_distance = float('inf')
for monster in self.monster_info:
mx1, my1 = monster["position"]
mw, mh = monster["size"]
mx2 = mx1 + mw
my2 = my1 + mh
# Calculate intersection
ix1 = max(x0, mx1)
iy1 = max(y0, my1)
ix2 = min(x1, mx2)
iy2 = min(y1, my2)
iw = max(0, ix2 - ix1)
ih = max(0, iy2 - iy1)
inter_area = iw * ih
monster_area = mw * mh
if monster_area == 0:
continue # skip degenerate box
if inter_area/monster_area >= overlap_threshold:
# Compute distance to player center
monster_center = (mx1 + mw // 2, my1 + mh // 2)
dx = monster_center[0] - self.loc_player[0]
dy = monster_center[1] - self.loc_player[1]
distance = abs(dx) + abs(dy) # Manhattan distance
if distance < min_distance:
min_distance = distance
nearest_monster = monster
return nearest_monster
def solve_rune(self):
'''
Solve the rune puzzle by detecting the arrow directions and pressing corresponding keys.
'''
while self.is_in_rune_game():
for arrow_idx in [0,1,2,3]:
# Get lastest game screen frame buffer
self.frame = self.capture.get_frame()
# Resize game screen to 1296x759
self.img_frame = cv2.resize(self.frame, (1296, 759),
interpolation=cv2.INTER_NEAREST)
# Crop arrow detection box
x = self.cfg.arrow_box_start_point[0] + self.cfg.arrow_box_interval*arrow_idx
y = self.cfg.arrow_box_start_point[1]
size = self.cfg.arrow_box_size
img_roi = self.img_frame[y:y+size, x:x+size]
# Loop through all possible arrows template and choose the most possible one
best_score = float('inf')
best_direction = ""
for direction, arrow_list in self.img_arrows.items():
for img_arrow in arrow_list:
_, score, _ = find_pattern_sqdiff(
img_roi, img_arrow,
mask=get_mask(img_arrow, (0, 255, 0)))
if score < best_score:
best_score = score
best_direction = direction
logger.info(f"[solve_rune] Arrow({arrow_idx}) is {best_direction} with score({best_score})")
# Update img_frame_debug
self.img_frame_debug = self.img_frame.copy()
draw_rectangle(
self.img_frame_debug, (x, y), (size, size),
(0, 0, 255), str(round(best_score, 2))
)
# Update debug window
self.update_img_frame_debug()
cv2.waitKey(1)
# For logging
screenshot(self.img_frame_debug, "solve_rune")
# Press the key for 0.5 second
if not self.args.disable_control:
self.kb.press_key(best_direction, 0.5)
time.sleep(1)
logger.info(f"[solve_rune] Solved all arrows")
def is_player_stuck(self):
"""
Detect if the player is stuck (not moving).
If stuck for more than WATCH_DOG_TIMEOUT seconds, performs a random action.
"""
dx = abs(self.loc_player_global[0] - self.loc_watch_dog[0])
dy = abs(self.loc_player_global[1] - self.loc_watch_dog[1])
current_time = time.time()
if dx + dy > self.cfg.watch_dog_range:
# Player moved, reset watchdog timer
self.loc_watch_dog = self.loc_player_global
self.t_watch_dog = current_time
return False
dt = current_time - self.t_watch_dog
if dt > self.cfg.watch_dog_timeout:
# watch dog idle for too long, player stuck
self.loc_watch_dog = self.loc_player_global
self.t_watch_dog = current_time
logger.warning(f"[is_player_stuck] Player stuck for {dt} seconds.")
return True
return False
def is_player_stuck_minimap(self):
"""
Detect if the player is stuck (not moving).
If stuck for more than WATCH_DOG_TIMEOUT seconds, performs a random action.
"""
dx = abs(self.loc_player_minimap[0] - self.loc_watch_dog[0])
dy = abs(self.loc_player_minimap[1] - self.loc_watch_dog[1])
current_time = time.time()
if dx + dy > self.cfg.watch_dog_range:
# Player moved, reset watchdog timer
self.loc_watch_dog = self.loc_player_minimap
self.t_watch_dog = current_time
return False
dt = current_time - self.t_watch_dog
if dt > self.cfg.watch_dog_timeout:
# watch dog idle for too long, player stuck
self.loc_watch_dog = self.loc_player_minimap
self.t_watch_dog = current_time
logger.warning(f"[is_player_stuck] Player stuck for {dt} seconds.")
return True
return False
def get_nearest_color_code(self):
'''
get_nearest_color_code
'''
x0, y0 = self.loc_player_global
h, w = self.img_route.shape[:2]
x_min = max(0, x0 - self.cfg.color_code_search_range)
x_max = min(w, x0 + self.cfg.color_code_search_range)
y_min = max(0, y0 - self.cfg.color_code_search_range)
y_max = min(h, y0 + self.cfg.color_code_search_range)
nearest = None
min_dist = float('inf')
for y in range(y_min, y_max):
for x in range(x_min, x_max):
pixel = tuple(self.img_route[y, x]) # (R, G, B)
if pixel in self.cfg.color_code:
dist = abs(x - x0) + abs(y - y0)
if dist < min_dist:
min_dist = dist
nearest = {
"pixel": (x, y),
"color": pixel,
"action": self.cfg.color_code[pixel],
"distance": dist
}
# Debug
draw_rectangle(
self.img_route_debug,
(x_min, y_min),
(self.cfg.color_code_search_range*2, self.cfg.color_code_search_range*2),
(0, 0, 255), "Color Search Range"
)
# Draw a straigt line from map_loc_player to color_code["pixel"]
if nearest is not None:
cv2.line(
self.img_route_debug,
self.loc_player_global, # start point
nearest["pixel"], # end point
(0, 255, 0), # green line
1 # thickness
)
# Print color code on debug image
cv2.putText(
self.img_frame_debug,
f"Route Action: {nearest['action']}",
(720, 90),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255),
2, cv2.LINE_AA
)
cv2.putText(
self.img_frame_debug, f"Route Index: {self.idx_routes}",
(720, 120),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255),
2, cv2.LINE_AA
)
return nearest # if not found return none
def get_hp_mp_exp(self):
'''
get_hp_mp_exp
'''
# HP crop
hp_bar = self.img_frame[self.cfg.hp_bar_top_left[1]:self.cfg.hp_bar_bottom_right[1]+1,
self.cfg.hp_bar_top_left[0]:self.cfg.hp_bar_bottom_right[0]+1]
# MP crop
mp_bar = self.img_frame[self.cfg.mp_bar_top_left[1]:self.cfg.mp_bar_bottom_right[1]+1,
self.cfg.mp_bar_top_left[0]:self.cfg.mp_bar_bottom_right[0]+1]
# EXP crop
exp_bar = self.img_frame[self.cfg.exp_bar_top_left[1]:self.cfg.exp_bar_bottom_right[1]+1,
self.cfg.exp_bar_top_left[0]:self.cfg.exp_bar_bottom_right[0]+1]
# HP Detection (detect empty part)
empty_mask_hp = (hp_bar[:,:,0] == hp_bar[:,:,1]) & (hp_bar[:,:,0] == hp_bar[:,:,2])
empty_pixels_hp = np.count_nonzero(empty_mask_hp)-6 # 6 pixel always be white
total_pixels_hp = hp_bar.shape[0] * hp_bar.shape[1] - 6
hp_ratio = 1 - (empty_pixels_hp / total_pixels_hp)
# MP Detection (detect empty part)
empty_mask_mp = (mp_bar[:,:,0] == mp_bar[:,:,1]) & (mp_bar[:,:,0] == mp_bar[:,:,2])
empty_pixels_mp = np.count_nonzero(empty_mask_mp)-6 # 6 pixel always be white
total_pixels_mp = mp_bar.shape[0] * mp_bar.shape[1] - 6
mp_ratio = 1 - (empty_pixels_mp / total_pixels_mp)
# EXP Detection (detect eexpty part)
empty_mask_exp = (exp_bar[:,:,0] == exp_bar[:,:,1]) & (exp_bar[:,:,0] == exp_bar[:,:,2])
eexpty_pixels_exp = np.count_nonzero(empty_mask_exp)-6 # 6 pixel always be white
total_pixels_exp = exp_bar.shape[0] * exp_bar.shape[1] - 6
exp_ratio = 1 - (eexpty_pixels_exp / total_pixels_exp)
# Compute original bar dimensions
hp_h, hp_w = hp_bar.shape[:2]
mp_h, mp_w = mp_bar.shape[:2]
exp_h, exp_w = exp_bar.shape[:2]
# Overlay HP/MP/EXP text
x_start, y_start = (250, 90)
cv2.putText(self.img_frame_debug, f"HP: {hp_ratio*100:.1f}%", (x_start, y_start),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,0,255), 2)
cv2.putText(self.img_frame_debug, f"MP: {mp_ratio*100:.1f}%", (x_start, y_start+30),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,0,255), 2)
cv2.putText(self.img_frame_debug, f"EXP: {exp_ratio*100:.1f}%", (x_start, y_start+60),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,0,255), 2)
# Paste HP/MP/EXP bar on img_frame_debug
x_start, y_start = (410, 73)
self.img_frame_debug[y_start:y_start+hp_h, x_start:x_start+hp_w] = hp_bar
self.img_frame_debug[y_start+30:y_start+30+mp_h, x_start:x_start+mp_w] = mp_bar
self.img_frame_debug[y_start+60:y_start+60+exp_h, x_start:x_start+exp_w] = exp_bar
return hp_ratio, mp_ratio, exp_ratio
def is_rune_warning(self):
'''
is_rune_warning
'''
x0, y0 = self.cfg.rune_warning_top_left
x1, y1 = self.cfg.rune_warning_bottom_right
_, score, _ = find_pattern_sqdiff(
self.img_frame_gray[y0:y1, x0:x1],
self.img_rune_warning)
if self.status == "hunting" and score < self.cfg.rune_warning_diff_thres:
logger.info(f"[is_rune_warning] Detect rune warning on screen with score({score})")
return True
else:
return False
def is_rune_near_player(self):
'''
is_rune_near_player
'''
# Calculate bounding box
h, w = self.img_frame.shape[:2]
x0 = max(0, self.loc_player[0] - self.cfg.rune_detect_box_width // 2)
y0 = max(0, self.loc_player[1] - self.cfg.rune_detect_box_height)
x1 = min(w, self.loc_player[0] + self.cfg.rune_detect_box_width // 2)
y1 = min(h, self.loc_player[1])
# Debug
draw_rectangle(
self.img_frame_debug, (x0, y0), (y1-y0, x1-x0),
(255, 0, 0), "Rune Detection Range"
)
# Find rune icon near player
if (x1 - x0) < self.img_rune.shape[1] or \
(y1 - y0) < self.img_rune.shape[0]:
return False # Skip check if box is out of range
else:
img_roi = self.img_frame[y0:y1, x0:x1]
loc_rune, score, _ = find_pattern_sqdiff(
img_roi,
self.img_rune,
mask=get_mask(self.img_rune, (0, 255, 0)))
# # Draw rectangle for debug
# draw_rectangle(
# self.img_frame_debug,
# (x0 + loc_rune[0], y0 + loc_rune[1]),
# self.img_rune.shape,
# (255, 0, 255), # purple in BGR
# f"Rune,{round(score, 2)}"
# )
detect_thres = self.cfg.rune_detect_diff_thres + self.rune_detect_level*self.cfg.rune_detect_level_coef
if score < detect_thres:
logger.info(f"[Rune Detect] Found rune near player with score({score})," + \
f"level({self.rune_detect_level}),threshold({detect_thres})")
# Draw rectangle for debug
draw_rectangle(
self.img_frame_debug,
(x0 + loc_rune[0], y0 + loc_rune[1]),
self.img_rune.shape,
(255, 0, 255), # purple in BGR
f"Rune,{round(score, 2)}"
)
screenshot(self.img_frame_debug, "rune_detected")
return True
else:
return False
def is_in_rune_game(self):
'''
is_in_rune_game
'''
# Get lastest game screen frame buffer
self.frame = self.capture.get_frame()
# Resize game screen to 1296x759
self.img_frame = cv2.resize(self.frame, (1296, 759), interpolation=cv2.INTER_NEAREST)
# Crop arrow detection box
x, y = self.cfg.arrow_box_start_point
size = self.cfg.arrow_box_size
img_roi = self.img_frame[y:y+size, x:x+size]
# Check if arrow exist on screen
best_score = float('inf')
for direc, arrow_list in self.img_arrows.items():
for img_arrow in arrow_list:
_, score, _ = find_pattern_sqdiff(
img_roi, img_arrow,
mask=get_mask(img_arrow, (0, 255, 0)))
if score < best_score:
best_score = score
draw_rectangle(
self.img_frame_debug, (x, y), (size, size),
(0, 0, 255), str(round(best_score, 2))
)
if best_score < self.cfg.arrow_box_diff_thres:
logger.info(f"Arrow screen detected with score({score})")
return True
return False
def get_monsters_in_range(self, top_left, bottom_right):
'''
get_monsters_in_range
'''
x0, y0 = top_left
x1, y1 = bottom_right
img_roi = self.img_frame[y0:y1, x0:x1]
monster_info = []
for monster_name, monster_imgs in self.monsters.items():
for img_monster, mask_monster in monster_imgs:
if self.args.patrol:
pass # Don't detect monster using template in patrol mode
elif self.cfg.monster_detect_mode == "template_free":
# Generate mask where pixel is exactly (0,0,0)
black_mask = np.all(img_roi == [0, 0, 0], axis=2).astype(np.uint8) * 255
cv2.imshow("Black Pixel Mask", black_mask)
# Shift player's location into ROI coordinate system
px, py = self.loc_player
px_in_roi = px - x0
py_in_roi = py - y0
# Define rectangle range around player (in ROI coordinate)
char_x_min = max(0, px_in_roi - self.cfg.character_width // 2)
char_x_max = min(img_roi.shape[1], px_in_roi + self.cfg.character_width // 2)
char_y_min = max(0, py_in_roi - self.cfg.character_height // 2)
char_y_max = min(img_roi.shape[0], py_in_roi + self.cfg.character_height // 2)
# Zero out mask inside this region (ignore player's own character)
black_mask[char_y_min:char_y_max, char_x_min:char_x_max] = 0
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (20, 20))
closed_mask = cv2.morphologyEx(black_mask, cv2.MORPH_CLOSE, kernel)
# cv2.imshow("Black Mask", closed_mask)
# draw player character bounding box
draw_rectangle(
self.img_frame_debug, (char_x_min+x0, char_y_min+y0),
(self.cfg.character_height, self.cfg.character_width),
(255, 0, 0), "Character Box"
)
num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(closed_mask, connectivity=8)
monster_info = []
min_area = 1000
for i in range(1, num_labels):
x, y, w, h, area = stats[i]
if area > min_area:
monster_info.append({
"name": "",
"position": (x0+x, y0+y),
"size": (h, w),
"score": 1.0,
})
elif self.cfg.monster_detect_mode == "contour_only":
# Use only black lines contour to detect monsters
# Create masks (already grayscale)
mask_pattern = np.all(img_monster == [0, 0, 0], axis=2).astype(np.uint8) * 255
mask_roi = np.all(img_roi == [0, 0, 0], axis=2).astype(np.uint8) * 255
# Apply Gaussian blur (soften the masks)
img_monster_blur = cv2.GaussianBlur(mask_pattern, (self.cfg.blur_range, self.cfg.blur_range), 0)
img_roi_blur = cv2.GaussianBlur(mask_roi, (self.cfg.blur_range, self.cfg.blur_range), 0)
# Check template vs ROI size before matching
h_roi, w_roi = img_roi_blur.shape[:2]
h_temp, w_temp = img_monster_blur.shape[:2]
if h_temp > h_roi or w_temp > w_roi:
return [] # template bigger than roi, skip this matching
# Perform template matching
res = cv2.matchTemplate(img_roi_blur, img_monster_blur, cv2.TM_SQDIFF_NORMED)
# Apply soft threshold
match_locations = np.where(res <= self.cfg.monster_diff_thres)
h, w = img_monster.shape[:2]
for pt in zip(*match_locations[::-1]):
monster_info.append({
"name": monster_name,
"position": (pt[0] + x0, pt[1] + y0),
"size": (h, w),
"score": res[pt[1], pt[0]],
})
elif self.cfg.monster_detect_mode == "grayscale":
img_monster_gray = cv2.cvtColor(img_monster, cv2.COLOR_BGR2GRAY)
img_roi_gray = cv2.cvtColor(img_roi, cv2.COLOR_BGR2GRAY)
res = cv2.matchTemplate(
img_roi_gray,
img_monster_gray,
cv2.TM_SQDIFF_NORMED,
mask=mask_monster)
match_locations = np.where(res <= self.cfg.monster_diff_thres)
h, w = img_monster.shape[:2]
for pt in zip(*match_locations[::-1]):
monster_info.append({
"name": monster_name,
"position": (pt[0] + x0, pt[1] + y0),
"size": (h, w),
"score": res[pt[1], pt[0]],
})
elif self.cfg.monster_detect_mode == "color":
res = cv2.matchTemplate(
img_roi,
img_monster,
cv2.TM_SQDIFF_NORMED,
mask=mask_monster)
match_locations = np.where(res <= self.cfg.monster_diff_thres)
h, w = img_monster.shape[:2]
for pt in zip(*match_locations[::-1]):
monster_info.append({
"name": monster_name,
"position": (pt[0] + x0, pt[1] + y0),
"size": (h, w),
"score": res[pt[1], pt[0]],
})
else:
logger.error(f"Unexpected camera localization mode: {self.cfg.monster_detect_mode}")
return []
# Apply Non-Maximum Suppression to monster detection
monster_info = nms(monster_info, iou_threshold=0.4)
# Detect monster via health bar
if self.cfg.monster_detect_with_health_bar:
# Create color mask for Monsters' HP bar
mask = cv2.inRange(img_roi,
np.array(self.cfg.monster_health_bar_color),
np.array(self.cfg.monster_health_bar_color))
# Find connected components (each cluster of green pixels)
num_labels, labels, stats, centroids = \
cv2.connectedComponentsWithStats(mask, connectivity=8)
for i in range(1, num_labels): # skip background (label 0)
x, y, w, h, area = stats[i]
if area < 3: # small noise filter
continue
# Guess a monster bounding box
y += 10
x = max(0, x)
y = max(0, y)
w = 70
h = 70
monster_info.append({
"name": "Health Bar",
"position": (x0 + x, y0 + y),
"size": (h, w),
"score": 1.0,
})
# Debug
# Draw attack detection range
draw_rectangle(
self.img_frame_debug, (x0, y0), (y1-y0, x1-x0),
(255, 0, 0), "Monster Detection Box"
)
# Draw monsters bounding box
for monster in monster_info:
if monster["name"] == "Health Bar":
color = (0, 255, 255)
else:
color = (0, 255, 0)
draw_rectangle(
self.img_frame_debug, monster["position"], monster["size"],
color, str(round(monster['score'], 2))
)
return monster_info
def get_player_location(self):
'''
get player location by detecting player's nametag
'''
img_roi = self.img_frame_gray[self.cfg.camera_ceiling:self.cfg.camera_floor, :]
# Pad search region to avoid edge cut-off issue (full template size)
(pad_y, pad_x) = self.img_nametag.shape[:2]
img_roi_padded = cv2.copyMakeBorder(
img_roi,
pad_y, pad_y, pad_x, pad_x,
borderType=cv2.BORDER_REPLICATE # replicate border for safe matching
)
# Adjust previous location
if self.is_first_frame:
last_result = None
else:
last_result = (
self.loc_nametag[0] + pad_x,
self.loc_nametag[1] - self.cfg.camera_ceiling + pad_y
)
# Split nametag into left and right half, detect seperately and pick highest socre
# This localization method is more robust for occluded nametag
h, w = self.img_nametag_gray.shape
mask_full = get_mask(self.img_nametag, (0, 255, 0))
nametag_variants = {
"left": {
"img_pattern": self.img_nametag_gray[:, :w // 2],
"mask": mask_full[:, :w // 2],
"last_result": last_result,
"score_penalty": 0.0
},
"right": {
"img_pattern": self.img_nametag_gray[:, w // 2:],
"mask": mask_full[:, w // 2:],
"last_result": (last_result[0] + w // 2, last_result[1]) if last_result else None,
"score_penalty": 0.0
}
}
# Match template for each split nametag
matches = []
for tag_type, data in nametag_variants.items():
loc, score, is_cached = find_pattern_sqdiff(
img_roi_padded,
data["img_pattern"],
last_result=data["last_result"],
mask=data["mask"],
global_threshold=0.3
)
w_match = data["img_pattern"].shape[1]
h_match = data["img_pattern"].shape[0]
score += data["score_penalty"]
matches.append((tag_type, loc, score, w_match, h_match, is_cached))
# Choose the best match
matches.sort(key=lambda x: (not x[5], x[2]))
tag_type, loc_nametag, score, w_match, h_match, is_cached = matches[0]
if tag_type == "right":
loc_nametag = (loc_nametag[0] - w_match, loc_nametag[1])
# Convert back to original (unpadded) coordinates
loc_nametag = (
loc_nametag[0] - pad_x,
loc_nametag[1] - pad_y + self.cfg.camera_ceiling
)
# Update name tag location if confidence is good
if score < self.cfg.nametag_diff_thres:
self.loc_nametag = loc_nametag
loc_player = (
self.loc_nametag[0] - self.cfg.nametag_offset[0],
self.loc_nametag[1] - self.cfg.nametag_offset[1]
)
# Draw name tag detection box for debug
draw_rectangle(
self.img_frame_debug, self.loc_nametag, self.img_nametag.shape,
(0, 255, 0), "")
text = f"NameTag,{round(score, 2)}," + \
f"{'cached' if is_cached else 'missed'}," + \
f"{tag_type}"
cv2.putText(self.img_frame_debug, text,
(self.loc_nametag[0], self.loc_nametag[1] + self.img_nametag.shape[0] + 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
# Draw player center
cv2.circle(self.img_frame_debug,
loc_player, radius=3,
color=(0, 0, 255), thickness=-1)
return loc_player
def get_player_location_global(self):
'''
get_player_location_global
'''
scale_factor = self.cfg.localize_downscale_factor
# Downscale both template and search image
img_roi = self.img_frame_gray[self.cfg.camera_ceiling:self.cfg.camera_floor, :]
img_query = cv2.resize(img_roi, (0, 0), fx=scale_factor, fy=scale_factor)
# Get previous frame result
if self.is_first_frame or \
time.time() - self.t_last_camera_missed > self.cfg.localize_cached_interval:
last_result = None
self.t_last_camera_missed = time.time()
else:
last_result = (
int(self.loc_camera[0] * scale_factor),
int(self.loc_camera[1] * scale_factor)
)
loc_camera, score, is_cached = find_pattern_sqdiff(
self.img_map_resized,
img_query,
last_result=last_result,
local_search_radius=20,
global_threshold = 0.8)
self.loc_camera = (
int(loc_camera[0] / scale_factor),
int(loc_camera[1] / scale_factor)
)
loc_player_global = (
self.loc_camera[0] + self.loc_player[0],
self.loc_camera[1] + self.loc_player[1] - self.cfg.camera_ceiling)
# Draw camera rectangle
camera_bottom_right = (
self.loc_camera[0] + self.img_frame.shape[1],
self.loc_camera[1] + self.img_frame.shape[0]
)
cv2.rectangle(self.img_route_debug, self.loc_camera,
camera_bottom_right, (0, 255, 255), 2)
cv2.putText(
self.img_route_debug,
f"Camera, score={round(score, 2)}, {'cached' if is_cached else 'missed'}",
(self.loc_camera[0], self.loc_camera[1] + 60),
cv2.FONT_HERSHEY_SIMPLEX, 2,
(0, 255, 0), 2
)
# Draw player center
cv2.circle(self.img_route_debug,
loc_player_global, radius=3,
color=(0, 0, 255), thickness=-1)
cv2.putText(self.img_route_debug, "Player",
(loc_player_global[0] - 30, loc_player_global[1] - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
return loc_player_global
def is_near_edge(self):
'''
is_near_edge
'''
if self.cfg.is_use_minimap:
x0, y0 = self.loc_player_minimap
h, w = self.img_route.shape[:2]
x_min = max(0, x0 - self.cfg.edge_teleport_minimap_box_width//2)
x_max = min(w, x0 + self.cfg.edge_teleport_minimap_box_width//2)
y_min = max(0, y0 - self.cfg.edge_teleport_minimap_box_height//2)
y_max = min(h, y0 + self.cfg.edge_teleport_minimap_box_height//2)
else:
x0, y0 = self.loc_player_global
h, w = self.img_route.shape[:2]
x_min = max(0, x0 - self.cfg.edge_teleport_box_width//2)
x_max = min(w, x0 + self.cfg.edge_teleport_box_width//2)
y_min = max(0, y0 - self.cfg.edge_teleport_box_height//2)
y_max = min(h, y0 + self.cfg.edge_teleport_box_height//2)
# Debug: draw search box
draw_rectangle(
self.img_route_debug,
(x_min, y_min),
(y_max - y_min, x_max - x_min),
(0, 0, 255), "Edge Check"
)
# Find mask of matching pixels
roi = self.img_route[y_min:y_max, x_min:x_max]
mask = np.all(roi == self.cfg.edge_teleport_color_code, axis=2)
coords = np.column_stack(np.where(mask))
# No edge pixel
if coords.size == 0:
return ""
# Calculate mean position of matching pixels
mean_x = np.mean(coords[:, 1])
# Compare to roi center
if mean_x < x0:
return "edge on left"
else:
return "edge on right"
def get_random_action(self):
'''
get_random_action
'''
action = random.choice(list(self.cfg.color_code.values()))
logger.warning(f"Perform random action: {action}")
return action
def update_info_on_img_frame_debug(self):
'''
update_info_on_img_frame_debug
'''
# Print text at bottom left corner
self.fps = round(1.0 / (time.time() - self.t_last_frame))
text_y_interval = 23
text_y_start = 550
dt_screenshot = time.time() - self.kb.t_last_screenshot
text_list = [
f"FPS: {self.fps}",
f"Status: {self.status}",
f"Press 'F1' to {'pause' if self.kb.is_enable else 'start'} Bot",
f"Press 'F2' to save screenshot{' : Saved' if dt_screenshot < 0.7 else ''}"
]
for idx, text in enumerate(text_list):
cv2.putText(
self.img_frame_debug, text,
(10, text_y_start + text_y_interval*idx),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255),
2, cv2.LINE_AA
)
# Don't draw minimap in patrol mode
if self.args.patrol:
return
# mini-map on debug image
if self.cfg.is_use_minimap:
# Compute crop region with boundary check
crop_w, crop_h = 300, 300
x0 = max(0, self.loc_player_minimap[0] - crop_w // 2)
y0 = max(0, self.loc_player_minimap[1] - crop_h // 2)
x1 = min(self.img_route_debug.shape[1], x0 + crop_w)
y1 = min(self.img_route_debug.shape[0], y0 + crop_h)
# Crop region
mini_map_crop = self.img_route_debug[y0:y1, x0:x1]
mini_map_crop = cv2.resize(mini_map_crop,
(int(mini_map_crop.shape[1] // 1.5),
int(mini_map_crop.shape[0] // 1.5)),
interpolation=cv2.INTER_NEAREST)
# Paste into top-right corner of self.img_frame_debug
h_crop, w_crop = mini_map_crop.shape[:2]
h_frame, w_frame = self.img_frame_debug.shape[:2]
x_paste = w_frame - w_crop - 10 # 10px margin from right
y_paste = 70
self.img_frame_debug[y_paste:y_paste + h_crop, x_paste:x_paste + w_crop] = mini_map_crop
# Draw border around minimap
cv2.rectangle(
self.img_frame_debug,
(x_paste, y_paste),
(x_paste + w_crop, y_paste + h_crop),
color=(255, 255, 255), # White border
thickness=2
)
else:
# Compute crop region with boundary check
crop_w, crop_h = 400, 400
x0 = max(0, self.loc_player_global[0] - crop_w // 2)
y0 = max(0, self.loc_player_global[1] - crop_h // 2)
x1 = min(self.img_route_debug.shape[1], x0 + crop_w)
y1 = min(self.img_route_debug.shape[0], y0 + crop_h)
# Crop region
mini_map_crop = self.img_route_debug[y0:y1, x0:x1]
mini_map_crop = cv2.resize(mini_map_crop,
(mini_map_crop.shape[1] // 2, mini_map_crop.shape[0] // 2),
interpolation=cv2.INTER_NEAREST)
# Paste into top-right corner of self.img_frame_debug
h_crop, w_crop = mini_map_crop.shape[:2]
h_frame, w_frame = self.img_frame_debug.shape[:2]
x_paste = w_frame - w_crop - 10 # 10px margin from right
y_paste = 70
self.img_frame_debug[y_paste:y_paste + h_crop, x_paste:x_paste + w_crop] = mini_map_crop
# Draw border around minimap
cv2.rectangle(
self.img_frame_debug,
(x_paste, y_paste),
(x_paste + w_crop, y_paste + h_crop),
color=(255, 255, 255), # White border
thickness=2
)
def update_img_frame_debug(self):
'''
update_img_frame_debug
'''
cv2.imshow("Game Window Debug",
self.img_frame_debug[self.cfg.camera_ceiling:self.cfg.camera_floor, :])
# Update FPS timer
self.t_last_frame = time.time()
def run_once(self):
'''
Process with one game window frame
'''
# Get lastest game screen frame buffer
self.frame = self.capture.get_frame()
# Resize game screen to 1296x759
self.img_frame = cv2.resize(self.frame, (1296, 759), interpolation=cv2.INTER_NEAREST)
# Grayscale game window
self.img_frame_gray = cv2.cvtColor(self.img_frame, cv2.COLOR_BGR2GRAY)
# Image for debug use
self.img_frame_debug = self.img_frame.copy()
# Get current route image
if not self.args.patrol:
self.img_route = self.img_routes[self.idx_routes]
self.img_route_debug = cv2.cvtColor(self.img_route, cv2.COLOR_RGB2BGR)
# Get minimap location
if self.is_first_frame and self.cfg.is_use_minimap:
self.loc_minimap = self.get_minimap_location()
# Debug
if self.cfg.is_use_minimap:
h, w = self.img_map.shape[:2]
draw_rectangle(
self.img_frame_debug,
self.loc_minimap,
(h, w),
(0, 0, 255), "minimap",thickness=1
)
# Detect HP/MP/EXP bar on UI
self.hp_ratio, self.mp_ratio, self.exp_ratio = self.get_hp_mp_exp()
# Check whether "PLease remove runes" warning appears on screen
if self.is_rune_warning():
self.rune_detect_level = 0
self.switch_status("finding_rune")
# Get player location in game window
self.loc_player = self.get_player_location()
# Get player location on map
if self.cfg.is_use_minimap:
loc_player_minimap = self.get_player_location_on_minimap()
if loc_player_minimap:
self.loc_player_minimap = loc_player_minimap
else:
if not self.args.patrol:
self.loc_player_global = self.get_player_location_global()
# Check whether a rune icon is near player
if self.is_rune_near_player():
self.switch_status("near_rune")
# Check whether we entered the rune mini-game
if self.status == "near_rune":
# stop character
self.kb.set_command("stop")
time.sleep(0.1) # Wait for character to stop
self.kb.disable() # Disable kb thread during rune solving
# Attempt to trigger rune
if not self.args.disable_control:
self.kb.press_key("up", 0.02)
time.sleep(1) # Wait rune game to pop up
# If entered the game, start solving rune
if self.is_in_rune_game():
self.solve_rune() # Blocking until runes solved
self.rune_detect_level = 0 # reset rune detect level
self.switch_status("hunting")
# Restore kb thread
self.kb.enable()
# Get all monster near player
if self.args.attack == "aoe_skill":
# Search monster near player
x0 = max(0, self.loc_player[0] - self.cfg.aoe_skill_range_x//2)
x1 = min(self.img_frame.shape[1], self.loc_player[0] + self.cfg.aoe_skill_range_x//2)
y0 = max(0, self.loc_player[1] - self.cfg.aoe_skill_range_y//2)
y1 = min(self.img_frame.shape[0], self.loc_player[1] + self.cfg.aoe_skill_range_y//2)
elif self.args.attack == "magic_claw":
# Search monster nearby magic claw range
dx = self.cfg.magic_claw_range_x + self.cfg.monster_search_margin
dy = self.cfg.magic_claw_range_y + self.cfg.monster_search_margin
x0 = max(0, self.loc_player[0] - dx)
x1 = min(self.img_frame.shape[1], self.loc_player[0] + dx)
y0 = max(0, self.loc_player[1] - dy)
y1 = min(self.img_frame.shape[0], self.loc_player[1] + dy)
# Get monster in skill range
self.monster_info = self.get_monsters_in_range((x0, y0), (x1, y1))
if self.args.attack == "aoe_skill":
if len(self.monster_info) == 0:
attack_direction = None
else:
attack_direction = "I don't care"
elif self.args.attack == "magic_claw":
# Get nearest monster to player
monster_left = self.get_nearest_monster(is_left = True)
monster_right = self.get_nearest_monster(is_left = False)
# Compute distance for left
distance_left = float('inf')
if monster_left is not None:
mx, my = monster_left["position"]
mw, mh = monster_left["size"]
center_left = (mx + mw // 2, my + mh // 2)
distance_left = abs(center_left[0] - self.loc_player[0]) + \
abs(center_left[1] - self.loc_player[1])
# Compute distance for right
distance_right = float('inf')
if monster_right is not None:
mx, my = monster_right["position"]
mw, mh = monster_right["size"]
center_right = (mx + mw // 2, my + mh // 2)
distance_right = abs(center_right[0] - self.loc_player[0]) + \
abs(center_right[1] - self.loc_player[1])
# Choose attack direction
attack_direction = None
if distance_left < distance_right:
attack_direction = "left"
elif distance_right < distance_left:
attack_direction = "right"
command = ""
if self.args.patrol:
x, y = self.loc_player
h, w = self.img_frame.shape[:2]
loc_player_ratio = float(x)/float(w)
left_ratio, right_ratio = self.cfg.patrol_range
# Check if we need to change patrol direction
if self.is_patrol_to_left and loc_player_ratio < left_ratio:
self.patrol_turn_point_cnt += 1
elif (not self.is_patrol_to_left) and loc_player_ratio > right_ratio:
self.patrol_turn_point_cnt += 1
if self.patrol_turn_point_cnt > self.cfg.turn_point_thres:
self.is_patrol_to_left = not self.is_patrol_to_left
self.patrol_turn_point_cnt = 0
# Set command for patrol mode
if time.time() - self.t_patrol_last_attack > self.cfg.patrol_attack_interval:
command = "attack"
self.t_patrol_last_attack = time.time()
elif self.is_patrol_to_left:
command = "walk left"
else:
command = "walk right"
else:
# get color code from img_route
if self.cfg.is_use_minimap:
color_code = self.get_nearest_color_code_on_minimap()
else:
color_code = self.get_nearest_color_code()
if color_code:
if color_code["action"] == "goal":
# Switch to next route map
self.idx_routes = (self.idx_routes+1)%len(self.img_routes)
logger.debug(f"Change to new route:{self.idx_routes}")
command = color_code["action"]
# teleport away from edge to avoid fall off
if self.is_near_edge() and \
time.time() - self.t_last_teleport > self.cfg.teleport_cooldown:
command = command.replace("walk", "teleport")
self.t_last_teleport = time.time() # update timer
# Special logic for each status, overwrite color code action
if self.status == "hunting":
# Perform a random action when player stuck
if self.cfg.is_use_minimap and not self.args.patrol and \
self.is_player_stuck_minimap():
command = self.get_random_action()
elif not self.cfg.is_use_minimap and not self.args.patrol and \
self.is_player_stuck():
command = self.get_random_action()
elif command in ["up", "down"]:
pass # Don't attack or heal while character is on rope
# elif self.hp_ratio <= self.cfg.heal_ratio:
# command = "heal"
# elif self.mp_ratio <= self.cfg.add_mp_ratio:
# command = "add mp"
elif attack_direction == "I don't care":
command = "attack"
elif attack_direction == "left":
command = "attack left"
elif attack_direction == "right":
command = "attack right"
# WIP: teleport while walking is unstable
# elif command[:4] == "walk":
# if self.cfg.is_use_teleport_to_walk and \
# time.time() - self.t_last_teleport > self.cfg.teleport_cooldown:
# command = command.replace("walk", "teleport")
# self.t_last_teleport = time.time() # update timer
elif self.status == "finding_rune":
if self.is_player_stuck():
command = self.get_random_action()
# Check if finding rune timeout
if time.time() - self.t_last_switch_status > self.cfg.rune_finding_timeout:
self.rune_detect_level = 0 # reset level
self.switch_status("resting")
# Check if need to raise level to lower the detection threshold
self.rune_detect_level = int(time.time() - self.t_last_switch_status) // self.cfg.rune_detect_level_raise_interval
elif self.status == "near_rune":
# Stay in near_rune status for only a few seconds
if time.time() - self.t_last_switch_status > self.cfg.near_rune_duration:
self.switch_status("hunting")
elif self.status == "resting":
self.img_routes = [self.img_route_rest] # Set up resting route
self.idx_routes = 0
else:
logger.error(f"Unknown status: {self.status}")
# send command to keyboard controller
self.kb.set_command(command)
#############
### Debug ###
#############
# Print text on debug image
self.update_info_on_img_frame_debug()
# Show debug image on window
self.update_img_frame_debug()
# Check if need to save screenshot
if self.kb.is_need_screen_shot:
screenshot(mapleStoryBot.img_frame)
self.kb.is_need_screen_shot = False
# Resize img_route_debug for better visualization
if not self.args.patrol:
h, w = self.img_route_debug.shape[:2]
if not self.cfg.is_use_minimap:
self.img_route_debug = cv2.resize(self.img_route_debug, (w // 2, h // 2),
interpolation=cv2.INTER_NEAREST)
cv2.imshow("Route Map Debug", self.img_route_debug)
# Enable cached location since second frame
self.is_first_frame = False
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'--disable_control',
action='store_true',
help='Disable simulated keyboard input'
)
parser.add_argument(
'--patrol',
action='store_true',
help='Enable patrol mode'
)
# Argument to specify map name
parser.add_argument(
'--map',
type=str,
default='lost_time_1',
help='Specify the map name'
)
parser.add_argument(
"--monsters",
type=str,
default="evolved_ghost",
help="Specify which monsters to load, comma-separated"
"(e.g., --monsters green_mushroom,zombie_mushroom)"
)
parser.add_argument(
'--attack',
type=str,
default='magic_claw',
help='Choose attack method, "magic_claw", "aoe_skill"'
)
try:
mapleStoryBot = MapleStoryBot(parser.parse_args())
except Exception as e:
logger.error(f"MapleStoryBot Init failed: {e}")
sys.exit(1)
else:
while True:
t_start = time.time()
# Process one game window frame
mapleStoryBot.run_once()
# Exit if 'q' is pressed
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
# Cap FPS to save system resource
frame_duration = time.time() - t_start
target_duration = 1.0 / mapleStoryBot.cfg.fps_limit
if frame_duration < target_duration:
time.sleep(target_duration - frame_duration)
cv2.destroyAllWindows()
| 412 | 0.889135 | 1 | 0.889135 | game-dev | MEDIA | 0.595223 | game-dev | 0.91422 | 1 | 0.91422 |
HellFirePvP/AstralSorcery | 3,844 | src/main/java/hellfirepvp/astralsorcery/common/network/play/client/PktToggleClientOption.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.common.network.play.client;
import hellfirepvp.astralsorcery.common.data.research.PlayerProgress;
import hellfirepvp.astralsorcery.common.data.research.ResearchHelper;
import hellfirepvp.astralsorcery.common.data.research.ResearchManager;
import hellfirepvp.astralsorcery.common.network.base.ASPacket;
import hellfirepvp.astralsorcery.common.util.data.ByteBufUtils;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.util.Util;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.network.NetworkEvent;
import javax.annotation.Nonnull;
/**
* This class is part of the Astral Sorcery Mod
* The complete source code for this mod can be found on github.
* Class: PktToggleClientOption
* Created by HellFirePvP
* Date: 13.05.2020 / 19:25
*/
public class PktToggleClientOption extends ASPacket<PktToggleClientOption> {
private Option option;
public PktToggleClientOption() {}
public PktToggleClientOption(Option option) {
this.option = option;
}
@Nonnull
@Override
public Encoder<PktToggleClientOption> encoder() {
return (pkt, buf) -> ByteBufUtils.writeEnumValue(buf, pkt.option);
}
@Nonnull
@Override
public Decoder<PktToggleClientOption> decoder() {
return buf -> new PktToggleClientOption(ByteBufUtils.readEnumValue(buf, Option.class));
}
@Nonnull
@Override
public Handler<PktToggleClientOption> handler() {
return new Handler<PktToggleClientOption>() {
@Override
@OnlyIn(Dist.CLIENT)
public void handleClient(PktToggleClientOption packet, NetworkEvent.Context context) {}
@Override
public void handleServer(PktToggleClientOption packet, NetworkEvent.Context context) {
ServerPlayerEntity player = context.getSender();
switch (packet.option) {
case DISABLE_PERK_ABILITIES:
if (ResearchManager.togglePerkAbilities(player)) {
PlayerProgress prog = ResearchHelper.getProgress(player, LogicalSide.SERVER);
if (prog.isValid()) {
ITextComponent status;
if (prog.doPerkAbilities()) {
status = new TranslationTextComponent("astralsorcery.progress.perk_abilities.enable").mergeStyle(TextFormatting.GREEN);
} else {
status = new TranslationTextComponent("astralsorcery.progress.perk_abilities.disable").mergeStyle(TextFormatting.RED);
}
player.sendMessage(new TranslationTextComponent("astralsorcery.progress.perk_abilities", status).mergeStyle(TextFormatting.GRAY), Util.DUMMY_UUID);
}
}
break;
}
}
@Override
public void handle(PktToggleClientOption packet, NetworkEvent.Context context, LogicalSide side) {}
};
}
public static enum Option {
DISABLE_PERK_ABILITIES
}
}
| 412 | 0.844345 | 1 | 0.844345 | game-dev | MEDIA | 0.841469 | game-dev,networking | 0.546888 | 1 | 0.546888 |
alinradut/AsteroidsCocos2D-x | 10,536 | libs/cocos2dx/platform/CCFileUtils.cpp | /****************************************************************************
Copyright (c) 2010 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCFileUtils.h"
#if (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) && (CC_TARGET_PLATFORM != CC_PLATFORM_AIRPLAY)
#include <stack>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xmlmemory.h>
#include "CCLibxml2.h"
#include "CCString.h"
#include "CCSAXParser.h"
#include "support/zip_support/unzip.h"
NS_CC_BEGIN;
typedef enum
{
SAX_NONE = 0,
SAX_KEY,
SAX_DICT,
SAX_INT,
SAX_REAL,
SAX_STRING,
SAX_ARRAY
}CCSAXState;
class CCDictMaker : public CCSAXDelegator
{
public:
CCDictionary<std::string, CCObject*> *m_pRootDict;
CCDictionary<std::string, CCObject*> *m_pCurDict;
std::stack<CCDictionary<std::string, CCObject*>*> m_tDictStack;
std::string m_sCurKey;///< parsed key
CCSAXState m_tState;
CCMutableArray<CCObject*> *m_pArray;
std::stack<CCMutableArray<CCObject*>*> m_tArrayStack;
std::stack<CCSAXState> m_tStateStack;
public:
CCDictMaker()
: m_pRootDict(NULL),
m_pCurDict(NULL),
m_tState(SAX_NONE),
m_pArray(NULL)
{
}
~CCDictMaker()
{
}
CCDictionary<std::string, CCObject*> *dictionaryWithContentsOfFile(const char *pFileName)
{
CCSAXParser parser;
if (false == parser.init("UTF-8"))
{
return NULL;
}
parser.setDelegator(this);
parser.parse(pFileName);
return m_pRootDict;
}
void startElement(void *ctx, const char *name, const char **atts)
{
CC_UNUSED_PARAM(ctx);
CC_UNUSED_PARAM(atts);
std::string sName((char*)name);
if( sName == "dict" )
{
m_pCurDict = new CCDictionary<std::string, CCObject*>();
if(! m_pRootDict)
{
m_pRootDict = m_pCurDict;
}
m_tState = SAX_DICT;
CCSAXState preState = SAX_NONE;
if (! m_tStateStack.empty())
{
preState = m_tStateStack.top();
}
if (SAX_ARRAY == preState)
{
// add the dictionary into the array
m_pArray->addObject(m_pCurDict);
}
else if (SAX_DICT == preState)
{
// add the dictionary into the pre dictionary
CCAssert(! m_tDictStack.empty(), "The state is wrong!");
CCDictionary<std::string, CCObject*>* pPreDict = m_tDictStack.top();
pPreDict->setObject(m_pCurDict, m_sCurKey);
}
m_pCurDict->autorelease();
// record the dict state
m_tStateStack.push(m_tState);
m_tDictStack.push(m_pCurDict);
}
else if(sName == "key")
{
m_tState = SAX_KEY;
}
else if(sName == "integer")
{
m_tState = SAX_INT;
}
else if(sName == "real")
{
m_tState = SAX_REAL;
}
else if(sName == "string")
{
m_tState = SAX_STRING;
}
else if (sName == "array")
{
m_tState = SAX_ARRAY;
m_pArray = new CCMutableArray<CCObject*>();
CCSAXState preState = m_tStateStack.empty() ? SAX_DICT : m_tStateStack.top();
if (preState == SAX_DICT)
{
m_pCurDict->setObject(m_pArray, m_sCurKey);
}
else if (preState == SAX_ARRAY)
{
CCAssert(! m_tArrayStack.empty(), "The state is worng!");
CCMutableArray<CCObject*>* pPreArray = m_tArrayStack.top();
pPreArray->addObject(m_pArray);
}
m_pArray->release();
// record the array state
m_tStateStack.push(m_tState);
m_tArrayStack.push(m_pArray);
}
else
{
m_tState = SAX_NONE;
}
}
void endElement(void *ctx, const char *name)
{
CC_UNUSED_PARAM(ctx);
CCSAXState curState = m_tStateStack.empty() ? SAX_DICT : m_tStateStack.top();
std::string sName((char*)name);
if( sName == "dict" )
{
m_tStateStack.pop();
m_tDictStack.pop();
if ( !m_tDictStack.empty())
{
m_pCurDict = m_tDictStack.top();
}
}
else if (sName == "array")
{
m_tStateStack.pop();
m_tArrayStack.pop();
if (! m_tArrayStack.empty())
{
m_pArray = m_tArrayStack.top();
}
}
else if (sName == "true")
{
CCString *str = new CCString("1");
if (SAX_ARRAY == curState)
{
m_pArray->addObject(str);
}
else if (SAX_DICT == curState)
{
m_pCurDict->setObject(str, m_sCurKey);
}
str->release();
}
else if (sName == "false")
{
CCString *str = new CCString("0");
if (SAX_ARRAY == curState)
{
m_pArray->addObject(str);
}
else if (SAX_DICT == curState)
{
m_pCurDict->setObject(str, m_sCurKey);
}
str->release();
}
m_tState = SAX_NONE;
}
void textHandler(void *ctx, const char *ch, int len)
{
CC_UNUSED_PARAM(ctx);
if (m_tState == SAX_NONE)
{
return;
}
CCSAXState curState = m_tStateStack.empty() ? SAX_DICT : m_tStateStack.top();
CCString *pText = new CCString();
pText->m_sString = std::string((char*)ch,0,len);
switch(m_tState)
{
case SAX_KEY:
m_sCurKey = pText->m_sString;
break;
case SAX_INT:
case SAX_REAL:
case SAX_STRING:
{
CCAssert(!m_sCurKey.empty(), "not found key : <integet/real>");
if (SAX_ARRAY == curState)
{
m_pArray->addObject(pText);
}
else if (SAX_DICT == curState)
{
m_pCurDict->setObject(pText, m_sCurKey);
}
break;
}
default:
break;
}
pText->release();
}
};
std::string& CCFileUtils::ccRemoveHDSuffixFromFile(std::string& path)
{
#if CC_IS_RETINA_DISPLAY_SUPPORTED
if( CC_CONTENT_SCALE_FACTOR() == 2 )
{
std::string::size_type pos = path.rfind("/") + 1; // the begin index of last part of path
std::string::size_type suffixPos = path.rfind(CC_RETINA_DISPLAY_FILENAME_SUFFIX);
if (std::string::npos != suffixPos && suffixPos > pos)
{
CCLog("cocos2d: FilePath(%s) contains suffix(%s), remove it.", path.c_str(),
CC_RETINA_DISPLAY_FILENAME_SUFFIX);
path.replace(suffixPos, strlen(CC_RETINA_DISPLAY_FILENAME_SUFFIX), "");
}
}
#endif // CC_IS_RETINA_DISPLAY_SUPPORTED
return path;
}
CCDictionary<std::string, CCObject*> *CCFileUtils::dictionaryWithContentsOfFile(const char *pFileName)
{
CCDictMaker tMaker;
return tMaker.dictionaryWithContentsOfFile(pFileName);
}
unsigned char* CCFileUtils::getFileDataFromZip(const char* pszZipFilePath, const char* pszFileName, unsigned long * pSize)
{
unsigned char * pBuffer = NULL;
unzFile pFile = NULL;
*pSize = 0;
do
{
CC_BREAK_IF(!pszZipFilePath || !pszFileName);
CC_BREAK_IF(strlen(pszZipFilePath) == 0);
pFile = unzOpen(pszZipFilePath);
CC_BREAK_IF(!pFile);
int nRet = unzLocateFile(pFile, pszFileName, 1);
CC_BREAK_IF(UNZ_OK != nRet);
char szFilePathA[260];
unz_file_info FileInfo;
nRet = unzGetCurrentFileInfo(pFile, &FileInfo, szFilePathA, sizeof(szFilePathA), NULL, 0, NULL, 0);
CC_BREAK_IF(UNZ_OK != nRet);
nRet = unzOpenCurrentFile(pFile);
CC_BREAK_IF(UNZ_OK != nRet);
pBuffer = new unsigned char[FileInfo.uncompressed_size];
int nSize = 0;
nSize = unzReadCurrentFile(pFile, pBuffer, FileInfo.uncompressed_size);
CCAssert(nSize == 0 || nSize == (int)FileInfo.uncompressed_size, "the file size is wrong");
*pSize = FileInfo.uncompressed_size;
unzCloseCurrentFile(pFile);
} while (0);
if (pFile)
{
unzClose(pFile);
}
return pBuffer;
}
//////////////////////////////////////////////////////////////////////////
// Notification support when getFileData from invalid file path.
//////////////////////////////////////////////////////////////////////////
static bool s_bPopupNotify = true;
void CCFileUtils::setIsPopupNotify(bool bNotify)
{
s_bPopupNotify = bNotify;
}
bool CCFileUtils::getIsPopupNotify()
{
return s_bPopupNotify;
}
NS_CC_END;
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
#include "win32/CCFileUtils_win32.cpp"
#endif
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WOPHONE)
#include "wophone/CCFileUtils_wophone.cpp"
#endif
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include "android/CCFileUtils_android.cpp"
#endif
#endif // (CC_TARGET_PLATFORM != CC_PLATFORM_IOS && CC_TARGET_PLATFORM != CC_PLATFORM_AIRPLAY)
| 412 | 0.936431 | 1 | 0.936431 | game-dev | MEDIA | 0.436596 | game-dev | 0.892288 | 1 | 0.892288 |
gamingdotme/opensource-casino-v10 | 42,137 | casino/app/Games/FullOfLuckCT/SlotSettings.php | <?php
namespace VanguardLTE\Games\FullOfLuckCT
{
class SlotSettings
{
public $playerId = null;
public $splitScreen = null;
public $reelStrip1 = null;
public $reelStrip2 = null;
public $reelStrip3 = null;
public $reelStrip4 = null;
public $reelStrip5 = null;
public $reelStrip6 = null;
public $reelStripBonus1 = null;
public $reelStripBonus2 = null;
public $reelStripBonus3 = null;
public $reelStripBonus4 = null;
public $reelStripBonus5 = null;
public $reelStripBonus6 = null;
public $slotId = '';
public $slotDBId = '';
public $Line = null;
public $scaleMode = null;
public $numFloat = null;
public $gameLine = null;
public $Bet = null;
public $isBonusStart = null;
public $Balance = null;
public $SymbolGame = null;
public $GambleType = null;
public $lastEvent = null;
public $Jackpots = [];
public $keyController = null;
public $slotViewState = null;
public $hideButtons = null;
public $slotReelsConfig = null;
public $slotFreeCount = null;
public $slotFreeMpl = null;
public $slotWildMpl = null;
public $slotExitUrl = null;
public $slotBonus = null;
public $slotBonusType = null;
public $slotScatterType = null;
public $slotGamble = null;
public $Paytable = [];
public $slotSounds = [];
public $jpgs = null;
private $Bank = null;
private $Percent = null;
private $WinLine = null;
private $WinGamble = null;
private $Bonus = null;
private $shop_id = null;
public $currency = null;
public $user = null;
public $game = null;
public $shop = null;
public $jpgPercentZero = false;
public $count_balance = null;
public function __construct($sid, $playerId)
{
$this->slotId = $sid;
$this->playerId = $playerId;
$user = \VanguardLTE\User::lockForUpdate()->find($this->playerId);
$this->user = $user;
$this->shop_id = $user->shop_id;
$gamebank = \VanguardLTE\GameBank::where(['shop_id' => $this->shop_id])->lockForUpdate()->get();
$game = \VanguardLTE\Game::where([
'name' => $this->slotId,
'shop_id' => $this->shop_id
])->lockForUpdate()->first();
$this->shop = \VanguardLTE\Shop::find($this->shop_id);
$this->game = $game;
$this->MaxWin = $this->shop->max_win;
$this->increaseRTP = 1;
$this->CurrentDenom = $this->game->denomination;
$this->scaleMode = 0;
$this->numFloat = 0;
$this->Paytable['SYM_1'] = [
0,
0,
2,
5,
20,
100
];
$this->Paytable['SYM_2'] = [
0,
0,
0,
5,
25,
100
];
$this->Paytable['SYM_3'] = [
0,
0,
0,
5,
25,
100
];
$this->Paytable['SYM_4'] = [
0,
0,
0,
5,
25,
100
];
$this->Paytable['SYM_5'] = [
0,
0,
0,
5,
25,
100
];
$this->Paytable['SYM_6'] = [
0,
0,
0,
5,
25,
150
];
$this->Paytable['SYM_7'] = [
0,
0,
0,
5,
25,
150
];
$this->Paytable['SYM_8'] = [
0,
0,
0,
15,
50,
200
];
$this->Paytable['SYM_9'] = [
0,
0,
0,
15,
50,
200
];
$this->Paytable['SYM_10'] = [
0,
0,
0,
15,
50,
200
];
$this->Paytable['SYM_11'] = [
0,
0,
2,
20,
150,
700
];
$this->Paytable['SYM_12'] = [
0,
0,
2,
20,
150,
700
];
$this->Paytable['SYM_13'] = [
0,
0,
10,
250,
2000,
9000
];
$reel = new GameReel();
foreach( [
'reelStrip1',
'reelStrip2',
'reelStrip3',
'reelStrip4',
'reelStrip5',
'reelStrip6'
] as $reelStrip )
{
if( count($reel->reelsStrip[$reelStrip]) )
{
$this->$reelStrip = $reel->reelsStrip[$reelStrip];
}
}
$this->keyController = [
'13' => 'uiButtonSpin,uiButtonSkip',
'49' => 'uiButtonInfo',
'50' => 'uiButtonCollect',
'51' => 'uiButtonExit2',
'52' => 'uiButtonLinesMinus',
'53' => 'uiButtonLinesPlus',
'54' => 'uiButtonBetMinus',
'55' => 'uiButtonBetPlus',
'56' => 'uiButtonGamble',
'57' => 'uiButtonRed',
'48' => 'uiButtonBlack',
'189' => 'uiButtonAuto',
'187' => 'uiButtonSpin'
];
$this->slotReelsConfig = [
[
425,
142,
3
],
[
669,
142,
3
],
[
913,
142,
3
],
[
1157,
142,
3
],
[
1401,
142,
3
]
];
$this->slotBonusType = 1;
$this->slotScatterType = 0;
$this->splitScreen = false;
$this->slotBonus = true;
$this->slotGamble = true;
$this->slotFastStop = 1;
$this->slotExitUrl = '/';
$this->slotWildMpl = 2;
$this->GambleType = 1;
$this->slotFreeCount = 15;
$this->slotFreeMpl = 3;
$this->slotViewState = ($game->slotViewState == '' ? 'Normal' : $game->slotViewState);
$this->hideButtons = [];
$this->jpgs = \VanguardLTE\JPG::where('shop_id', $this->shop_id)->lockForUpdate()->get();
$this->slotJackPercent = [];
$this->slotJackpot = [];
for( $jp = 1; $jp <= 4; $jp++ )
{
$this->slotJackpot[] = $game->{'jp_' . $jp};
$this->slotJackPercent[] = $game->{'jp_' . $jp . '_percent'};
}
$this->Denominations = [1];
$this->Line = [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15
];
$this->gameLine = [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15
];
$this->Bet = explode(',', $game->bet);
$this->Balance = $user->balance;
$this->SymbolGame = [
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'10',
'11',
'12',
'13'
];
$this->Bank = $game->get_gamebank();
$this->Percent = $this->shop->percent;
$this->WinGamble = $game->rezerv;
$this->slotDBId = $game->id;
$this->slotCurrency = $user->shop->currency;
$this->count_balance = $user->count_balance;
if( $user->address > 0 && $user->count_balance == 0 )
{
$this->Percent = 0;
$this->jpgPercentZero = true;
}
else if( $user->count_balance == 0 )
{
$this->Percent = 100;
}
if( !isset($this->user->session) || strlen($this->user->session) <= 0 )
{
$this->user->session = serialize([]);
}
$this->gameData = unserialize($this->user->session);
if( count($this->gameData) > 0 )
{
foreach( $this->gameData as $key => $vl )
{
if( $vl['timelife'] <= time() )
{
unset($this->gameData[$key]);
}
}
}
if( !isset($this->game->advanced) || strlen($this->game->advanced) <= 0 )
{
$this->game->advanced = serialize([]);
}
$this->gameDataStatic = unserialize($this->game->advanced);
if( count($this->gameDataStatic) > 0 )
{
foreach( $this->gameDataStatic as $key => $vl )
{
if( $vl['timelife'] <= time() )
{
unset($this->gameDataStatic[$key]);
}
}
}
}
public function is_active()
{
if( $this->game && $this->shop && $this->user && (!$this->game->view || $this->shop->is_blocked || $this->user->is_blocked || $this->user->status == \VanguardLTE\Support\Enum\UserStatus::BANNED) )
{
\VanguardLTE\Session::where('user_id', $this->user->id)->delete();
$this->user->update(['remember_token' => null]);
return false;
}
if( !$this->game->view )
{
return false;
}
if( $this->shop->is_blocked )
{
return false;
}
if( $this->user->is_blocked )
{
return false;
}
if( $this->user->status == \VanguardLTE\Support\Enum\UserStatus::BANNED )
{
return false;
}
return true;
}
public function SetGameData($key, $value)
{
$timeLife = 86400;
$this->gameData[$key] = [
'timelife' => time() + $timeLife,
'payload' => $value
];
}
public function GetGameData($key)
{
if( isset($this->gameData[$key]) )
{
return $this->gameData[$key]['payload'];
}
else
{
return 0;
}
}
public function FormatFloat($num)
{
$str0 = explode('.', $num);
if( isset($str0[1]) )
{
if( strlen($str0[1]) > 4 )
{
return round($num * 100) / 100;
}
else if( strlen($str0[1]) > 2 )
{
return floor($num * 100) / 100;
}
else
{
return $num;
}
}
else
{
return $num;
}
}
public function SaveGameData()
{
$this->user->session = serialize($this->gameData);
$this->user->save();
}
public function CheckBonusWin()
{
$allRateCnt = 0;
$allRate = 0;
foreach( $this->Paytable as $vl )
{
foreach( $vl as $vl2 )
{
if( $vl2 > 0 )
{
$allRateCnt++;
$allRate += $vl2;
break;
}
}
}
return $allRate / $allRateCnt;
}
public function GetRandomPay()
{
$allRate = [];
foreach( $this->Paytable as $vl )
{
foreach( $vl as $vl2 )
{
if( $vl2 > 0 )
{
$allRate[] = $vl2;
}
}
}
shuffle($allRate);
if( $this->game->stat_in < ($this->game->stat_out + ($allRate[0] * $this->AllBet)) )
{
$allRate[0] = 0;
}
return $allRate[0];
}
public function HasGameDataStatic($key)
{
if( isset($this->gameDataStatic[$key]) )
{
return true;
}
else
{
return false;
}
}
public function SaveGameDataStatic()
{
$this->game->advanced = serialize($this->gameDataStatic);
$this->game->save();
$this->game->refresh();
}
public function SetGameDataStatic($key, $value)
{
$timeLife = 86400;
$this->gameDataStatic[$key] = [
'timelife' => time() + $timeLife,
'payload' => $value
];
}
public function GetGameDataStatic($key)
{
if( isset($this->gameDataStatic[$key]) )
{
return $this->gameDataStatic[$key]['payload'];
}
else
{
return 0;
}
}
public function HasGameData($key)
{
if( isset($this->gameData[$key]) )
{
return true;
}
else
{
return false;
}
}
public function GetHistory()
{
$history = \VanguardLTE\GameLog::whereRaw('game_id=? and user_id=? ORDER BY id DESC LIMIT 10', [
$this->slotDBId,
$this->playerId
])->get();
$this->lastEvent = 'NULL';
foreach( $history as $log )
{
$tmpLog = json_decode($log->str);
if( $tmpLog->responseEvent != 'gambleResult' )
{
$this->lastEvent = $log->str;
break;
}
}
if( isset($tmpLog) )
{
return $tmpLog;
}
else
{
return 'NULL';
}
}
public function UpdateJackpots($bet)
{
$bet = $bet * $this->CurrentDenom;
$count_balance = $this->count_balance;
$jsum = [];
$payJack = 0;
for( $i = 0; $i < count($this->jpgs); $i++ )
{
if( $count_balance == 0 || $this->jpgPercentZero )
{
$jsum[$i] = $this->jpgs[$i]->balance;
}
else if( $count_balance < $bet )
{
$jsum[$i] = $count_balance / 100 * $this->jpgs[$i]->percent + $this->jpgs[$i]->balance;
}
else
{
$jsum[$i] = $bet / 100 * $this->jpgs[$i]->percent + $this->jpgs[$i]->balance;
}
if( $this->jpgs[$i]->get_pay_sum() < $jsum[$i] && $this->jpgs[$i]->get_pay_sum() > 0 )
{
if( $this->jpgs[$i]->user_id && $this->jpgs[$i]->user_id != $this->user->id )
{
}
else
{
$payJack = $this->jpgs[$i]->get_pay_sum() / $this->CurrentDenom;
$jsum[$i] = $jsum[$i] - $this->jpgs[$i]->get_pay_sum();
$this->SetBalance($this->jpgs[$i]->get_pay_sum() / $this->CurrentDenom);
if( $this->jpgs[$i]->get_pay_sum() > 0 )
{
\VanguardLTE\StatGame::create([
'user_id' => $this->playerId,
'balance' => $this->Balance * $this->CurrentDenom,
'bet' => 0,
'win' => $this->jpgs[$i]->get_pay_sum(),
'game' => $this->game->name . ' JPG ' . $this->jpgs[$i]->id,
'in_game' => 0,
'in_jpg' => 0,
'in_profit' => 0,
'shop_id' => $this->shop_id,
'date_time' => \Carbon\Carbon::now()
]);
}
}
$i++;
}
$this->jpgs[$i]->balance = $jsum[$i];
$this->jpgs[$i]->save();
if( $this->jpgs[$i]->balance < $this->jpgs[$i]->get_min('start_balance') )
{
$summ = $this->jpgs[$i]->get_start_balance();
if( $summ > 0 )
{
$this->jpgs[$i]->add_jpg('add', $summ);
}
}
}
if( $payJack > 0 )
{
$payJack = sprintf('%01.2f', $payJack);
$this->Jackpots['jackPay'] = $payJack;
}
}
public function GetBank($slotState = '')
{
if( $this->isBonusStart || $slotState == 'bonus' || $slotState == 'freespin' || $slotState == 'respin' )
{
$slotState = 'bonus';
}
else
{
$slotState = '';
}
$game = $this->game;
$this->Bank = $game->get_gamebank($slotState);
return $this->Bank / $this->CurrentDenom;
}
public function GetPercent()
{
return $this->Percent;
}
public function GetCountBalanceUser()
{
return $this->user->count_balance;
}
public function InternalErrorSilent($errcode)
{
$strLog = '';
$strLog .= "\n";
$strLog .= ('{"responseEvent":"error","responseType":"' . $errcode . '","serverResponse":"InternalError","request":' . json_encode($_REQUEST) . ',"requestRaw":' . file_get_contents('php://input') . '}');
$strLog .= "\n";
$strLog .= ' ############################################### ';
$strLog .= "\n";
$slg = '';
if( file_exists(storage_path('logs/') . $this->slotId . 'Internal.log') )
{
$slg = file_get_contents(storage_path('logs/') . $this->slotId . 'Internal.log');
}
file_put_contents(storage_path('logs/') . $this->slotId . 'Internal.log', $slg . $strLog);
}
public function InternalError($errcode)
{
$strLog = '';
$strLog .= "\n";
$strLog .= ('{"responseEvent":"error","responseType":"' . $errcode . '","serverResponse":"InternalError","request":' . json_encode($_REQUEST) . ',"requestRaw":' . file_get_contents('php://input') . '}');
$strLog .= "\n";
$strLog .= ' ############################################### ';
$strLog .= "\n";
$slg = '';
if( file_exists(storage_path('logs/') . $this->slotId . 'Internal.log') )
{
$slg = file_get_contents(storage_path('logs/') . $this->slotId . 'Internal.log');
}
file_put_contents(storage_path('logs/') . $this->slotId . 'Internal.log', $slg . $strLog);
exit( '' );
}
public function SetBank($slotState = '', $sum, $slotEvent = '')
{
if( $this->isBonusStart || $slotState == 'bonus' || $slotState == 'freespin' || $slotState == 'respin' )
{
$slotState = 'bonus';
}
else
{
$slotState = '';
}
if( $this->GetBank($slotState) + $sum < 0 )
{
$this->InternalError('Bank_ ' . $sum . ' CurrentBank_ ' . $this->GetBank($slotState) . ' CurrentState_ ' . $slotState . ' Trigger_ ' . ($this->GetBank($slotState) + $sum));
}
$sum = $sum * $this->CurrentDenom;
$game = $this->game;
$bankBonusSum = 0;
if( $sum > 0 && $slotEvent == 'bet' )
{
$this->toGameBanks = 0;
$this->toSlotJackBanks = 0;
$this->toSysJackBanks = 0;
$this->betProfit = 0;
$prc = $this->GetPercent();
$prc_b = 10;
if( $prc <= $prc_b )
{
$prc_b = 0;
}
$count_balance = $this->count_balance;
$gameBet = $sum / $this->GetPercent() * 100;
if( $count_balance < $gameBet && $count_balance > 0 )
{
$firstBid = $count_balance;
$secondBid = $gameBet - $firstBid;
if( isset($this->betRemains0) )
{
$secondBid = $this->betRemains0;
}
$bankSum = $firstBid / 100 * $this->GetPercent();
$sum = $bankSum + $secondBid;
$bankBonusSum = $firstBid / 100 * $prc_b;
}
else if( $count_balance > 0 )
{
$bankBonusSum = $gameBet / 100 * $prc_b;
}
for( $i = 0; $i < count($this->jpgs); $i++ )
{
if( !$this->jpgPercentZero )
{
if( $count_balance < $gameBet && $count_balance > 0 )
{
$this->toSlotJackBanks += ($count_balance / 100 * $this->jpgs[$i]->percent);
}
else if( $count_balance > 0 )
{
$this->toSlotJackBanks += ($gameBet / 100 * $this->jpgs[$i]->percent);
}
}
}
$this->toGameBanks = $sum;
$this->betProfit = $gameBet - $this->toGameBanks - $this->toSlotJackBanks - $this->toSysJackBanks;
}
if( $sum > 0 )
{
$this->toGameBanks = $sum;
}
if( $bankBonusSum > 0 )
{
$sum -= $bankBonusSum;
$game->set_gamebank($bankBonusSum, 'inc', 'bonus');
}
if( $sum == 0 && $slotEvent == 'bet' && isset($this->betRemains) )
{
$sum = $this->betRemains;
}
$game->set_gamebank($sum, 'inc', $slotState);
$game->save();
return $game;
}
public function SetBalance($sum, $slotEvent = '')
{
if( $this->GetBalance() + $sum < 0 )
{
$this->InternalError('Balance_ ' . $sum);
}
$sum = $sum * $this->CurrentDenom;
if( $sum < 0 && $slotEvent == 'bet' )
{
$user = $this->user;
if( $user->count_balance == 0 )
{
$remains = [];
$this->betRemains = 0;
$sm = abs($sum);
if( $user->address < $sm && $user->address > 0 )
{
$remains[] = $sm - $user->address;
}
for( $i = 0; $i < count($remains); $i++ )
{
if( $this->betRemains < $remains[$i] )
{
$this->betRemains = $remains[$i];
}
}
}
if( $user->count_balance > 0 && $user->count_balance < abs($sum) )
{
$remains0 = [];
$sm = abs($sum);
$tmpSum = $sm - $user->count_balance;
$this->betRemains0 = $tmpSum;
if( $user->address > 0 )
{
$this->betRemains0 = 0;
if( $user->address < $tmpSum && $user->address > 0 )
{
$remains0[] = $tmpSum - $user->address;
}
for( $i = 0; $i < count($remains0); $i++ )
{
if( $this->betRemains0 < $remains0[$i] )
{
$this->betRemains0 = $remains0[$i];
}
}
}
}
$sum0 = abs($sum);
if( $user->count_balance == 0 )
{
$sm = abs($sum);
if( $user->address < $sm && $user->address > 0 )
{
$user->address = 0;
}
else if( $user->address > 0 )
{
$user->address -= $sm;
}
}
else if( $user->count_balance > 0 && $user->count_balance < $sum0 )
{
$sm = $sum0 - $user->count_balance;
if( $user->address < $sm && $user->address > 0 )
{
$user->address = 0;
}
else if( $user->address > 0 )
{
$user->address -= $sm;
}
}
$this->user->count_balance = $this->user->updateCountBalance($sum, $this->count_balance);
$this->user->count_balance = $this->FormatFloat($this->user->count_balance);
}
$this->user->increment('balance', $sum);
$this->user->balance = $this->FormatFloat($this->user->balance);
$this->user->save();
return $this->user;
}
public function GetBalance()
{
$user = $this->user;
$this->Balance = $user->balance / $this->CurrentDenom;
return $this->Balance;
}
public function SaveLogReport($spinSymbols, $bet, $lines, $win, $slotState)
{
$reportName = $this->slotId . ' ' . $slotState;
if( $slotState == 'freespin' )
{
$reportName = $this->slotId . ' FG';
}
else if( $slotState == 'bet' )
{
$reportName = $this->slotId . '';
}
else if( $slotState == 'slotGamble' )
{
$reportName = $this->slotId . ' DG';
}
$game = $this->game;
if( $slotState == 'bet' )
{
$this->user->update_level('bet', $bet * $this->CurrentDenom);
}
if( $slotState != 'freespin' )
{
$game->increment('stat_in', $bet * $this->CurrentDenom);
}
$game->increment('stat_out', $win * $this->CurrentDenom);
$game->tournament_stat($slotState, $this->user->id, $bet * $this->CurrentDenom, $win * $this->CurrentDenom);
$this->user->update(['last_bid' => \Carbon\Carbon::now()]);
if( !isset($this->betProfit) )
{
$this->betProfit = 0;
$this->toGameBanks = 0;
$this->toSlotJackBanks = 0;
$this->toSysJackBanks = 0;
}
if( !isset($this->toGameBanks) )
{
$this->toGameBanks = 0;
}
$this->game->increment('bids');
$this->game->refresh();
$gamebank = \VanguardLTE\GameBank::where(['shop_id' => $game->shop_id])->first();
if( $gamebank )
{
list($slotsBank, $bonusBank, $fishBank, $tableBank, $littleBank) = \VanguardLTE\Lib\Banker::get_all_banks($game->shop_id);
}
else
{
$slotsBank = $game->get_gamebank('', 'slots');
$bonusBank = $game->get_gamebank('bonus', 'bonus');
$fishBank = $game->get_gamebank('', 'fish');
$tableBank = $game->get_gamebank('', 'table_bank');
$littleBank = $game->get_gamebank('', 'little');
}
$totalBank = $slotsBank + $bonusBank + $fishBank + $tableBank + $littleBank;
\VanguardLTE\GameLog::create([
'game_id' => $this->slotDBId,
'user_id' => $this->playerId,
'ip' => $_SERVER['REMOTE_ADDR'],
'str' => $spinSymbols,
'shop_id' => $this->shop_id
]);
\VanguardLTE\StatGame::create([
'user_id' => $this->playerId,
'balance' => $this->Balance * $this->CurrentDenom,
'bet' => $bet * $this->CurrentDenom,
'win' => $win * $this->CurrentDenom,
'game' => $reportName,
'in_game' => $this->toGameBanks,
'in_jpg' => $this->toSlotJackBanks,
'in_profit' => $this->betProfit,
'denomination' => $this->CurrentDenom,
'shop_id' => $this->shop_id,
'slots_bank' => (double)$slotsBank,
'bonus_bank' => (double)$bonusBank,
'fish_bank' => (double)$fishBank,
'table_bank' => (double)$tableBank,
'little_bank' => (double)$littleBank,
'total_bank' => (double)$totalBank,
'date_time' => \Carbon\Carbon::now()
]);
}
public function GetSpinSettings($garantType = 'bet', $bet, $lines)
{
$curField = 10;
switch( $lines )
{
case 10:
$curField = 10;
break;
case 9:
case 8:
$curField = 9;
break;
case 7:
case 6:
$curField = 7;
break;
case 5:
case 4:
$curField = 5;
break;
case 3:
case 2:
$curField = 3;
break;
case 1:
$curField = 1;
break;
default:
$curField = 10;
break;
}
if( $garantType != 'bet' )
{
$pref = '_bonus';
}
else
{
$pref = '';
}
$this->AllBet = $bet * $lines;
$linesPercentConfigSpin = $this->game->get_lines_percent_config('spin');
$linesPercentConfigBonus = $this->game->get_lines_percent_config('bonus');
$currentPercent = $this->shop->percent;
$currentSpinWinChance = 0;
$currentBonusWinChance = 0;
$percentLevel = '';
foreach( $linesPercentConfigSpin['line' . $curField . $pref] as $k => $v )
{
$l = explode('_', $k);
$l0 = $l[0];
$l1 = $l[1];
if( $l0 <= $currentPercent && $currentPercent <= $l1 )
{
$percentLevel = $k;
break;
}
}
$currentSpinWinChance = $linesPercentConfigSpin['line' . $curField . $pref][$percentLevel];
$currentBonusWinChance = $linesPercentConfigBonus['line' . $curField . $pref][$percentLevel];
$RtpControlCount = 200;
if( !$this->HasGameDataStatic('SpinWinLimit') )
{
$this->SetGameDataStatic('SpinWinLimit', 0);
}
if( !$this->HasGameDataStatic('RtpControlCount') )
{
$this->SetGameDataStatic('RtpControlCount', $RtpControlCount);
}
if( $this->game->stat_in > 0 )
{
$rtpRange = $this->game->stat_out / $this->game->stat_in * 100;
}
else
{
$rtpRange = 0;
}
if( $this->GetGameDataStatic('RtpControlCount') == 0 )
{
if( $currentPercent + rand(1, 2) < $rtpRange && $this->GetGameDataStatic('SpinWinLimit') <= 0 )
{
$this->SetGameDataStatic('SpinWinLimit', rand(25, 50));
}
if( $pref == '' && $this->GetGameDataStatic('SpinWinLimit') > 0 )
{
$currentBonusWinChance = 5000;
$currentSpinWinChance = 20;
$this->MaxWin = rand(1, 5);
if( $rtpRange < ($currentPercent - 1) )
{
$this->SetGameDataStatic('SpinWinLimit', 0);
$this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1);
}
}
}
else if( $this->GetGameDataStatic('RtpControlCount') < 0 )
{
if( $currentPercent + rand(1, 2) < $rtpRange && $this->GetGameDataStatic('SpinWinLimit') <= 0 )
{
$this->SetGameDataStatic('SpinWinLimit', rand(25, 50));
}
$this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1);
if( $pref == '' && $this->GetGameDataStatic('SpinWinLimit') > 0 )
{
$currentBonusWinChance = 5000;
$currentSpinWinChance = 20;
$this->MaxWin = rand(1, 5);
if( $rtpRange < ($currentPercent - 1) )
{
$this->SetGameDataStatic('SpinWinLimit', 0);
}
}
if( $this->GetGameDataStatic('RtpControlCount') < (-1 * $RtpControlCount) && $currentPercent - 1 <= $rtpRange && $rtpRange <= ($currentPercent + 2) )
{
$this->SetGameDataStatic('RtpControlCount', $RtpControlCount);
}
}
else
{
$this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1);
}
$bonusWin = rand(1, $currentBonusWinChance);
$spinWin = rand(1, $currentSpinWinChance);
$return = [
'none',
0
];
if( $bonusWin == 1 && $this->slotBonus )
{
$this->isBonusStart = true;
$garantType = 'bonus';
$winLimit = $this->GetBank($garantType);
$return = [
'bonus',
$winLimit
];
if( $this->game->stat_in < ($this->CheckBonusWin() * $bet + $this->game->stat_out) || $winLimit < ($this->CheckBonusWin() * $bet) )
{
$return = [
'none',
0
];
}
}
else if( $spinWin == 1 )
{
$winLimit = $this->GetBank($garantType);
$return = [
'win',
$winLimit
];
}
if( $garantType == 'bet' && $this->GetBalance() <= (2 / $this->CurrentDenom) )
{
$randomPush = rand(1, 10);
if( $randomPush == 1 )
{
$winLimit = $this->GetBank('');
$return = [
'win',
$winLimit
];
}
}
return $return;
}
public function GetRandomScatterPos($rp)
{
$rpResult = [];
for( $i = 0; $i < count($rp); $i++ )
{
if( $rp[$i] == '1' )
{
if( isset($rp[$i + 1]) && isset($rp[$i - 1]) )
{
array_push($rpResult, $i);
}
if( isset($rp[$i + 1]) && isset($rp[$i + 2]) )
{
array_push($rpResult, $i + 1);
}
if( isset($rp[$i - 1]) && isset($rp[$i - 2]) )
{
array_push($rpResult, $i - 1);
}
}
}
shuffle($rpResult);
if( !isset($rpResult[0]) )
{
$rpResult[0] = rand(2, count($rp) - 3);
}
return $rpResult[0];
}
public function GetGambleSettings()
{
$spinWin = rand(1, $this->WinGamble);
return $spinWin;
}
public function GetReelStrips($winType, $slotEvent)
{
$game = $this->game;
if( $slotEvent == 'freespin' )
{
$reel = new GameReel();
$fArr = $reel->reelsStripBonus;
foreach( [
'reelStrip1',
'reelStrip2',
'reelStrip3',
'reelStrip4',
'reelStrip5',
'reelStrip6'
] as $reelStrip )
{
$curReel = array_shift($fArr);
if( count($curReel) )
{
$this->$reelStrip = $curReel;
}
}
}
if( $winType != 'bonus' )
{
$prs = [];
foreach( [
'reelStrip1',
'reelStrip2',
'reelStrip3',
'reelStrip4',
'reelStrip5',
'reelStrip6'
] as $index => $reelStrip )
{
if( is_array($this->$reelStrip) && count($this->$reelStrip) > 0 )
{
$prs[$index + 1] = mt_rand(0, count($this->$reelStrip) - 3);
}
}
}
else
{
$reelsId = [];
foreach( [
'reelStrip1',
'reelStrip2',
'reelStrip3',
'reelStrip4',
'reelStrip5',
'reelStrip6'
] as $index => $reelStrip )
{
if( is_array($this->$reelStrip) && count($this->$reelStrip) > 0 )
{
$prs[$index + 1] = $this->GetRandomScatterPos($this->$reelStrip);
$reelsId[] = $index + 1;
}
}
$scattersCnt = rand(3, count($reelsId));
shuffle($reelsId);
for( $i = 0; $i < count($reelsId); $i++ )
{
if( $i < $scattersCnt )
{
$prs[$reelsId[$i]] = $this->GetRandomScatterPos($this->{'reelStrip' . $reelsId[$i]});
}
else
{
$prs[$reelsId[$i]] = rand(0, count($this->{'reelStrip' . $reelsId[$i]}) - 3);
}
}
}
$reel = [
'rp' => []
];
foreach( $prs as $index => $value )
{
$key = $this->{'reelStrip' . $index};
$cnt = count($key);
$key[-1] = $key[$cnt - 1];
$key[$cnt] = $key[0];
$reel['reel' . $index][0] = $key[$value - 1];
$reel['reel' . $index][1] = $key[$value];
$reel['reel' . $index][2] = $key[$value + 1];
$reel['rp'][] = $value;
}
return $reel;
}
}
}
| 412 | 0.636998 | 1 | 0.636998 | game-dev | MEDIA | 0.589865 | game-dev,web-backend | 0.813259 | 1 | 0.813259 |
klebs6/aloe-rs | 8,588 | aloe-box2d/src/polyshapes1.rs | crate::ix!();
//-------------------------------------------[.cpp/Aloe/examples/DemoRunner/Builds/Android/app/src/main/assets/Box2DTests/PolyShapes.h]
/**
This tests stacking. It also shows how to use
b2World::Query and b2TestOverlap.
*/
pub const k_maxBodies: usize = 256;
pub const POLY_SHAPES_CALLBACK_E_MAXCOUNT: usize = 4;
/**
| This callback is called by
| b2World::QueryAABB. We find all the fixtures
| that overlap an AABB. Of those, we use
| b2TestOverlap to determine which fixtures
| overlap a circle. Up to 4 overlapped fixtures
| will be highlighted with a yellow border.
*/
pub struct PolyShapesCallback {
circle: b2CircleShape,
transform: b2Transform,
debug_draw: *mut b2Draw,
count: i32,
}
impl b2QueryCallback for PolyShapesCallback {
/**
| Called for each fixture found in the
| query AABB.
|
| -----------
| @return
|
| false to terminate the query.
|
*/
fn report_fixture(&mut self, fixture: *mut b2Fixture) -> bool {
todo!();
/*
if (m_count == POLY_SHAPES_CALLBACK_E_MAXCOUNT)
{
return false;
}
b2Body* body = fixture->GetBody();
b2Shape* shape = fixture->GetShape();
bool overlap = b2TestOverlap(shape, 0, &m_circle, 0, body->GetTransform(), m_transform);
if (overlap)
{
DrawFixture(fixture);
++m_count;
}
return true;
*/
}
}
impl Default for PolyShapesCallback {
fn default() -> Self {
todo!();
/*
m_count = 0
*/
}
}
impl PolyShapesCallback {
pub fn draw_fixture(&mut self, fixture: *mut b2Fixture) {
todo!();
/*
b2Color color(0.95f, 0.95f, 0.6f);
const b2Transform& xf = fixture->GetBody()->GetTransform();
switch (fixture->GetType())
{
case b2Shape::e_circle:
{
b2CircleShape* circle = (b2CircleShape*)fixture->GetShape();
b2Vec2 center = b2Mul(xf, circle->m_p);
float32 radius = circle->m_radius;
m_debugDraw->DrawCircle(center, radius, color);
}
break;
case b2Shape::e_polygon:
{
b2PolygonShape* poly = (b2PolygonShape*)fixture->GetShape();
int32 vertexCount = poly->m_vertexCount;
b2Assert(vertexCount <= b2_maxPolygonVertices);
b2Vec2 vertices[b2_maxPolygonVertices];
for (int32 i = 0; i < vertexCount; ++i)
{
vertices[i] = b2Mul(xf, poly->m_vertices[i]);
}
m_debugDraw->DrawPolygon(vertices, vertexCount, color);
}
break;
default:
break;
}
*/
}
}
///---------------------
pub struct PolyShapes {
base: Test,
body_index: i32,
bodies: *mut [b2Body; k_maxBodies],
polygons: [b2PolygonShape; 4],
circle: b2CircleShape,
}
impl Default for PolyShapes {
fn default() -> Self {
todo!();
/*
// Ground body
{
b2BodyDef bd;
b2Body* ground = m_world->CreateBody(&bd);
b2EdgeShape shape;
shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
ground->CreateFixture(&shape, 0.0f);
}
{
b2Vec2 vertices[3];
vertices[0].Set(-0.5f, 0.0f);
vertices[1].Set(0.5f, 0.0f);
vertices[2].Set(0.0f, 1.5f);
m_polygons[0].Set(vertices, 3);
}
{
b2Vec2 vertices[3];
vertices[0].Set(-0.1f, 0.0f);
vertices[1].Set(0.1f, 0.0f);
vertices[2].Set(0.0f, 1.5f);
m_polygons[1].Set(vertices, 3);
}
{
float32 w = 1.0f;
float32 b = w / (2.0f + b2Sqrt(2.0f));
float32 s = b2Sqrt(2.0f) * b;
b2Vec2 vertices[8];
vertices[0].Set(0.5f * s, 0.0f);
vertices[1].Set(0.5f * w, b);
vertices[2].Set(0.5f * w, b + s);
vertices[3].Set(0.5f * s, w);
vertices[4].Set(-0.5f * s, w);
vertices[5].Set(-0.5f * w, b + s);
vertices[6].Set(-0.5f * w, b);
vertices[7].Set(-0.5f * s, 0.0f);
m_polygons[2].Set(vertices, 8);
}
{
m_polygons[3].SetAsBox(0.5f, 0.5f);
}
{
m_circle.m_radius = 0.5f;
}
m_bodyIndex = 0;
memset(m_bodies, 0, sizeof(m_bodies))
*/
}
}
impl PolyShapes {
pub fn create(&mut self, index: i32) {
todo!();
/*
if (m_bodies[m_bodyIndex] != NULL)
{
m_world->DestroyBody(m_bodies[m_bodyIndex]);
m_bodies[m_bodyIndex] = NULL;
}
b2BodyDef bd;
bd.type = b2_dynamicBody;
float32 x = RandomFloat(-2.0f, 2.0f);
bd.position.Set(x, 10.0f);
bd.angle = RandomFloat(-b2_pi, b2_pi);
if (index == 4)
{
bd.angularDamping = 0.02f;
}
m_bodies[m_bodyIndex] = m_world->CreateBody(&bd);
if (index < 4)
{
b2FixtureDef fd;
fd.shape = m_polygons + index;
fd.density = 1.0f;
fd.friction = 0.3f;
m_bodies[m_bodyIndex]->CreateFixture(&fd);
}
else
{
b2FixtureDef fd;
fd.shape = &m_circle;
fd.density = 1.0f;
fd.friction = 0.3f;
m_bodies[m_bodyIndex]->CreateFixture(&fd);
}
m_bodyIndex = (m_bodyIndex + 1) % k_maxBodies;
*/
}
pub fn destroy_body(&mut self) {
todo!();
/*
for (int32 i = 0; i < k_maxBodies; ++i)
{
if (m_bodies[i] != NULL)
{
m_world->DestroyBody(m_bodies[i]);
m_bodies[i] = NULL;
return;
}
}
*/
}
pub fn keyboard(&mut self, key: u8) {
todo!();
/*
switch (key)
{
case '1':
case '2':
case '3':
case '4':
case '5':
Create(key - '1');
break;
case 'a':
for (int32 i = 0; i < k_maxBodies; i += 2)
{
if (m_bodies[i])
{
bool active = m_bodies[i]->IsActive();
m_bodies[i]->SetActive(!active);
}
}
break;
case 'd':
DestroyBody();
break;
}
*/
}
pub fn step(&mut self, settings: *mut Settings) {
todo!();
/*
Test::Step(settings);
PolyShapesCallback callback;
callback.m_circle.m_radius = 2.0f;
callback.m_circle.m_p.Set(0.0f, 1.1f);
callback.m_transform.SetIdentity();
callback.m_debugDraw = &m_debugDraw;
b2AABB aabb;
callback.m_circle.ComputeAABB(&aabb, callback.m_transform, 0);
m_world->QueryAABB(&callback, aabb);
b2Color color(0.4f, 0.7f, 0.8f);
m_debugDraw.DrawCircle(callback.m_circle.m_p, callback.m_circle.m_radius, color);
m_debugDraw.DrawString(5, m_textLine, "Press 1-5 to drop stuff");
m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "Press 'a' to (de)activate some bodies");
m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "Press 'd' to destroy a body");
m_textLine += 15;
*/
}
pub fn create_default() -> *mut Test {
todo!();
/*
return new PolyShapes;
*/
}
}
| 412 | 0.977239 | 1 | 0.977239 | game-dev | MEDIA | 0.797358 | game-dev | 0.972803 | 1 | 0.972803 |
chakra-core/ChakraCore | 6,031 | lib/Backend/SwitchIRBuilder.h | //-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#pragma once
/**
* The object that handles actions generated by a SwitchIRBuilder, which
* will be either an IRBuilder or an IRBuilderAsmJs
*/
struct SwitchAdapter {
virtual void AddBranchInstr(IR::BranchInstr * instr, uint32 offset, uint32 targetOffset, bool clearBackEdge = false) = 0;
virtual void AddInstr(IR::Instr * instr, uint32 offset) = 0;
virtual void CreateRelocRecord(IR::BranchInstr * branchInstr, uint32 offset, uint32 targetOffset, bool clearBackEdge = false) = 0;
virtual void ConvertToBailOut(IR::Instr * instr, IR::BailOutKind kind) = 0;
};
/**
* Handles delegating actions generated by a SwitchIRBuilder to an IRBuilder
*/
struct IRBuilderSwitchAdapter : public SwitchAdapter {
private:
IRBuilder * m_builder;
public:
IRBuilderSwitchAdapter(IRBuilder * builder)
: m_builder(builder) {}
virtual void AddBranchInstr(IR::BranchInstr * instr, uint32 offset, uint32 targetOffset, bool clearBackEdge = false);
virtual void AddInstr(IR::Instr * instr, uint32 offset);
virtual void CreateRelocRecord(IR::BranchInstr * branchInstr, uint32 offset, uint32 targetOffset, bool clearBackEdge = false);
virtual void ConvertToBailOut(IR::Instr * instr, IR::BailOutKind kind);
};
/**
* Handles delegating actions generated by a SwitchIRBuilder to an IRBuilderAsmJs
*/
#ifdef ASMJS_PLAT
struct IRBuilderAsmJsSwitchAdapter : public SwitchAdapter {
private:
IRBuilderAsmJs * m_builder;
public:
IRBuilderAsmJsSwitchAdapter(IRBuilderAsmJs * builder)
: m_builder(builder) {}
virtual void AddBranchInstr(IR::BranchInstr * instr, uint32 offset, uint32 targetOffset, bool clearBackEdge = false);
virtual void AddInstr(IR::Instr * instr, uint32 offset);
virtual void CreateRelocRecord(IR::BranchInstr * branchInstr, uint32 offset, uint32 targetOffset, bool clearBackEdge = false);
virtual void ConvertToBailOut(IR::Instr * instr, IR::BailOutKind kind);
};
#endif
/**
* Handles construction of switch statements, with appropriate optimizations. Note that some of these
* optimizations occur during IR building (rather than GlobOpt) because the abstraction of a switch/case
* block is not maintained with the resulting IR. Thus, some optimizations must occur during this phase.
*/
class SwitchIRBuilder {
private:
typedef JsUtil::List<CaseNode*, JitArenaAllocator> CaseNodeList;
typedef JsUtil::List<JITJavascriptString *, JitArenaAllocator> StrSwitchCaseList;
SwitchAdapter* m_adapter;
Func* m_func;
JitArenaAllocator* m_tempAlloc;
CaseNodeList* m_caseNodes;
bool m_seenOnlySingleCharStrCaseNodes;
IR::Instr * m_profiledSwitchInstr;
bool m_isAsmJs;
bool m_switchOptBuildBail; //bool refers to whether the bail out has to be generated or not
bool m_switchIntDynProfile; // bool refers to whether dynamic profile info says that the switch expression is an integer or not
bool m_switchStrDynProfile; // bool refers to whether dynamic profile info says that the switch expression is a string or not
BVSparse<JitArenaAllocator> * m_intConstSwitchCases;
StrSwitchCaseList * m_strConstSwitchCases;
Js::OpCode m_eqOp;
Js::OpCode m_ltOp;
Js::OpCode m_leOp;
Js::OpCode m_gtOp;
Js::OpCode m_geOp;
Js::OpCode m_subOp;
public:
SwitchIRBuilder(SwitchAdapter * adapter)
: m_adapter(adapter)
, m_profiledSwitchInstr(nullptr)
, m_switchOptBuildBail(false)
, m_switchIntDynProfile(false)
, m_switchStrDynProfile(false)
, m_isAsmJs(false)
, m_seenOnlySingleCharStrCaseNodes(true) {}
void Init(Func * func, JitArenaAllocator * tempAlloc, bool isAsmJs);
void BeginSwitch();
void EndSwitch(uint32 offset, uint32 targetOffset);
void SetProfiledInstruction(IR::Instr * instr, Js::ProfileId profileId);
void OnCase(IR::RegOpnd * src1Opnd, IR::Opnd * src2Opnd, uint32 offset, uint32 targetOffset);
void FlushCases(uint32 targetOffset);
void RefineCaseNodes();
void ResetCaseNodes();
void BuildCaseBrInstr(uint32 targetOffset);
void BuildBinaryTraverseInstr(int start, int end, uint32 defaultLeafBranch);
void BuildLinearTraverseInstr(int start, int end, uint32 defaultLeafBranch);
void BuildEmptyCasesInstr(CaseNode* currCaseNode, uint32 defaultLeafBranch);
void BuildOptimizedIntegerCaseInstrs(uint32 targetOffset);
void BuildMultiBrCaseInstrForStrings(uint32 targetOffset);
void FixUpMultiBrJumpTable(IR::MultiBranchInstr * multiBranchInstr, uint32 targetOffset);
void TryBuildBinaryTreeOrMultiBrForSwitchInts(IR::MultiBranchInstr * &multiBranchInstr, uint32 fallthrOffset,
int startjmpTableIndex, int endjmpTableIndex, int startBinaryTravIndex, uint32 targetOffset);
bool TestAndAddStringCaseConst(JITJavascriptString * str);
void BuildBailOnNotInteger();
void BuildBailOnNotString();
IR::MultiBranchInstr * BuildMultiBrCaseInstrForInts(uint32 start, uint32 end, uint32 targetOffset);
};
| 412 | 0.766013 | 1 | 0.766013 | game-dev | MEDIA | 0.249001 | game-dev | 0.688217 | 1 | 0.688217 |
nathtest/UProjOblivionRemastered | 1,210 | Source/Altar/Public/NiGeomMorpherController.h | #pragma once
#include "CoreMinimal.h"
#include "NiInterpController.h"
#include "NiGeomMorpherController.generated.h"
class UMorphWeight;
class UNiInterpolator;
class UNiMorphData;
UCLASS(Blueprintable)
class ALTAR_API UNiGeomMorpherController : public UNiInterpController {
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, meta=(AllowPrivateAccess=true))
int64 MorpherFlags;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
UNiMorphData* Data;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
uint8 AlwaysUpdate;
UPROPERTY(EditAnywhere, meta=(AllowPrivateAccess=true))
int64 NumInterpolators;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
TArray<UNiInterpolator*> Interpolators;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
TArray<UMorphWeight*> InterpolatorWeights;
UPROPERTY(EditAnywhere, meta=(AllowPrivateAccess=true))
int64 NumUnknownInts;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
TArray<int32> UnknownInts;
UNiGeomMorpherController();
};
| 412 | 0.888391 | 1 | 0.888391 | game-dev | MEDIA | 0.673952 | game-dev | 0.508154 | 1 | 0.508154 |
tankyc/sango_infinity | 2,194 | Project/Assets/Scripts/Extensions/OwnRuntimeTransformGizmos/Editor/VolumeScaleGizmoInspectorGUI.cs | #if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
namespace RTEditor
{
[CustomEditor(typeof(VolumeScaleGizmo))]
public class VolumeScaleGizmoInspectorGUI : GizmoInspectorGUIBase
{
private static bool _keyMappingsAreVisible = true;
private VolumeScaleGizmo _volumeScaleGizmo;
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
EditorGUILayout.BeginVertical("Box");
Color newColor = EditorGUILayout.ColorField("Line Color", _volumeScaleGizmo.LineColor);
if(newColor != _volumeScaleGizmo.LineColor)
{
UnityEditorUndoHelper.RecordObjectForInspectorPropertyChange(_volumeScaleGizmo);
_volumeScaleGizmo.LineColor = newColor;
}
int newInt = EditorGUILayout.IntField("Drag Handle Size (in pixels)", _volumeScaleGizmo.DragHandleSizeInPixels);
if(newInt != _volumeScaleGizmo.DragHandleSizeInPixels)
{
UnityEditorUndoHelper.RecordObjectForInspectorPropertyChange(_volumeScaleGizmo);
_volumeScaleGizmo.DragHandleSizeInPixels = newInt;
}
EditorGUILayout.Separator();
float newFloat = EditorGUILayout.FloatField("Snap Step (In World Units)", _volumeScaleGizmo.SnapStepInWorldUnits);
if (newFloat != _volumeScaleGizmo.SnapStepInWorldUnits)
{
UnityEditorUndoHelper.RecordObjectForInspectorPropertyChange(_volumeScaleGizmo);
_volumeScaleGizmo.SnapStepInWorldUnits = newFloat;
}
EditorGUILayout.EndVertical();
_keyMappingsAreVisible = EditorGUILayout.Foldout(_keyMappingsAreVisible, "Key mappings");
if (_keyMappingsAreVisible)
{
_volumeScaleGizmo.EnableScaleFromCenterShortcut.RenderView(_volumeScaleGizmo);
_volumeScaleGizmo.EnableStepSnappingShortcut.RenderView(_volumeScaleGizmo);
}
}
protected override void OnEnable()
{
base.OnEnable();
_volumeScaleGizmo = target as VolumeScaleGizmo;
}
}
}
#endif | 412 | 0.71251 | 1 | 0.71251 | game-dev | MEDIA | 0.462275 | game-dev,desktop-app | 0.853521 | 1 | 0.853521 |
SceneView/sceneform-android | 2,132 | core/src/main/java/com/google/ar/sceneform/rendering/CleanupRegistry.java | package com.google.ar.sceneform.rendering;
import com.google.ar.sceneform.resources.ResourceHolder;
import java.lang.ref.ReferenceQueue;
import java.util.HashSet;
import java.util.Iterator;
/**
* Maintains a {@link ReferenceQueue} and executes a {@link Runnable} after each object in the queue
* is garbage collected.
*/
public class CleanupRegistry<T> implements ResourceHolder {
private final java.util.HashSet<CleanupItem<T>> cleanupItemHashSet;
private final ReferenceQueue<T> referenceQueue;
public CleanupRegistry() {
this(new HashSet<>(), new ReferenceQueue<>());
}
public CleanupRegistry(
java.util.HashSet<CleanupItem<T>> cleanupItemHashSet, ReferenceQueue<T> referenceQueue) {
this.cleanupItemHashSet = cleanupItemHashSet;
this.referenceQueue = referenceQueue;
}
/**
* Adds {@code trackedOBject} to the {@link ReferenceQueue}.
*
* @param trackedObject The target to be tracked.
* @param cleanupCallback Will be called after {@code trackedOBject} is disposed.
*/
public void register(T trackedObject, Runnable cleanupCallback) {
cleanupItemHashSet.add(new CleanupItem<T>(trackedObject, referenceQueue, cleanupCallback));
}
/**
* Polls the {@link ReferenceQueue} for garbage collected objects and runs the associated {@link
* Runnable}
*
* @return count of resources remaining.
*/
@Override
@SuppressWarnings("unchecked") // safe cast from Reference to a CleanupItem
public long reclaimReleasedResources() {
CleanupItem<T> ref = (CleanupItem<T>) referenceQueue.poll();
while (ref != null) {
if (cleanupItemHashSet.contains(ref)) {
ref.run();
cleanupItemHashSet.remove(ref);
}
ref = (CleanupItem<T>) referenceQueue.poll();
}
return cleanupItemHashSet.size();
}
/** Ignores reference count and releases any associated resources */
@Override
public void destroyAllResources() {
Iterator<CleanupItem<T>> iterator = cleanupItemHashSet.iterator();
while (iterator.hasNext()) {
CleanupItem<T> ref = iterator.next();
iterator.remove();
ref.run();
}
}
}
| 412 | 0.935393 | 1 | 0.935393 | game-dev | MEDIA | 0.537906 | game-dev | 0.790637 | 1 | 0.790637 |
egret-labs/egret-game-library | 5,614 | physics/featuresDemo/src/scene/HeightfieldScene.ts | class HeightfieldScene extends egret.DisplayObjectContainer {
public constructor() {
super();
this.once(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
}
private onAddToStage(): void {
this.createGameScene();
}
private world: p2.World;
private debugDraw: p2DebugDraw;
private dragHelper:DragHelper;
private createGameScene(): void {
this.init();
this.createDebug();
this.addEventListener(egret.Event.ENTER_FRAME, this.loop, this);
}
private init(){
var world = new p2.World({
gravity : [0,-10]
});
this.world = world;
(<p2.GSSolver>world.solver).tolerance = 0.01;
// Set large friction - needed for powerful vehicle engine!
world.defaultContactMaterial.friction = 10;
// Create ground
var data = [];
var numDataPoints = 200;
for(var i=0; i<numDataPoints; i++){
data.push(0.5*Math.cos(0.2*i) * Math.sin(0.5*i) + 0.6*Math.sin(0.1*i) * Math.sin(0.05*i));
}
var heightfieldShape = new p2.Heightfield({
heights: data,
elementWidth: 1
});
var heightfield = new p2.Body({
position:[-10,-1]
});
heightfield.addShape(heightfieldShape);
world.addBody(heightfield);
// Create chassis
var chassisBody = new p2.Body({ mass : 1, position:[-4,1] }),
chassisShape = new p2.Box({ width: 1, height: 0.5 });
chassisBody.addShape(chassisShape);
world.addBody(chassisBody);
// Create wheels
var wheelBody1 = new p2.Body({ mass : 1, position:[chassisBody.position[0] - 0.5,0.7] }),
wheelBody2 = new p2.Body({ mass : 1, position:[chassisBody.position[0] + 0.5,0.7] }),
wheelShapeLeft = new p2.Circle({ radius: 0.3 }),
wheelShapeRight = new p2.Circle({ radius: 0.3 });
wheelBody1.addShape(wheelShapeLeft);
wheelBody2.addShape(wheelShapeRight);
world.addBody(wheelBody1);
world.addBody(wheelBody2);
// Disable collisions between chassis and wheels
var WHEELS = 1, // Define bits for each shape type
CHASSIS = 2,
GROUND = 4,
OTHER = 8;
wheelShapeLeft.collisionGroup = wheelShapeRight.collisionGroup = WHEELS; // Assign groups
chassisShape.collisionGroup = CHASSIS;
heightfieldShape .collisionGroup = GROUND;
wheelShapeLeft.collisionMask = wheelShapeRight.collisionMask = GROUND | OTHER; // Wheels can only collide with ground
chassisShape.collisionMask = GROUND | OTHER; // Chassis can only collide with ground
heightfieldShape.collisionMask = WHEELS | CHASSIS | OTHER; // Ground can collide with wheels and chassis
// Constrain wheels to chassis
var c1 = new p2.PrismaticConstraint(chassisBody,wheelBody1,{
localAnchorA : [-0.5,-0.3],
localAnchorB : [0,0],
localAxisA : [0,1],
disableRotationalLock : true,
});
var c2 = new p2.PrismaticConstraint(chassisBody,wheelBody2,{
localAnchorA : [ 0.5,-0.3],
localAnchorB : [0,0],
localAxisA : [0,1],
disableRotationalLock : true,
});
c1.setLimits(-0.4, 0.2);
c2.setLimits(-0.4, 0.2);
world.addConstraint(c1);
world.addConstraint(c2);
// Add springs for the suspension
var stiffness = 100,
damping = 5,
restLength = 0.5;
// Left spring
world.addSpring(new p2.LinearSpring(chassisBody, wheelBody1, {
restLength : restLength,
stiffness : stiffness,
damping : damping,
localAnchorA : [-0.5,0],
localAnchorB : [0,0],
}));
// Right spring
world.addSpring(new p2.LinearSpring(chassisBody, wheelBody2, {
restLength : restLength,
stiffness : stiffness,
damping : damping,
localAnchorA : [0.5,0],
localAnchorB : [0,0],
}));
// Apply current engine torque after each step
var torque = 0;
world.on("postStep",function(evt){
wheelBody1.angularForce += torque;
wheelBody2.angularForce += torque;
});
// Change the current engine torque with the left/right keys
document.addEventListener("keydown",function(evt:KeyboardEvent){
var t = 5;
switch(evt.keyCode){
case 39: // right
torque = -t;
break;
case 37: // left
torque = t;
break;
}
});
document.addEventListener("keyup",function(){
torque = 0;
});
world.on("addBody",function(evt){
evt.body.setDensity(1);
});
}
private loop(): void {
this.world.step(1 / 60);
this.debugDraw.drawDebug();
}
private createDebug(): void {
//创建调试试图
this.debugDraw = new p2DebugDraw(this.world);
var sprite: egret.Sprite = new egret.Sprite();
this.addChild(sprite);
this.debugDraw.setSprite(sprite);
this.debugDraw.setLineWidth(0.02);
sprite.x = this.stage.stageWidth/2;
sprite.y = this.stage.stageHeight/2;
sprite.scaleX = 50;
sprite.scaleY = -50;
this.dragHelper = new DragHelper(this.stage, sprite, this.world);
}
} | 412 | 0.826939 | 1 | 0.826939 | game-dev | MEDIA | 0.849633 | game-dev | 0.987853 | 1 | 0.987853 |
CrazyVince/Hacking | 2,775 | Library/PackageCache/com.unity.visualscripting@1.8.0/Runtime/VisualScripting.Core/Graphs/GraphsExceptionUtility.cs | using System;
using System.Collections.Generic;
using UnityEngine;
namespace Unity.VisualScripting
{
public static class GraphsExceptionUtility
{
// Note: Checking hasDebugData here instead of enableDebug,
// because we always want exceptions to register, even if
// background debug is disabled.
private const string handledKey = "Bolt.Core.Handled";
public static Exception GetException(this IGraphElementWithDebugData element, GraphPointer pointer)
{
if (!pointer.hasDebugData)
{
return null;
}
var debugData = pointer.GetElementDebugData<IGraphElementDebugData>(element);
return debugData.runtimeException;
}
public static void SetException(this IGraphElementWithDebugData element, GraphPointer pointer, Exception ex)
{
if (!pointer.hasDebugData)
{
return;
}
var debugData = pointer.GetElementDebugData<IGraphElementDebugData>(element);
debugData.runtimeException = ex;
}
public static void HandleException(this IGraphElementWithDebugData element, GraphPointer pointer, Exception ex)
{
Ensure.That(nameof(ex)).IsNotNull(ex);
if (pointer == null)
{
Debug.LogError("Caught exception with null graph pointer (flow was likely disposed):\n" + ex);
return;
}
var reference = pointer.AsReference();
if (!ex.HandledIn(reference))
{
element.SetException(pointer, ex);
}
while (reference.isChild)
{
var parentElement = reference.parentElement;
reference = reference.ParentReference(true);
if (parentElement is IGraphElementWithDebugData debuggableParentElement)
{
if (!ex.HandledIn(reference))
{
debuggableParentElement.SetException(reference, ex);
}
}
}
}
private static bool HandledIn(this Exception ex, GraphReference reference)
{
Ensure.That(nameof(ex)).IsNotNull(ex);
if (!ex.Data.Contains(handledKey))
{
ex.Data.Add(handledKey, new HashSet<GraphReference>());
}
var handled = (HashSet<GraphReference>)ex.Data[handledKey];
if (handled.Contains(reference))
{
return true;
}
else
{
handled.Add(reference);
return false;
}
}
}
}
| 412 | 0.786339 | 1 | 0.786339 | game-dev | MEDIA | 0.528288 | game-dev | 0.733283 | 1 | 0.733283 |
DanielEverland/ScriptableObject-Architecture | 5,066 | Assets/SO Architecture/Editor/Inspectors/BaseVariableEditor.cs | using UnityEngine;
using UnityEditor;
using UnityEditor.AnimatedValues;
namespace ScriptableObjectArchitecture.Editor
{
[CustomEditor(typeof(BaseVariable<>), true)]
public class BaseVariableEditor : UnityEditor.Editor
{
private BaseVariable Target { get { return (BaseVariable)target; } }
protected bool IsClampable { get { return Target.Clampable; } }
protected bool IsClamped { get { return Target.IsClamped; } }
private SerializedProperty _valueProperty;
private SerializedProperty _readOnly;
private SerializedProperty _raiseWarning;
private SerializedProperty _isClamped;
private SerializedProperty _minValueProperty;
private SerializedProperty _maxValueProperty;
private SerializedProperty _defaultValueProperty;
private SerializedProperty _useDefaultProperty;
private AnimBool _useDefaultValueAnimation;
private AnimBool _raiseWarningAnimation;
private AnimBool _isClampedVariableAnimation;
private const string READONLY_TOOLTIP = "Should this value be changable during runtime? Will still be editable in the inspector regardless";
protected virtual void OnEnable()
{
_valueProperty = serializedObject.FindProperty("_value");
_readOnly = serializedObject.FindProperty("_readOnly");
_raiseWarning = serializedObject.FindProperty("_raiseWarning");
_isClamped = serializedObject.FindProperty("_isClamped");
_minValueProperty = serializedObject.FindProperty("_minClampedValue");
_maxValueProperty = serializedObject.FindProperty("_maxClampedValue");
_defaultValueProperty = serializedObject.FindProperty("_defaultValue");
_useDefaultProperty = serializedObject.FindProperty("_useDefaultValue");
_useDefaultValueAnimation = new AnimBool(_useDefaultProperty.boolValue);
_useDefaultValueAnimation.valueChanged.AddListener(Repaint);
_raiseWarningAnimation = new AnimBool(_readOnly.boolValue);
_raiseWarningAnimation.valueChanged.AddListener(Repaint);
_isClampedVariableAnimation = new AnimBool(_isClamped.boolValue);
_isClampedVariableAnimation.valueChanged.AddListener(Repaint);
}
public override void OnInspectorGUI()
{
serializedObject.Update();
DrawValue();
EditorGUILayout.Space();
DrawClampedFields();
DrawReadonlyField();
}
protected virtual void DrawValue()
{
GenericPropertyDrawer.DrawPropertyDrawerLayout(_valueProperty, Target.Type);
EditorGUILayout.PropertyField(_useDefaultProperty);
_useDefaultValueAnimation.target = _useDefaultProperty.boolValue;
using (var anim = new EditorGUILayout.FadeGroupScope(_useDefaultValueAnimation.faded))
{
if (anim.visible)
{
using (new EditorGUI.IndentLevelScope())
{
GenericPropertyDrawer.DrawPropertyDrawerLayout(_defaultValueProperty, Target.ReferenceType);
}
}
}
}
protected void DrawClampedFields()
{
if (!IsClampable)
return;
EditorGUILayout.PropertyField(_isClamped);
_isClampedVariableAnimation.target = _isClamped.boolValue;
using (var anim = new EditorGUILayout.FadeGroupScope(_isClampedVariableAnimation.faded))
{
if(anim.visible)
{
using (new EditorGUI.IndentLevelScope())
{
EditorGUILayout.PropertyField(_minValueProperty);
EditorGUILayout.PropertyField(_maxValueProperty);
}
}
}
}
protected void DrawReadonlyField()
{
if (_isClamped.boolValue)
return;
EditorGUILayout.PropertyField(_readOnly, new GUIContent("Read Only", READONLY_TOOLTIP));
_raiseWarningAnimation.target = _readOnly.boolValue;
using (var fadeGroup = new EditorGUILayout.FadeGroupScope(_raiseWarningAnimation.faded))
{
if (fadeGroup.visible)
{
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(_raiseWarning);
EditorGUI.indentLevel--;
}
}
}
}
[CustomEditor(typeof(BaseVariable<,>), true)]
public class BaseVariableWithEventEditor : BaseVariableEditor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
EditorGUILayout.Space();
EditorGUILayout.PropertyField(serializedObject.FindProperty("_event"));
serializedObject.ApplyModifiedProperties();
}
}
} | 412 | 0.794804 | 1 | 0.794804 | game-dev | MEDIA | 0.870228 | game-dev | 0.873533 | 1 | 0.873533 |
Xiao-MoMi/Custom-Fishing | 1,811 | compatibility/src/main/java/net/momirealms/customfishing/bukkit/integration/item/ZaphkielItemProvider.java | /*
* Copyright (C) <2024> <XiaoMoMi>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customfishing.bukkit.integration.item;
import ink.ptms.zaphkiel.ZapAPI;
import ink.ptms.zaphkiel.Zaphkiel;
import net.momirealms.customfishing.api.integration.ItemProvider;
import net.momirealms.customfishing.api.mechanic.context.Context;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import java.util.Objects;
public class ZaphkielItemProvider implements ItemProvider {
private final ZapAPI zapAPI;
public ZaphkielItemProvider() {
this.zapAPI = Zaphkiel.INSTANCE.api();
}
@Override
public String identifier() {
return "Zaphkiel";
}
@NotNull
@Override
public ItemStack buildItem(@NotNull Context<Player> player, @NotNull String id) {
return Objects.requireNonNull(zapAPI.getItemManager().generateItemStack(id, player.holder()));
}
@Override
public String itemID(@NotNull ItemStack itemStack) {
if (itemStack.getType() == Material.AIR) return null;
return zapAPI.getItemHandler().getItemId(itemStack);
}
}
| 412 | 0.540089 | 1 | 0.540089 | game-dev | MEDIA | 0.980567 | game-dev | 0.517739 | 1 | 0.517739 |
ArchipelagoMW/Archipelago | 25,555 | worlds/ladx/LADXR/roomEditor.py | import json
from . import entityData
WARP_TYPE_IDS = {0xE1, 0xE2, 0xE3, 0xBA, 0xA8, 0xBE, 0xCB, 0xC2, 0xC6}
ALT_ROOM_OVERLAYS = {"Alt06": 0x1040, "Alt0E": 0x1090, "Alt1B": 0x10E0, "Alt2B": 0x1130, "Alt79": 0x1180, "Alt8C": 0x11D0}
class RoomEditor:
def __init__(self, rom, room=None):
assert room is not None
self.room = room
self.entities = []
self.objects = []
self.tileset_index = None
self.palette_index = None
self.attribset = None
if isinstance(room, int):
entities_raw = rom.entities[room]
idx = 0
while entities_raw[idx] != 0xFF:
x = entities_raw[idx] & 0x0F
y = entities_raw[idx] >> 4
id = entities_raw[idx + 1]
self.entities.append((x, y, id))
idx += 2
assert idx == len(entities_raw) - 1
if isinstance(room, str):
if room in rom.rooms_overworld_top:
objects_raw = rom.rooms_overworld_top[room]
elif room in rom.rooms_overworld_bottom:
objects_raw = rom.rooms_overworld_bottom[room]
elif room in rom.rooms_indoor_a:
objects_raw = rom.rooms_indoor_a[room]
else:
assert False, "Failed to find alt room: %s" % (room)
else:
if room < 0x080:
objects_raw = rom.rooms_overworld_top[room]
elif room < 0x100:
objects_raw = rom.rooms_overworld_bottom[room - 0x80]
elif room < 0x200:
objects_raw = rom.rooms_indoor_a[room - 0x100]
elif room < 0x300:
objects_raw = rom.rooms_indoor_b[room - 0x200]
else:
objects_raw = rom.rooms_color_dungeon[room - 0x300]
self.animation_id = objects_raw[0]
self.floor_object = objects_raw[1]
idx = 2
while objects_raw[idx] != 0xFE:
x = objects_raw[idx] & 0x0F
y = objects_raw[idx] >> 4
if y == 0x08: # horizontal
count = x
x = objects_raw[idx + 1] & 0x0F
y = objects_raw[idx + 1] >> 4
self.objects.append(ObjectHorizontal(x, y, objects_raw[idx + 2], count))
idx += 3
elif y == 0x0C: # vertical
count = x
x = objects_raw[idx + 1] & 0x0F
y = objects_raw[idx + 1] >> 4
self.objects.append(ObjectVertical(x, y, objects_raw[idx + 2], count))
idx += 3
elif y == 0x0E: # warp
self.objects.append(ObjectWarp(objects_raw[idx] & 0x0F, objects_raw[idx + 1], objects_raw[idx + 2], objects_raw[idx + 3], objects_raw[idx + 4]))
idx += 5
else:
self.objects.append(Object(x, y, objects_raw[idx + 1]))
idx += 2
if room is not None:
assert idx == len(objects_raw) - 1
if isinstance(room, int) and room < 0x0CC:
self.overlay = rom.banks[0x26][room * 80:room * 80+80]
elif isinstance(room, int) and room < 0x100:
self.overlay = rom.banks[0x27][(room - 0xCC) * 80:(room - 0xCC) * 80 + 80]
elif room in ALT_ROOM_OVERLAYS:
self.overlay = rom.banks[0x27][ALT_ROOM_OVERLAYS[room]:ALT_ROOM_OVERLAYS[room] + 80]
else:
self.overlay = None
def store(self, rom, new_room_nr=None):
if new_room_nr is None:
new_room_nr = self.room
objects_raw = bytearray([self.animation_id, self.floor_object])
for obj in self.objects:
objects_raw += obj.export()
objects_raw += bytearray([0xFE])
if isinstance(new_room_nr, str):
if new_room_nr in rom.rooms_overworld_top:
rom.rooms_overworld_top[new_room_nr] = objects_raw
elif new_room_nr in rom.rooms_overworld_bottom:
rom.rooms_overworld_bottom[new_room_nr] = objects_raw
elif new_room_nr in rom.rooms_indoor_a:
rom.rooms_indoor_a[new_room_nr] = objects_raw
else:
assert False, "Failed to find alt room: %s" % (new_room_nr)
elif new_room_nr < 0x080:
rom.rooms_overworld_top[new_room_nr] = objects_raw
elif new_room_nr < 0x100:
rom.rooms_overworld_bottom[new_room_nr - 0x80] = objects_raw
elif new_room_nr < 0x200:
rom.rooms_indoor_a[new_room_nr - 0x100] = objects_raw
elif new_room_nr < 0x300:
rom.rooms_indoor_b[new_room_nr - 0x200] = objects_raw
else:
rom.rooms_color_dungeon[new_room_nr - 0x300] = objects_raw
if isinstance(new_room_nr, int) and new_room_nr < 0x100:
if self.tileset_index is not None:
rom.banks[0x3F][0x3F00 + new_room_nr] = self.tileset_index & 0xFF
if self.attribset is not None:
# With a tileset, comes metatile gbc data that we need to store a proper bank+pointer.
rom.banks[0x1A][0x2476 + new_room_nr] = self.attribset[0]
rom.banks[0x1A][0x1E76 + new_room_nr*2] = self.attribset[1] & 0xFF
rom.banks[0x1A][0x1E76 + new_room_nr*2+1] = self.attribset[1] >> 8
if self.palette_index is not None:
rom.banks[0x21][0x02ef + new_room_nr] = self.palette_index
if isinstance(new_room_nr, int):
entities_raw = bytearray()
for entity in self.entities:
entities_raw += bytearray([entity[0] | entity[1] << 4, entity[2]])
entities_raw += bytearray([0xFF])
rom.entities[new_room_nr] = entities_raw
if new_room_nr < 0x0CC:
rom.banks[0x26][new_room_nr * 80:new_room_nr * 80 + 80] = self.overlay
elif new_room_nr < 0x100:
rom.banks[0x27][(new_room_nr - 0xCC) * 80:(new_room_nr - 0xCC) * 80 + 80] = self.overlay
elif new_room_nr in ALT_ROOM_OVERLAYS:
rom.banks[0x27][ALT_ROOM_OVERLAYS[new_room_nr]:ALT_ROOM_OVERLAYS[new_room_nr] + 80] = self.overlay
def addEntity(self, x, y, type_id):
self.entities.append((x, y, type_id))
def removeEntities(self, type_id):
self.entities = list(filter(lambda e: e[2] != type_id, self.entities))
def hasEntity(self, type_id):
return any(map(lambda e: e[2] == type_id, self.entities))
def changeObject(self, x, y, new_type):
for obj in self.objects:
if obj.x == x and obj.y == y:
obj.type_id = new_type
if self.overlay is not None:
self.overlay[x + y * 10] = new_type
def removeObject(self, x, y):
self.objects = list(filter(lambda obj: obj.x != x or obj.y != y, self.objects))
def moveObject(self, x, y, new_x, new_y):
for obj in self.objects:
if obj.x == x and obj.y == y:
if self.overlay is not None:
self.overlay[x + y * 10] = self.floor_object
self.overlay[new_x + new_y * 10] = obj.type_id
obj.x = new_x
obj.y = new_y
def getWarps(self):
return list(filter(lambda obj: isinstance(obj, ObjectWarp), self.objects))
def updateOverlay(self, preserve_floor=False):
if self.overlay is None:
return
if not preserve_floor:
for n in range(80):
self.overlay[n] = self.floor_object
for obj in self.objects:
if isinstance(obj, ObjectHorizontal):
for n in range(obj.count):
self.overlay[obj.x + n + obj.y * 10] = obj.type_id
elif isinstance(obj, ObjectVertical):
for n in range(obj.count):
self.overlay[obj.x + n * 10 + obj.y * 10] = obj.type_id
elif not isinstance(obj, ObjectWarp):
self.overlay[obj.x + obj.y * 10] = obj.type_id
def loadFromJson(self, filename):
self.objects = []
self.entities = []
self.animation_id = 0
self.tileset_index = 0x0F
self.palette_index = 0x01
data = json.load(open(filename))
for prop in data.get("properties", []):
if prop["name"] == "palette":
self.palette_index = int(prop["value"], 16)
elif prop["name"] == "tileset":
self.tileset_index = int(prop["value"], 16)
elif prop["name"] == "animationset":
self.animation_id = int(prop["value"], 16)
elif prop["name"] == "attribset":
bank, _, addr = prop["value"].partition(":")
self.attribset = (int(bank, 16), int(addr, 16) + 0x4000)
tiles = [0] * 80
for layer in data["layers"]:
if "data" in layer:
for n in range(80):
if layer["data"][n] > 0:
tiles[n] = (layer["data"][n] - 1) & 0xFF
if "objects" in layer:
for obj in layer["objects"]:
x = int((obj["x"] + obj["width"] / 2) // 16)
y = int((obj["y"] + obj["height"] / 2) // 16)
if obj["type"] == "warp":
warp_type, map_nr, room, x, y = obj["name"].split(":")
self.objects.append(ObjectWarp(int(warp_type), int(map_nr, 16), int(room, 16) & 0xFF, int(x, 16), int(y, 16)))
elif obj["type"] == "entity":
type_id = entityData.NAME.index(obj["name"])
self.addEntity(x, y, type_id)
elif obj["type"] == "hidden_tile":
self.objects.append(Object(x, y, int(obj["name"], 16)))
self.buildObjectList(tiles, reduce_size=True)
return data
def getTileArray(self):
if self.room < 0x100:
tiles = [self.floor_object] * 80
else:
tiles = [self.floor_object & 0x0F] * 80
def objHSize(type_id):
if type_id == 0xF5:
return 2
return 1
def objVSize(type_id):
if type_id == 0xF5:
return 2
return 1
def getObject(x, y):
x, y = (x & 15), (y & 15)
if x < 10 and y < 8:
return tiles[x + y * 10]
return 0
if self.room < 0x100:
def placeObject(x, y, type_id):
if type_id == 0xF5:
if getObject(x, y) in (0x1B, 0x28, 0x29, 0x83, 0x90):
placeObject(x, y, 0x29)
else:
placeObject(x, y, 0x25)
if getObject(x + 1, y) in (0x1B, 0x27, 0x82, 0x86, 0x8A, 0x90, 0x2A):
placeObject(x + 1, y, 0x2A)
else:
placeObject(x + 1, y, 0x26)
if getObject(x, y + 1) in (0x26, 0x2A):
placeObject(x, y + 1, 0x2A)
elif getObject(x, y + 1) == 0x90:
placeObject(x, y + 1, 0x82)
else:
placeObject(x, y + 1, 0x27)
if getObject(x + 1, y + 1) in (0x25, 0x29):
placeObject(x + 1, y + 1, 0x29)
elif getObject(x + 1, y + 1) == 0x90:
placeObject(x + 1, y + 1, 0x83)
else:
placeObject(x + 1, y + 1, 0x28)
elif type_id == 0xF6: # two door house
placeObject(x + 0, y, 0x55)
placeObject(x + 1, y, 0x5A)
placeObject(x + 2, y, 0x5A)
placeObject(x + 3, y, 0x5A)
placeObject(x + 4, y, 0x56)
placeObject(x + 0, y + 1, 0x57)
placeObject(x + 1, y + 1, 0x59)
placeObject(x + 2, y + 1, 0x59)
placeObject(x + 3, y + 1, 0x59)
placeObject(x + 4, y + 1, 0x58)
placeObject(x + 0, y + 2, 0x5B)
placeObject(x + 1, y + 2, 0xE2)
placeObject(x + 2, y + 2, 0x5B)
placeObject(x + 3, y + 2, 0xE2)
placeObject(x + 4, y + 2, 0x5B)
elif type_id == 0xF7: # large house
placeObject(x + 0, y, 0x55)
placeObject(x + 1, y, 0x5A)
placeObject(x + 2, y, 0x56)
placeObject(x + 0, y + 1, 0x57)
placeObject(x + 1, y + 1, 0x59)
placeObject(x + 2, y + 1, 0x58)
placeObject(x + 0, y + 2, 0x5B)
placeObject(x + 1, y + 2, 0xE2)
placeObject(x + 2, y + 2, 0x5B)
elif type_id == 0xF8: # catfish
placeObject(x + 0, y, 0xB6)
placeObject(x + 1, y, 0xB7)
placeObject(x + 2, y, 0x66)
placeObject(x + 0, y + 1, 0x67)
placeObject(x + 1, y + 1, 0xE3)
placeObject(x + 2, y + 1, 0x68)
elif type_id == 0xF9: # palace door
placeObject(x + 0, y, 0xA4)
placeObject(x + 1, y, 0xA5)
placeObject(x + 2, y, 0xA6)
placeObject(x + 0, y + 1, 0xA7)
placeObject(x + 1, y + 1, 0xE3)
placeObject(x + 2, y + 1, 0xA8)
elif type_id == 0xFA: # stone pig head
placeObject(x + 0, y, 0xBB)
placeObject(x + 1, y, 0xBC)
placeObject(x + 0, y + 1, 0xBD)
placeObject(x + 1, y + 1, 0xBE)
elif type_id == 0xFB: # palmtree
if x == 15:
placeObject(x + 1, y + 1, 0xB7)
placeObject(x + 1, y + 2, 0xCE)
else:
placeObject(x + 0, y, 0xB6)
placeObject(x + 0, y + 1, 0xCD)
placeObject(x + 1, y + 0, 0xB7)
placeObject(x + 1, y + 1, 0xCE)
elif type_id == 0xFC: # square "hill with hole" (seen near lvl4 entrance)
placeObject(x + 0, y, 0x2B)
placeObject(x + 1, y, 0x2C)
placeObject(x + 2, y, 0x2D)
placeObject(x + 0, y + 1, 0x37)
placeObject(x + 1, y + 1, 0xE8)
placeObject(x + 2, y + 1, 0x38)
placeObject(x - 1, y + 2, 0x0A)
placeObject(x + 0, y + 2, 0x33)
placeObject(x + 1, y + 2, 0x2F)
placeObject(x + 2, y + 2, 0x34)
placeObject(x + 0, y + 3, 0x0A)
placeObject(x + 1, y + 3, 0x0A)
placeObject(x + 2, y + 3, 0x0A)
placeObject(x + 3, y + 3, 0x0A)
elif type_id == 0xFD: # small house
placeObject(x + 0, y, 0x52)
placeObject(x + 1, y, 0x52)
placeObject(x + 2, y, 0x52)
placeObject(x + 0, y + 1, 0x5B)
placeObject(x + 1, y + 1, 0xE2)
placeObject(x + 2, y + 1, 0x5B)
else:
x, y = (x & 15), (y & 15)
if x < 10 and y < 8:
tiles[x + y * 10] = type_id
else:
def placeObject(x, y, type_id):
x, y = (x & 15), (y & 15)
if type_id == 0xEC: # key door
placeObject(x, y, 0x2D)
placeObject(x + 1, y, 0x2E)
elif type_id == 0xED:
placeObject(x, y, 0x2F)
placeObject(x + 1, y, 0x30)
elif type_id == 0xEE:
placeObject(x, y, 0x31)
placeObject(x, y + 1, 0x32)
elif type_id == 0xEF:
placeObject(x, y, 0x33)
placeObject(x, y + 1, 0x34)
elif type_id == 0xF0: # closed door
placeObject(x, y, 0x35)
placeObject(x + 1, y, 0x36)
elif type_id == 0xF1:
placeObject(x, y, 0x37)
placeObject(x + 1, y, 0x38)
elif type_id == 0xF2:
placeObject(x, y, 0x39)
placeObject(x, y + 1, 0x3A)
elif type_id == 0xF3:
placeObject(x, y, 0x3B)
placeObject(x, y + 1, 0x3C)
elif type_id == 0xF4: # open door
placeObject(x, y, 0x43)
placeObject(x + 1, y, 0x44)
elif type_id == 0xF5:
placeObject(x, y, 0x8C)
placeObject(x + 1, y, 0x08)
elif type_id == 0xF6:
placeObject(x, y, 0x09)
placeObject(x, y + 1, 0x0A)
elif type_id == 0xF7:
placeObject(x, y, 0x0B)
placeObject(x, y + 1, 0x0C)
elif type_id == 0xF8: # boss door
placeObject(x, y, 0xA4)
placeObject(x + 1, y, 0xA5)
elif type_id == 0xF9: # stairs door
placeObject(x, y, 0xAF)
placeObject(x + 1, y, 0xB0)
elif type_id == 0xFA: # flipwall
placeObject(x, y, 0xB1)
placeObject(x + 1, y, 0xB2)
elif type_id == 0xFB: # one way arrow
placeObject(x, y, 0x45)
placeObject(x + 1, y, 0x46)
elif type_id == 0xFC: # entrance
placeObject(x + 0, y, 0xB3)
placeObject(x + 1, y, 0xB4)
placeObject(x + 2, y, 0xB4)
placeObject(x + 3, y, 0xB5)
placeObject(x + 0, y + 1, 0xB6)
placeObject(x + 1, y + 1, 0xB7)
placeObject(x + 2, y + 1, 0xB8)
placeObject(x + 3, y + 1, 0xB9)
placeObject(x + 0, y + 2, 0xBA)
placeObject(x + 1, y + 2, 0xBB)
placeObject(x + 2, y + 2, 0xBC)
placeObject(x + 3, y + 2, 0xBD)
elif type_id == 0xFD: # entrance
placeObject(x, y, 0xC1)
placeObject(x + 1, y, 0xC2)
else:
if x < 10 and y < 8:
tiles[x + y * 10] = type_id
def addWalls(flags):
for x in range(0, 10):
if flags & 0b0010:
placeObject(x, 0, 0x21)
if flags & 0b0001:
placeObject(x, 7, 0x22)
for y in range(0, 8):
if flags & 0b1000:
placeObject(0, y, 0x23)
if flags & 0b0100:
placeObject(9, y, 0x24)
if flags & 0b1000 and flags & 0b0010:
placeObject(0, 0, 0x25)
if flags & 0b0100 and flags & 0b0010:
placeObject(9, 0, 0x26)
if flags & 0b1000 and flags & 0b0001:
placeObject(0, 7, 0x27)
if flags & 0b0100 and flags & 0b0001:
placeObject(9, 7, 0x28)
if self.floor_object & 0xF0 == 0x00:
addWalls(0b1111)
if self.floor_object & 0xF0 == 0x10:
addWalls(0b1101)
if self.floor_object & 0xF0 == 0x20:
addWalls(0b1011)
if self.floor_object & 0xF0 == 0x30:
addWalls(0b1110)
if self.floor_object & 0xF0 == 0x40:
addWalls(0b0111)
if self.floor_object & 0xF0 == 0x50:
addWalls(0b1001)
if self.floor_object & 0xF0 == 0x60:
addWalls(0b0101)
if self.floor_object & 0xF0 == 0x70:
addWalls(0b0110)
if self.floor_object & 0xF0 == 0x80:
addWalls(0b1010)
for obj in self.objects:
if isinstance(obj, ObjectWarp):
pass
elif isinstance(obj, ObjectHorizontal):
for n in range(0, obj.count):
placeObject(obj.x + n * objHSize(obj.type_id), obj.y, obj.type_id)
elif isinstance(obj, ObjectVertical):
for n in range(0, obj.count):
placeObject(obj.x, obj.y + n * objVSize(obj.type_id), obj.type_id)
else:
placeObject(obj.x, obj.y, obj.type_id)
return tiles
def buildObjectList(self, tiles, *, reduce_size=False):
self.objects = [obj for obj in self.objects if isinstance(obj, ObjectWarp)]
tiles = tiles.copy()
if self.overlay:
for n in range(80):
self.overlay[n] = tiles[n]
if reduce_size:
if tiles[n] in {0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F,
0x33, 0x34, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
0x48, 0x49, 0x4B, 0x4C, 0x4E,
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F}:
tiles[n] = 0x3A # Solid tiles
if tiles[n] in {0x08, 0x09, 0x0C, 0x44,
0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF}:
tiles[n] = 0x04 # Open tiles
is_overworld = isinstance(self.room, str) or self.room < 0x100
counts = {}
for n in tiles:
if n < 0x0F or is_overworld:
counts[n] = counts.get(n, 0) + 1
self.floor_object = max(counts, key=counts.get)
for y in range(8) if is_overworld else range(1, 7):
for x in range(10) if is_overworld else range(1, 9):
if tiles[x + y * 10] == self.floor_object:
tiles[x + y * 10] = -1
for y in range(8):
for x in range(10):
obj = tiles[x + y * 10]
if obj == -1:
continue
w = 1
h = 1
while x + w < 10 and tiles[x + w + y * 10] == obj:
w += 1
while y + h < 8 and tiles[x + (y + h) * 10] == obj:
h += 1
if obj in {0xE1, 0xE2, 0xE3, 0xBA, 0xC6}: # Entrances should never be horizontal/vertical lists
w = 1
h = 1
if w > h:
for n in range(w):
tiles[x + n + y * 10] = -1
self.objects.append(ObjectHorizontal(x, y, obj, w))
elif h > 1:
for n in range(h):
tiles[x + (y + n) * 10] = -1
self.objects.append(ObjectVertical(x, y, obj, h))
else:
self.objects.append(Object(x, y, obj))
class Object:
def __init__(self, x, y, type_id):
self.x = x
self.y = y
self.type_id = type_id
def export(self):
return bytearray([self.x | (self.y << 4), self.type_id])
def __repr__(self):
return "%s:%d,%d:%02X" % (self.__class__.__name__, self.x, self.y, self.type_id)
class ObjectHorizontal(Object):
def __init__(self, x, y, type_id, count):
super().__init__(x, y, type_id)
self.count = count
def export(self):
return bytearray([0x80 | self.count, self.x | (self.y << 4), self.type_id])
def __repr__(self):
return "%s:%d,%d:%02Xx%d" % (self.__class__.__name__, self.x, self.y, self.type_id, self.count)
class ObjectVertical(Object):
def __init__(self, x, y, type_id, count):
super().__init__(x, y, type_id)
self.count = count
def export(self):
return bytearray([0xC0 | self.count, self.x | (self.y << 4), self.type_id])
def __repr__(self):
return "%s:%d,%d:%02Xx%d" % (self.__class__.__name__, self.x, self.y, self.type_id, self.count)
class ObjectWarp(Object):
def __init__(self, warp_type, map_nr, room_nr, target_x, target_y):
super().__init__(None, None, None)
if warp_type > 0:
# indoor map
if map_nr == 0xff:
room_nr += 0x300 # color dungeon
elif 0x06 <= map_nr < 0x1A:
room_nr += 0x200 # indoor B
else:
room_nr += 0x100 # indoor A
self.warp_type = warp_type
self.room = room_nr
self.map_nr = map_nr
self.target_x = target_x
self.target_y = target_y
def export(self):
return bytearray([0xE0 | self.warp_type, self.map_nr, self.room & 0xFF, self.target_x, self.target_y])
def copy(self):
return ObjectWarp(self.warp_type, self.map_nr, self.room & 0xFF, self.target_x, self.target_y)
def __repr__(self):
return "%s:%d:%03x:%02x:%d,%d" % (self.__class__.__name__, self.warp_type, self.room, self.map_nr, self.target_x, self.target_y)
| 412 | 0.76883 | 1 | 0.76883 | game-dev | MEDIA | 0.340668 | game-dev | 0.829277 | 1 | 0.829277 |
stal111/Forbidden-Arcanus | 1,783 | neoforge/src/main/java/com/stal111/forbidden_arcanus/common/block/entity/forge/TierPredicate.java | package com.stal111.forbidden_arcanus.common.block.entity.forge;
import com.mojang.serialization.Codec;
import com.mojang.serialization.MapCodec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import com.stal111.forbidden_arcanus.ForbiddenArcanus;
import net.minecraft.Util;
import net.minecraft.network.chat.Component;
import java.util.function.IntPredicate;
/**
* @author stal111
* @since 30.05.2024
*/
public record TierPredicate(int tier, boolean matchExact) implements IntPredicate {
private static final String MATCH_EXACT = Util.makeDescriptionId("block", ForbiddenArcanus.location("hephaestus_forge.tier.match_exact"));
private static final String AT_LEAST = Util.makeDescriptionId("block", ForbiddenArcanus.location("hephaestus_forge.tier.at_least"));
public static final TierPredicate ANY = new TierPredicate(1, false);
public static final MapCodec<TierPredicate> CODEC = RecordCodecBuilder.mapCodec(instance -> instance.group(
Codec.INT.optionalFieldOf("forge_tier", 1).forGetter(predicate -> {
return predicate.tier;
}),
Codec.BOOL.optionalFieldOf("match_tier_exact", false).forGetter(predicate -> {
return predicate.matchExact;
})
).apply(instance, TierPredicate::new));
public static TierPredicate min(int tier) {
return new TierPredicate(tier, false);
}
public static TierPredicate exact(int tier) {
return new TierPredicate(tier, true);
}
@Override
public boolean test(int value) {
return this.matchExact ? this.tier == value : this.tier <= value;
}
public Component getDescription() {
return Component.translatable(this.matchExact ? MATCH_EXACT : AT_LEAST, this.tier);
}
}
| 412 | 0.760596 | 1 | 0.760596 | game-dev | MEDIA | 0.934401 | game-dev | 0.80339 | 1 | 0.80339 |
willothy/strat-hero.nvim | 1,478 | lua/strat-hero/view/round_end.lua | ---Game over screen.
---@class StratHero.Ui.RoundEnd: StratHero.Ui.View
---@type StratHero.Ui.RoundEnd
local RoundEnd = {}
local function rpad(str, len)
str = tostring(str or "")
return str .. string.rep(" ", len - string.len(str))
end
function RoundEnd.render(game, win_config, first_render)
if not first_render then
return
end
local Line = require("nui.line")
win_config.title = string.format("Round %d Over", game.round - 1)
win_config.title_pos = "center"
win_config.footer = ""
win_config.footer_pos = "center"
local score = tostring(game.score)
local round = tostring(game.round)
local time_bonus = tostring(game.last_time_bonus)
local perfect = game.last_failures == 0
local perfect_bonus = perfect and tostring(game.PERFECT_ROUND_BONUS) or "0"
local rows = {
{ "" },
{ "Score", score },
{ "" },
{ "Time Bonus", time_bonus },
{
"Perfect Round",
perfect_bonus,
},
}
local l_max = 0
local r_max = 0
for _, row in ipairs(rows) do
l_max = math.max(l_max, #(row[1] or ""))
r_max = math.max(r_max, #(row[2] or ""))
end
local l_len = l_max + 2
local r_len = r_max
return vim
.iter(rows)
:map(function(row)
local line = Line()
if row[1] then
line:append(rpad(row[1], l_len), "Title")
end
if row[2] then
line:append(rpad(row[2], r_len), "DiagnosticWarn")
end
return line
end)
:totable()
end
return RoundEnd
| 412 | 0.807337 | 1 | 0.807337 | game-dev | MEDIA | 0.843253 | game-dev | 0.963109 | 1 | 0.963109 |
ronanociosoig/Tuist-Pokedex | 2,258 | Features/Pokedex/Tests/AppDataTests.swift | //
// AppDataTests.swift
// PokedexTests
//
// Created by Ronan on 10/05/2019.
// Copyright © 2019 Sonomos. All rights reserved.
//
// swiftlint:disable all
import XCTest
import Pokedex
import Common
//@testable import Pokedex
class AppDataTests: XCTestCase {
enum PokemonId: Int {
case pokemon5
case pokemon12
}
func testNewSpecies() {
let appData = AppData(storage: FileStorage())
let pokemon5 = loadPokemon(identifier: .pokemon5)
let pokemon12 = loadPokemon(identifier: .pokemon12)
appData.pokemon = pokemon5
let localPokemon = PokemonParser.parse(pokemon: pokemon5)
appData.pokemons.append(localPokemon)
var newSpecies = appData.newSpecies()
XCTAssertFalse(newSpecies)
appData.pokemon = pokemon12
newSpecies = appData.newSpecies()
XCTAssertTrue(newSpecies)
}
func loadPokemon(identifier: PokemonId) -> Pokemon {
let data: Data
switch identifier {
case .pokemon5:
data = try! MockData.loadResponse()!
case .pokemon12:
data = try! MockData.loadOtherResponse()!
}
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let pokemon = try! decoder.decode(Pokemon.self, from: data)
return pokemon
}
func testSortByOrder() {
let appData = AppData(storage: FileStorage())
let pokemon5 = loadPokemon(identifier: .pokemon5)
let pokemon12 = loadPokemon(identifier: .pokemon12)
let localPokemon5 = PokemonParser.parse(pokemon: pokemon5)
let localPokemon12 = PokemonParser.parse(pokemon: pokemon12)
appData.pokemons.append(localPokemon5)
appData.pokemons.append(localPokemon12)
appData.sortByOrder()
guard let firstItem = appData.pokemons.first else {
XCTFail("Failed to parse data")
return
}
guard let lastItem = appData.pokemons.last else {
XCTFail("Failed to parse data")
return
}
XCTAssertTrue(firstItem.order < lastItem.order)
}
}
| 412 | 0.646099 | 1 | 0.646099 | game-dev | MEDIA | 0.539837 | game-dev | 0.553319 | 1 | 0.553319 |
randomguy3725/MoonLight | 21,045 | src/main/java/net/minecraft/client/gui/GuiScreenBook.java | package net.minecraft.client.gui;
import com.google.common.collect.Lists;
import com.google.gson.JsonParseException;
import io.netty.buffer.Unpooled;
import java.io.IOException;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.event.ClickEvent;
import net.minecraft.init.Items;
import net.minecraft.item.ItemEditableBook;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.nbt.NBTTagString;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.play.client.C17PacketCustomPayload;
import net.minecraft.util.ChatAllowedCharacters;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.IChatComponent;
import net.minecraft.util.ResourceLocation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.lwjglx.input.Keyboard;
public class GuiScreenBook extends GuiScreen
{
private static final Logger logger = LogManager.getLogger();
private static final ResourceLocation bookGuiTextures = new ResourceLocation("textures/gui/book.png");
private final EntityPlayer editingPlayer;
private final ItemStack bookObj;
private final boolean bookIsUnsigned;
private boolean bookIsModified;
private boolean bookGettingSigned;
private int updateCount;
private final int bookImageWidth = 192;
private final int bookImageHeight = 192;
private int bookTotalPages = 1;
private int currPage;
private NBTTagList bookPages;
private String bookTitle = "";
private List<IChatComponent> field_175386_A;
private int field_175387_B = -1;
private GuiScreenBook.NextPageButton buttonNextPage;
private GuiScreenBook.NextPageButton buttonPreviousPage;
private GuiButton buttonDone;
private GuiButton buttonSign;
private GuiButton buttonFinalize;
private GuiButton buttonCancel;
public GuiScreenBook(EntityPlayer player, ItemStack book, boolean isUnsigned)
{
this.editingPlayer = player;
this.bookObj = book;
this.bookIsUnsigned = isUnsigned;
if (book.hasTagCompound())
{
NBTTagCompound nbttagcompound = book.getTagCompound();
this.bookPages = nbttagcompound.getTagList("pages", 8);
if (this.bookPages != null)
{
this.bookPages = (NBTTagList)this.bookPages.copy();
this.bookTotalPages = this.bookPages.tagCount();
if (this.bookTotalPages < 1)
{
this.bookTotalPages = 1;
}
}
}
if (this.bookPages == null && isUnsigned)
{
this.bookPages = new NBTTagList();
this.bookPages.appendTag(new NBTTagString(""));
this.bookTotalPages = 1;
}
}
public void updateScreen()
{
super.updateScreen();
++this.updateCount;
}
public void initGui()
{
this.buttonList.clear();
Keyboard.enableRepeatEvents(true);
if (this.bookIsUnsigned)
{
this.buttonList.add(this.buttonSign = new GuiButton(3, this.width / 2 - 100, 4 + this.bookImageHeight, 98, 20, I18n.format("book.signButton")));
this.buttonList.add(this.buttonDone = new GuiButton(0, this.width / 2 + 2, 4 + this.bookImageHeight, 98, 20, I18n.format("gui.done")));
this.buttonList.add(this.buttonFinalize = new GuiButton(5, this.width / 2 - 100, 4 + this.bookImageHeight, 98, 20, I18n.format("book.finalizeButton")));
this.buttonList.add(this.buttonCancel = new GuiButton(4, this.width / 2 + 2, 4 + this.bookImageHeight, 98, 20, I18n.format("gui.cancel")));
}
else
{
this.buttonList.add(this.buttonDone = new GuiButton(0, this.width / 2 - 100, 4 + this.bookImageHeight, 200, 20, I18n.format("gui.done")));
}
int i = (this.width - this.bookImageWidth) / 2;
int j = 2;
this.buttonList.add(this.buttonNextPage = new GuiScreenBook.NextPageButton(1, i + 120, j + 154, true));
this.buttonList.add(this.buttonPreviousPage = new GuiScreenBook.NextPageButton(2, i + 38, j + 154, false));
this.updateButtons();
}
public void onGuiClosed()
{
Keyboard.enableRepeatEvents(false);
}
private void updateButtons()
{
this.buttonNextPage.visible = !this.bookGettingSigned && (this.currPage < this.bookTotalPages - 1 || this.bookIsUnsigned);
this.buttonPreviousPage.visible = !this.bookGettingSigned && this.currPage > 0;
this.buttonDone.visible = !this.bookIsUnsigned || !this.bookGettingSigned;
if (this.bookIsUnsigned)
{
this.buttonSign.visible = !this.bookGettingSigned;
this.buttonCancel.visible = this.bookGettingSigned;
this.buttonFinalize.visible = this.bookGettingSigned;
this.buttonFinalize.enabled = !this.bookTitle.trim().isEmpty();
}
}
private void sendBookToServer(boolean publish) throws IOException
{
if (this.bookIsUnsigned && this.bookIsModified)
{
if (this.bookPages != null)
{
while (this.bookPages.tagCount() > 1)
{
String s = this.bookPages.getStringTagAt(this.bookPages.tagCount() - 1);
if (!s.isEmpty())
{
break;
}
this.bookPages.removeTag(this.bookPages.tagCount() - 1);
}
if (this.bookObj.hasTagCompound())
{
NBTTagCompound nbttagcompound = this.bookObj.getTagCompound();
nbttagcompound.setTag("pages", this.bookPages);
}
else
{
this.bookObj.setTagInfo("pages", this.bookPages);
}
String s2 = "MC|BEdit";
if (publish)
{
s2 = "MC|BSign";
this.bookObj.setTagInfo("author", new NBTTagString(this.editingPlayer.getName()));
this.bookObj.setTagInfo("title", new NBTTagString(this.bookTitle.trim()));
for (int i = 0; i < this.bookPages.tagCount(); ++i)
{
String s1 = this.bookPages.getStringTagAt(i);
IChatComponent ichatcomponent = new ChatComponentText(s1);
s1 = IChatComponent.Serializer.componentToJson(ichatcomponent);
this.bookPages.set(i, new NBTTagString(s1));
}
this.bookObj.setItem(Items.written_book);
}
PacketBuffer packetbuffer = new PacketBuffer(Unpooled.buffer());
packetbuffer.writeItemStackToBuffer(this.bookObj);
this.mc.getNetHandler().addToSendQueue(new C17PacketCustomPayload(s2, packetbuffer));
}
}
}
protected void actionPerformed(GuiButton button) throws IOException
{
if (button.enabled)
{
if (button.id == 0)
{
this.mc.displayGuiScreen(null);
this.sendBookToServer(false);
}
else if (button.id == 3 && this.bookIsUnsigned)
{
this.bookGettingSigned = true;
}
else if (button.id == 1)
{
if (this.currPage < this.bookTotalPages - 1)
{
++this.currPage;
}
else if (this.bookIsUnsigned)
{
this.addNewPage();
if (this.currPage < this.bookTotalPages - 1)
{
++this.currPage;
}
}
}
else if (button.id == 2)
{
if (this.currPage > 0)
{
--this.currPage;
}
}
else if (button.id == 5 && this.bookGettingSigned)
{
this.sendBookToServer(true);
this.mc.displayGuiScreen(null);
}
else if (button.id == 4 && this.bookGettingSigned)
{
this.bookGettingSigned = false;
}
this.updateButtons();
}
}
private void addNewPage()
{
if (this.bookPages != null && this.bookPages.tagCount() < 50)
{
this.bookPages.appendTag(new NBTTagString(""));
++this.bookTotalPages;
this.bookIsModified = true;
}
}
protected void keyTyped(char typedChar, int keyCode) throws IOException
{
super.keyTyped(typedChar, keyCode);
if (this.bookIsUnsigned)
{
if (this.bookGettingSigned)
{
this.keyTypedInTitle(typedChar, keyCode);
}
else
{
this.keyTypedInBook(typedChar, keyCode);
}
}
}
private void keyTypedInBook(char typedChar, int keyCode)
{
if (GuiScreen.isKeyComboCtrlV(keyCode))
{
this.pageInsertIntoCurrent(GuiScreen.getClipboardString());
}
else
{
switch (keyCode)
{
case 14:
String s = this.pageGetCurrent();
if (!s.isEmpty())
{
this.pageSetCurrent(s.substring(0, s.length() - 1));
}
return;
case 28:
case 156:
this.pageInsertIntoCurrent("\n");
return;
default:
if (ChatAllowedCharacters.isAllowedCharacter(typedChar))
{
this.pageInsertIntoCurrent(Character.toString(typedChar));
}
}
}
}
private void keyTypedInTitle(char p_146460_1_, int p_146460_2_) throws IOException
{
switch (p_146460_2_)
{
case 14:
if (!this.bookTitle.isEmpty())
{
this.bookTitle = this.bookTitle.substring(0, this.bookTitle.length() - 1);
this.updateButtons();
}
return;
case 28:
case 156:
if (!this.bookTitle.isEmpty())
{
this.sendBookToServer(true);
this.mc.displayGuiScreen(null);
}
return;
default:
if (this.bookTitle.length() < 16 && ChatAllowedCharacters.isAllowedCharacter(p_146460_1_))
{
this.bookTitle = this.bookTitle + p_146460_1_;
this.updateButtons();
this.bookIsModified = true;
}
}
}
private String pageGetCurrent()
{
return this.bookPages != null && this.currPage >= 0 && this.currPage < this.bookPages.tagCount() ? this.bookPages.getStringTagAt(this.currPage) : "";
}
private void pageSetCurrent(String p_146457_1_)
{
if (this.bookPages != null && this.currPage >= 0 && this.currPage < this.bookPages.tagCount())
{
this.bookPages.set(this.currPage, new NBTTagString(p_146457_1_));
this.bookIsModified = true;
}
}
private void pageInsertIntoCurrent(String p_146459_1_)
{
String s = this.pageGetCurrent();
String s1 = s + p_146459_1_;
int i = this.fontRendererObj.splitStringWidth(s1 + EnumChatFormatting.BLACK + "_", 118);
if (i <= 128 && s1.length() < 256)
{
this.pageSetCurrent(s1);
}
}
public void drawScreen(int mouseX, int mouseY, float partialTicks)
{
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
this.mc.getTextureManager().bindTexture(bookGuiTextures);
int i = (this.width - this.bookImageWidth) / 2;
int j = 2;
this.drawTexturedModalRect(i, j, 0, 0, this.bookImageWidth, this.bookImageHeight);
if (this.bookGettingSigned)
{
String s = this.bookTitle;
if (this.bookIsUnsigned)
{
if (this.updateCount / 6 % 2 == 0)
{
s = s + EnumChatFormatting.BLACK + "_";
}
else
{
s = s + EnumChatFormatting.GRAY + "_";
}
}
String s1 = I18n.format("book.editTitle");
int k = this.fontRendererObj.getStringWidth(s1);
this.fontRendererObj.drawString(s1, i + 36 + (116 - k) / 2, j + 16 + 16, 0);
int l = this.fontRendererObj.getStringWidth(s);
this.fontRendererObj.drawString(s, i + 36 + (116 - l) / 2, j + 48, 0);
String s2 = I18n.format("book.byAuthor", this.editingPlayer.getName());
int i1 = this.fontRendererObj.getStringWidth(s2);
this.fontRendererObj.drawString(EnumChatFormatting.DARK_GRAY + s2, i + 36 + (116 - i1) / 2, j + 48 + 10, 0);
String s3 = I18n.format("book.finalizeWarning");
this.fontRendererObj.drawSplitString(s3, i + 36, j + 80, 116, 0);
}
else
{
String s4 = I18n.format("book.pageIndicator", this.currPage + 1, this.bookTotalPages);
String s5 = "";
if (this.bookPages != null && this.currPage >= 0 && this.currPage < this.bookPages.tagCount())
{
s5 = this.bookPages.getStringTagAt(this.currPage);
}
if (this.bookIsUnsigned)
{
if (this.fontRendererObj.getBidiFlag())
{
s5 = s5 + "_";
}
else if (this.updateCount / 6 % 2 == 0)
{
s5 = s5 + EnumChatFormatting.BLACK + "_";
}
else
{
s5 = s5 + EnumChatFormatting.GRAY + "_";
}
}
else if (this.field_175387_B != this.currPage)
{
if (ItemEditableBook.validBookTagContents(this.bookObj.getTagCompound()))
{
try
{
IChatComponent ichatcomponent = IChatComponent.Serializer.jsonToComponent(s5);
this.field_175386_A = ichatcomponent != null ? GuiUtilRenderComponents.splitText(ichatcomponent, 116, this.fontRendererObj, true, true) : null;
}
catch (JsonParseException var13)
{
this.field_175386_A = null;
}
}
else
{
ChatComponentText chatcomponenttext = new ChatComponentText(EnumChatFormatting.DARK_RED + "* Invalid book tag *");
this.field_175386_A = Lists.newArrayList(chatcomponenttext);
}
this.field_175387_B = this.currPage;
}
int j1 = this.fontRendererObj.getStringWidth(s4);
this.fontRendererObj.drawString(s4, i - j1 + this.bookImageWidth - 44, j + 16, 0);
if (this.field_175386_A == null)
{
this.fontRendererObj.drawSplitString(s5, i + 36, j + 16 + 16, 116, 0);
}
else
{
int k1 = Math.min(128 / this.fontRendererObj.FONT_HEIGHT, this.field_175386_A.size());
for (int l1 = 0; l1 < k1; ++l1)
{
IChatComponent ichatcomponent2 = this.field_175386_A.get(l1);
this.fontRendererObj.drawString(ichatcomponent2.getUnformattedText(), i + 36, j + 16 + 16 + l1 * this.fontRendererObj.FONT_HEIGHT, 0);
}
IChatComponent ichatcomponent1 = this.func_175385_b(mouseX, mouseY);
if (ichatcomponent1 != null)
{
this.handleComponentHover(ichatcomponent1, mouseX, mouseY);
}
}
}
super.drawScreen(mouseX, mouseY, partialTicks);
}
public void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException
{
if (mouseButton == 0)
{
IChatComponent ichatcomponent = this.func_175385_b(mouseX, mouseY);
if (this.handleComponentClick(ichatcomponent))
{
return;
}
}
super.mouseClicked(mouseX, mouseY, mouseButton);
}
protected boolean handleComponentClick(IChatComponent component)
{
ClickEvent clickevent = component == null ? null : component.getChatStyle().getChatClickEvent();
if (clickevent == null)
{
return false;
}
else if (clickevent.getAction() == ClickEvent.Action.CHANGE_PAGE)
{
String s = clickevent.getValue();
try
{
int i = Integer.parseInt(s) - 1;
if (i >= 0 && i < this.bookTotalPages && i != this.currPage)
{
this.currPage = i;
this.updateButtons();
return true;
}
}
catch (Throwable var5)
{
}
return false;
}
else
{
boolean flag = super.handleComponentClick(component);
if (flag && clickevent.getAction() == ClickEvent.Action.RUN_COMMAND)
{
this.mc.displayGuiScreen(null);
}
return flag;
}
}
public IChatComponent func_175385_b(int p_175385_1_, int p_175385_2_)
{
if (this.field_175386_A == null)
{
return null;
}
else
{
int i = p_175385_1_ - (this.width - this.bookImageWidth) / 2 - 36;
int j = p_175385_2_ - 2 - 16 - 16;
if (i >= 0 && j >= 0)
{
int k = Math.min(128 / this.fontRendererObj.FONT_HEIGHT, this.field_175386_A.size());
if (i <= 116 && j < this.mc.fontRendererObj.FONT_HEIGHT * k + k)
{
int l = j / this.mc.fontRendererObj.FONT_HEIGHT;
if (l >= 0 && l < this.field_175386_A.size())
{
IChatComponent ichatcomponent = this.field_175386_A.get(l);
int i1 = 0;
for (IChatComponent ichatcomponent1 : ichatcomponent)
{
if (ichatcomponent1 instanceof ChatComponentText)
{
i1 += this.mc.fontRendererObj.getStringWidth(((ChatComponentText)ichatcomponent1).getChatComponentText_TextValue());
if (i1 > i)
{
return ichatcomponent1;
}
}
}
}
return null;
}
else
{
return null;
}
}
else
{
return null;
}
}
}
static class NextPageButton extends GuiButton
{
private final boolean field_146151_o;
public NextPageButton(int p_i46316_1_, int p_i46316_2_, int p_i46316_3_, boolean p_i46316_4_)
{
super(p_i46316_1_, p_i46316_2_, p_i46316_3_, 23, 13, "");
this.field_146151_o = p_i46316_4_;
}
public void drawButton(Minecraft mc, int mouseX, int mouseY)
{
if (this.visible)
{
boolean flag = mouseX >= this.xPosition && mouseY >= this.yPosition && mouseX < this.xPosition + this.width && mouseY < this.yPosition + this.height;
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
mc.getTextureManager().bindTexture(GuiScreenBook.bookGuiTextures);
int i = 0;
int j = 192;
if (flag)
{
i += 23;
}
if (!this.field_146151_o)
{
j += 13;
}
this.drawTexturedModalRect(this.xPosition, this.yPosition, i, j, 23, 13);
}
}
}
}
| 412 | 0.863578 | 1 | 0.863578 | game-dev | MEDIA | 0.542998 | game-dev,desktop-app | 0.960485 | 1 | 0.960485 |
MJRLegends/ExtraPlanets | 2,574 | src/main/java/com/mjr/extraplanets/client/gui/vehicles/GuiSchematicMarsRover.java | package com.mjr.extraplanets.client.gui.vehicles;
import org.lwjgl.opengl.GL11;
import com.mjr.extraplanets.Constants;
import com.mjr.extraplanets.inventory.vehicles.ContainerSchematicMarsRover;
import com.mjr.mjrlegendslib.util.TranslateUtilities;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import micdoodle8.mods.galacticraft.api.recipe.ISchematicResultPage;
import micdoodle8.mods.galacticraft.api.recipe.SchematicRegistry;
import micdoodle8.mods.galacticraft.core.client.gui.container.GuiPositionedContainer;
public class GuiSchematicMarsRover extends GuiPositionedContainer implements ISchematicResultPage {
private static final ResourceLocation marsRoverBenchTexture = new ResourceLocation(Constants.ASSET_PREFIX, "textures/gui/mars_roverbench.png");
private int pageIndex;
public GuiSchematicMarsRover(InventoryPlayer inventoryPlayer, BlockPos pos) {
super(new ContainerSchematicMarsRover(inventoryPlayer, pos), pos);
this.ySize = 221;
}
@Override
public void initGui() {
super.initGui();
this.buttonList.clear();
this.buttonList.add(new GuiButton(0, this.width / 2 - 130, this.height / 2 - 110, 40, 20, TranslateUtilities.translate("gui.button.back.name")));
this.buttonList.add(new GuiButton(1, this.width / 2 - 130, this.height / 2 - 110 + 25, 40, 20, TranslateUtilities.translate("gui.button.next.name")));
}
@Override
protected void actionPerformed(GuiButton par1GuiButton) {
if (par1GuiButton.enabled) {
switch (par1GuiButton.id) {
case 0:
SchematicRegistry.flipToLastPage(this, this.pageIndex);
break;
case 1:
SchematicRegistry.flipToNextPage(this, this.pageIndex);
break;
}
}
}
@Override
protected void drawGuiContainerForegroundLayer(int par1, int par2) {
this.fontRenderer.drawString(TranslateUtilities.translate("schematic.mars.rover.name"), 7, -20 + 27, 4210752);
this.fontRenderer.drawString(TranslateUtilities.translate("container.inventory"), 8, 202 - 104 + 2 + 27, 4210752);
}
@Override
protected void drawGuiContainerBackgroundLayer(float par1, int par2, int par3) {
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
this.mc.renderEngine.bindTexture(GuiSchematicMarsRover.marsRoverBenchTexture);
final int var5 = (this.width - this.xSize) / 2;
final int var6 = (this.height - 220) / 2;
this.drawTexturedModalRect(var5, var6, 0, 0, this.xSize, 220);
}
@Override
public void setPageIndex(int index) {
this.pageIndex = index;
}
} | 412 | 0.867842 | 1 | 0.867842 | game-dev | MEDIA | 0.881116 | game-dev | 0.957642 | 1 | 0.957642 |
CrazyVince/Hacking | 9,846 | Library/PackageCache/com.unity.visualscripting@1.8.0/Editor/VisualScripting.Core/Reflection/MemberOptionTree.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using UnityEngine;
using UnityObject = UnityEngine.Object;
namespace Unity.VisualScripting
{
public class MemberOptionTree : FuzzyOptionTree
{
public enum RootMode
{
Members,
Types,
Namespaces
}
public MemberOptionTree(IEnumerable<Type> types, MemberFilter memberFilter, TypeFilter memberTypeFilter, ActionDirection direction) : base(new GUIContent("Member"))
{
favorites = new Favorites(this);
codebase = Codebase.Subset(types, memberFilter.Configured(), memberTypeFilter?.Configured(false));
this.direction = direction;
expectingBoolean = memberTypeFilter?.ExpectsBoolean ?? false;
}
public MemberOptionTree(UnityObject target, MemberFilter memberFilter, TypeFilter memberTypeFilter, ActionDirection direction)
: this(EditorUnityObjectUtility.GetUnityTypes(target), memberFilter, memberTypeFilter, direction)
{
rootMode = RootMode.Types;
}
private readonly CodebaseSubset codebase;
private readonly ActionDirection direction;
private readonly bool expectingBoolean;
private readonly RootMode rootMode = RootMode.Namespaces;
public override void Prewarm()
{
base.Prewarm();
codebase.Cache();
}
public override IFuzzyOption Option(object item)
{
if (item is Member)
{
return new MemberOption((Member)item, direction, expectingBoolean);
}
if (item is Type)
{
return new TypeOption((Type)item, true);
}
return base.Option(item);
}
#region Hierarchy
public override IEnumerable<object> Root()
{
if (rootMode == RootMode.Types)
{
foreach (var type in codebase.members
.Select(m => m.targetType)
.Distinct()
.OrderBy(t => t.DisplayName()))
{
yield return type;
}
}
else if (rootMode == RootMode.Namespaces)
{
foreach (var @namespace in codebase.members.Select(m => m.targetType)
.Distinct()
.Where(t => !t.IsEnum)
.Select(t => t.Namespace().Root)
.Distinct()
.OrderBy(ns => ns.DisplayName(false)))
{
yield return @namespace;
}
}
else
{
throw new UnexpectedEnumValueException<RootMode>(rootMode);
}
}
public override IEnumerable<object> Children(object parent)
{
if (parent is Namespace)
{
var @namespace = (Namespace)parent;
if (!@namespace.IsGlobal)
{
foreach (var childNamespace in codebase.members
.Select(m => m.targetType)
.Distinct()
.Where(t => !t.IsEnum)
.Select(t => t.Namespace())
.Distinct()
.Where(ns => ns.Parent == @namespace)
.OrderBy(ns => ns.DisplayName(false)))
{
yield return childNamespace;
}
}
foreach (var type in codebase.members
.Select(m => m.targetType)
.Where(t => !t.IsEnum)
.Distinct()
.Where(t => t.Namespace() == @namespace)
.OrderBy(t => t.DisplayName()))
{
yield return type;
}
}
else if (parent is Type)
{
foreach (var member in codebase.members
.Where(m => m.targetType == (Type)parent)
.OrderBy(m => BoltCore.Configuration.groupInheritedMembers && m.isPseudoInherited)
.ThenBy(m => m.info.DisplayName()))
{
yield return member;
}
}
else if (parent is Member)
{
yield break;
}
else
{
throw new NotSupportedException();
}
}
#endregion
#region Search
public override bool searchable { get; } = true;
public override IEnumerable<object> OrderedSearchResults(string query, CancellationToken cancellation)
{
// Exclude duplicate inherited members, like the high amount of "Destroy()" or "enabled",
// if their declaring type is also available for search.
foreach (var member in codebase.members
.Cancellable(cancellation)
.UnorderedSearchFilter(query, m => MemberOption.Haystack(m, direction, expectingBoolean))
.Where(m => !m.isPseudoInherited || !codebase.types.Contains(m.declaringType))
.OrderBy(m => BoltCore.Configuration.groupInheritedMembers && m.isPseudoInherited)
.ThenByDescending(m => SearchUtility.Relevance(query, MemberOption.Haystack(m, direction, expectingBoolean))))
{
yield return member;
}
foreach (var type in codebase.types
.Cancellable(cancellation)
.Where(t => !t.IsEnum)
.OrderedSearchFilter(query, TypeOption.Haystack))
{
yield return type;
}
}
public override string SearchResultLabel(object item, string query)
{
if (item is Type)
{
return TypeOption.SearchResultLabel((Type)item, query);
}
else if (item is Member)
{
return MemberOption.SearchResultLabel((Member)item, query, direction, expectingBoolean);
}
throw new NotSupportedException();
}
#endregion
#region Favorites
public override ICollection<object> favorites { get; }
public override string FavoritesLabel(object item)
{
if (item is Namespace)
{
return ((Namespace)item).DisplayName();
}
else if (item is Type)
{
return ((Type)item).DisplayName();
}
else if (item is Member)
{
var member = (Member)item;
if (member.isInvocable)
{
return $"{member.info.DisplayName(direction, expectingBoolean)} ({member.methodBase.DisplayParameterString(member.targetType)})";
}
else
{
return member.info.DisplayName(direction, expectingBoolean);
}
}
throw new NotSupportedException();
}
public override bool CanFavorite(object item)
{
return item is Member;
}
public override void OnFavoritesChange()
{
BoltCore.Configuration.Save();
}
private class Favorites : ICollection<object>
{
public Favorites(MemberOptionTree tree)
{
this.tree = tree;
}
private readonly MemberOptionTree tree;
private IEnumerable<Member> validFavorites => BoltCore.Configuration.favoriteMembers.Where(tree.codebase.ValidateMember);
public int Count => validFavorites.Count();
public bool IsReadOnly => false;
public IEnumerator<object> GetEnumerator()
{
foreach (var favorite in validFavorites)
{
yield return favorite;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public bool Contains(object item)
{
return validFavorites.Contains((Member)item);
}
public void Add(object item)
{
favorites.Add(item);
}
public bool Remove(object item)
{
return favorites.Remove(item);
}
public void Clear()
{
favorites.Clear();
}
public void CopyTo(object[] array, int arrayIndex)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (arrayIndex < 0)
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
}
if (array.Length - arrayIndex < Count)
{
throw new ArgumentException();
}
var i = 0;
foreach (var item in this)
{
array[i + arrayIndex] = item;
i++;
}
}
private static readonly ICollection<object> favorites = new VariantCollection<object, Member>(BoltCore.Configuration.favoriteMembers);
}
#endregion
}
}
| 412 | 0.92718 | 1 | 0.92718 | game-dev | MEDIA | 0.442216 | game-dev | 0.983832 | 1 | 0.983832 |
ss14Starlight/space-station-14 | 9,882 | Content.Server/PowerCell/PowerCellSystem.cs | using Content.Server.Emp;
using Content.Server.Power.Components;
using Content.Shared.Examine;
using Content.Shared.PowerCell;
using Content.Shared.PowerCell.Components;
using Content.Shared.Rounding;
using Content.Shared.Kitchen.Components; // Starlight-edit
using Robust.Shared.Containers;
using System.Diagnostics.CodeAnalysis;
using Content.Server.Power.EntitySystems;
using Content.Server.UserInterface;
using Content.Shared.Containers.ItemSlots;
using Content.Shared.Popups;
using ActivatableUISystem = Content.Shared.UserInterface.ActivatableUISystem;
namespace Content.Server.PowerCell;
/// <summary>
/// Handles Power cells
/// </summary>
public sealed partial class PowerCellSystem : SharedPowerCellSystem
{
[Dependency] private readonly ActivatableUISystem _activatable = default!;
[Dependency] private readonly BatterySystem _battery = default!;
[Dependency] private readonly SharedContainerSystem _containerSystem = default!;
[Dependency] private readonly ItemSlotsSystem _itemSlotsSystem = default!;
[Dependency] private readonly SharedAppearanceSystem _sharedAppearanceSystem = default!;
[Dependency] private readonly SharedPopupSystem _popup = default!;
[Dependency] private readonly RiggableSystem _riggableSystem = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<PowerCellComponent, ChargeChangedEvent>(OnChargeChanged);
SubscribeLocalEvent<PowerCellComponent, ExaminedEvent>(OnCellExamined);
SubscribeLocalEvent<PowerCellComponent, EmpAttemptEvent>(OnCellEmpAttempt);
SubscribeLocalEvent<PowerCellDrawComponent, ChargeChangedEvent>(OnDrawChargeChanged);
SubscribeLocalEvent<PowerCellDrawComponent, PowerCellChangedEvent>(OnDrawCellChanged);
SubscribeLocalEvent<PowerCellSlotComponent, ExaminedEvent>(OnCellSlotExamined);
// funny
SubscribeLocalEvent<PowerCellSlotComponent, BeingMicrowavedEvent>(OnSlotMicrowaved);
SubscribeLocalEvent<PowerCellSlotComponent, GetChargeEvent>(OnGetCharge);
SubscribeLocalEvent<PowerCellSlotComponent, ChangeChargeEvent>(OnChangeCharge);
}
private void OnSlotMicrowaved(EntityUid uid, PowerCellSlotComponent component, BeingMicrowavedEvent args)
{
if (!_itemSlotsSystem.TryGetSlot(uid, component.CellSlotId, out var slot))
return;
if (slot.Item == null)
return;
RaiseLocalEvent(slot.Item.Value, args);
}
private void OnChargeChanged(EntityUid uid, PowerCellComponent component, ref ChargeChangedEvent args)
{
if (TryComp<RiggableComponent>(uid, out var rig) && rig.IsRigged)
{
_riggableSystem.Explode(uid, cause: null);
return;
}
var frac = args.Charge / args.MaxCharge;
var level = (byte)ContentHelpers.RoundToNearestLevels(frac, 1, PowerCellComponent.PowerCellVisualsLevels);
_sharedAppearanceSystem.SetData(uid, PowerCellVisuals.ChargeLevel, level);
// If this power cell is inside a cell-slot, inform that entity that the power has changed (for updating visuals n such).
if (_containerSystem.TryGetContainingContainer((uid, null, null), out var container)
&& TryComp(container.Owner, out PowerCellSlotComponent? slot)
&& _itemSlotsSystem.TryGetSlot(container.Owner, slot.CellSlotId, out var itemSlot))
{
if (itemSlot.Item == uid)
RaiseLocalEvent(container.Owner, new PowerCellChangedEvent(false));
}
}
protected override void OnCellRemoved(EntityUid uid, PowerCellSlotComponent component, EntRemovedFromContainerMessage args)
{
base.OnCellRemoved(uid, component, args);
if (args.Container.ID != component.CellSlotId)
return;
var ev = new PowerCellSlotEmptyEvent();
RaiseLocalEvent(uid, ref ev);
}
#region Activatable
/// <inheritdoc/>
public override bool HasActivatableCharge(EntityUid uid, PowerCellDrawComponent? battery = null, PowerCellSlotComponent? cell = null, EntityUid? user = null)
{
// Default to true if we don't have the components.
if (!Resolve(uid, ref battery, ref cell, false))
return true;
return HasCharge(uid, battery.UseRate, cell, user);
}
/// <summary>
/// Tries to use the <see cref="PowerCellDrawComponent.UseRate"/> for this entity.
/// </summary>
/// <param name="user">Popup to this user with the relevant detail if specified.</param>
public bool TryUseActivatableCharge(EntityUid uid, PowerCellDrawComponent? battery = null, PowerCellSlotComponent? cell = null, EntityUid? user = null)
{
// Default to true if we don't have the components.
if (!Resolve(uid, ref battery, ref cell, false))
return true;
if (TryUseCharge(uid, battery.UseRate, cell, user))
{
_sharedAppearanceSystem.SetData(uid, PowerCellSlotVisuals.Enabled, HasActivatableCharge(uid, battery, cell, user));
_activatable.CheckUsage(uid);
return true;
}
return false;
}
/// <inheritdoc/>
public override bool HasDrawCharge(
EntityUid uid,
PowerCellDrawComponent? battery = null,
PowerCellSlotComponent? cell = null,
EntityUid? user = null)
{
if (!Resolve(uid, ref battery, ref cell, false))
return true;
return HasCharge(uid, battery.DrawRate, cell, user);
}
#endregion
/// <summary>
/// Returns whether the entity has a slotted battery and charge for the requested action.
/// </summary>
/// <param name="user">Popup to this user with the relevant detail if specified.</param>
public bool HasCharge(EntityUid uid, float charge, PowerCellSlotComponent? component = null, EntityUid? user = null)
{
if (!TryGetBatteryFromSlot(uid, out var battery, component))
{
if (user != null)
_popup.PopupEntity(Loc.GetString("power-cell-no-battery"), uid, user.Value);
return false;
}
if (battery.CurrentCharge < charge)
{
if (user != null)
_popup.PopupEntity(Loc.GetString("power-cell-insufficient"), uid, user.Value);
return false;
}
return true;
}
/// <summary>
/// Tries to use charge from a slotted battery.
/// </summary>
public bool TryUseCharge(EntityUid uid, float charge, PowerCellSlotComponent? component = null, EntityUid? user = null)
{
if (!TryGetBatteryFromSlot(uid, out var batteryEnt, out var battery, component))
{
if (user != null)
_popup.PopupEntity(Loc.GetString("power-cell-no-battery"), uid, user.Value);
return false;
}
if (!_battery.TryUseCharge(batteryEnt.Value, charge, battery))
{
if (user != null)
_popup.PopupEntity(Loc.GetString("power-cell-insufficient"), uid, user.Value);
return false;
}
_sharedAppearanceSystem.SetData(uid, PowerCellSlotVisuals.Enabled, battery.CurrentCharge > 0);
return true;
}
public bool TryGetBatteryFromSlot(EntityUid uid, [NotNullWhen(true)] out BatteryComponent? battery, PowerCellSlotComponent? component = null)
{
return TryGetBatteryFromSlot(uid, out _, out battery, component);
}
public bool TryGetBatteryFromSlot(EntityUid uid,
[NotNullWhen(true)] out EntityUid? batteryEnt,
[NotNullWhen(true)] out BatteryComponent? battery,
PowerCellSlotComponent? component = null)
{
if (!Resolve(uid, ref component, false))
{
batteryEnt = null;
battery = null;
return false;
}
if (_itemSlotsSystem.TryGetSlot(uid, component.CellSlotId, out ItemSlot? slot))
{
batteryEnt = slot.Item;
return TryComp(slot.Item, out battery);
}
batteryEnt = null;
battery = null;
return false;
}
private void OnCellExamined(EntityUid uid, PowerCellComponent component, ExaminedEvent args)
{
TryComp<BatteryComponent>(uid, out var battery);
OnBatteryExamined(uid, battery, args);
}
private void OnCellEmpAttempt(EntityUid uid, PowerCellComponent component, EmpAttemptEvent args)
{
var parent = Transform(uid).ParentUid;
// relay the attempt event to the slot so it can cancel it
if (HasComp<PowerCellSlotComponent>(parent))
RaiseLocalEvent(parent, args);
}
private void OnCellSlotExamined(EntityUid uid, PowerCellSlotComponent component, ExaminedEvent args)
{
TryGetBatteryFromSlot(uid, out var battery);
OnBatteryExamined(uid, battery, args);
}
private void OnBatteryExamined(EntityUid uid, BatteryComponent? component, ExaminedEvent args)
{
if (component != null)
{
var charge = component.CurrentCharge / component.MaxCharge * 100;
args.PushMarkup(Loc.GetString("power-cell-component-examine-details", ("currentCharge", $"{charge:F0}")));
}
else
{
args.PushMarkup(Loc.GetString("power-cell-component-examine-details-no-battery"));
}
}
private void OnGetCharge(Entity<PowerCellSlotComponent> entity, ref GetChargeEvent args)
{
if (!TryGetBatteryFromSlot(entity, out var batteryUid, out _))
return;
RaiseLocalEvent(batteryUid.Value, ref args);
}
private void OnChangeCharge(Entity<PowerCellSlotComponent> entity, ref ChangeChargeEvent args)
{
if (!TryGetBatteryFromSlot(entity, out var batteryUid, out _))
return;
RaiseLocalEvent(batteryUid.Value, ref args);
}
}
| 412 | 0.965566 | 1 | 0.965566 | game-dev | MEDIA | 0.900269 | game-dev | 0.956127 | 1 | 0.956127 |
huika/UMA | 1,051 | UMAProject/Assets/UMA/Example/Expressions/Scenes/Scripts/ActiveObjectSwitcher.cs | using UnityEngine;
using System.Collections;
namespace UMA.PoseTools
{
public class ActiveObjectSwitcher : MonoBehaviour
{
public GameObject[] objects = new GameObject[0];
public GameObject activeObj = null;
private int selected = 0;
private string[] names = null;
// Position variables
public int xPos = 25;
public int yPos = 25;
// Use this for initialization
void Start()
{
if ((activeObj == null) && (objects.Length > 0))
{
activeObj = objects[0];
}
selected = 0;
names = new string[objects.Length];
for (int i = 0; i < objects.Length; i++)
{
names[i] = objects[i].name;
if (activeObj == objects[i])
{
selected = i;
}
}
}
void OnGUI()
{
GUILayout.BeginArea(new Rect(xPos, yPos, 80, 400));
int newSelected = GUILayout.SelectionGrid(selected, names, 1);
if (newSelected != selected)
{
activeObj.SetActive(false);
selected = newSelected;
activeObj = objects[newSelected];
activeObj.SetActive(true);
}
GUILayout.EndArea();
}
}
} | 412 | 0.62883 | 1 | 0.62883 | game-dev | MEDIA | 0.677311 | game-dev | 0.871447 | 1 | 0.871447 |
MergHQ/CRYENGINE | 8,063 | Code/CryEngine/CrySystem/SimpleStringPool.h | // Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved.
// -------------------------------------------------------------------------
// File name: SimpleStringPool.h
// Created: 21/04/2006 by Timur.
// Description:
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#ifndef __SimpleStringPool_h__
#define __SimpleStringPool_h__
#pragma once
#include <CrySystem/ISystem.h>
#include <CryCore/StlUtils.h>
//TODO: Pull most of this into a cpp file!
struct SStringData
{
SStringData(const char* szString, int nStrLen)
: m_szString(szString)
, m_nStrLen(nStrLen)
{
}
const char* m_szString;
int m_nStrLen;
private:
bool operator==(const SStringData& other) const;
};
struct hash_stringdata
{
size_t operator()(const SStringData& key) const
{
return stl::hash_strcmp<const char*>()(key.m_szString);
}
bool operator()(const SStringData& key1, const SStringData& key2) const
{
return
key1.m_nStrLen == key2.m_nStrLen &&
strcmp(key1.m_szString, key2.m_szString) == 0;
}
};
/////////////////////////////////////////////////////////////////////
// String pool implementation.
// Inspired by expat implementation.
/////////////////////////////////////////////////////////////////////
class CSimpleStringPool
{
public:
enum { STD_BLOCK_SIZE = 1u << 16 };
struct BLOCK
{
BLOCK* next;
int size;
char s[1];
};
unsigned int m_blockSize;
BLOCK* m_blocks;
BLOCK* m_free_blocks;
const char* m_end;
char* m_ptr;
char* m_start;
int nUsedSpace;
int nUsedBlocks;
bool m_reuseStrings;
typedef std::unordered_map<SStringData, char*, hash_stringdata, hash_stringdata> TStringToExistingStringMap;
TStringToExistingStringMap m_stringToExistingStringMap;
static size_t g_nTotalAllocInXmlStringPools;
CSimpleStringPool()
{
m_blockSize = STD_BLOCK_SIZE - offsetof(BLOCK, s);
m_blocks = 0;
m_start = 0;
m_ptr = 0;
m_end = 0;
nUsedSpace = 0;
nUsedBlocks = 0;
m_free_blocks = 0;
m_reuseStrings = false;
}
explicit CSimpleStringPool(bool reuseStrings)
: m_blockSize(STD_BLOCK_SIZE - offsetof(BLOCK, s))
, m_blocks(NULL)
, m_free_blocks(NULL)
, m_end(0)
, m_ptr(0)
, m_start(0)
, nUsedSpace(0)
, nUsedBlocks(0)
, m_reuseStrings(reuseStrings)
{
}
~CSimpleStringPool()
{
BLOCK* pBlock = m_blocks;
while (pBlock)
{
BLOCK* temp = pBlock->next;
g_nTotalAllocInXmlStringPools -= (offsetof(BLOCK, s) + pBlock->size * sizeof(char));
free(pBlock);
pBlock = temp;
}
pBlock = m_free_blocks;
while (pBlock)
{
BLOCK* temp = pBlock->next;
g_nTotalAllocInXmlStringPools -= (offsetof(BLOCK, s) + pBlock->size * sizeof(char));
free(pBlock);
pBlock = temp;
}
m_blocks = 0;
m_ptr = 0;
m_start = 0;
m_end = 0;
}
void SetBlockSize(unsigned int nBlockSize)
{
if (nBlockSize > 1024 * 1024)
nBlockSize = 1024 * 1024;
unsigned int size = 512;
while (size < nBlockSize)
size *= 2;
m_blockSize = size - offsetof(BLOCK, s);
}
void Clear()
{
BLOCK* pLast = m_free_blocks;
if (pLast)
{
while (pLast->next)
pLast = pLast->next;
pLast->next = m_blocks;
}
else
{
m_free_blocks = m_blocks;
}
m_blocks = 0;
m_start = 0;
m_ptr = 0;
m_end = 0;
nUsedSpace = 0;
if (m_reuseStrings)
{
m_stringToExistingStringMap.clear();
}
}
char* Append(const char* ptr, int nStrLen)
{
MEMSTAT_CONTEXT(EMemStatContextTypes::MSC_Other, 0, "StringPool");
assert(nStrLen <= 100000);
if (m_reuseStrings)
{
if (char* existingString = FindExistingString(ptr, nStrLen))
{
return existingString;
}
}
char* ret = m_ptr;
if (m_ptr && nStrLen + 1 < (m_end - m_ptr))
{
memcpy(m_ptr, ptr, nStrLen);
m_ptr = m_ptr + nStrLen;
*m_ptr++ = 0; // add null termination.
}
else
{
int nNewBlockSize = std::max(nStrLen + 1, (int)m_blockSize);
AllocBlock(nNewBlockSize, nStrLen + 1);
PREFAST_ASSUME(m_ptr);
memcpy(m_ptr, ptr, nStrLen);
m_ptr = m_ptr + nStrLen;
*m_ptr++ = 0; // add null termination.
ret = m_start;
}
if (m_reuseStrings)
{
MEMSTAT_CONTEXT(EMemStatContextTypes::MSC_Other, 0, "String map");
assert(!FindExistingString(ptr, nStrLen));
m_stringToExistingStringMap[SStringData(ret, nStrLen)] = ret;
}
nUsedSpace += nStrLen;
return ret;
}
char* ReplaceString(const char* str1, const char* str2)
{
if (m_reuseStrings)
{
CryFatalError("Can't replace strings in an xml node that reuses strings");
}
int nStrLen1 = strlen(str1);
int nStrLen2 = strlen(str2);
// undo ptr1 add.
if (m_ptr != m_start)
m_ptr = m_ptr - nStrLen1 - 1;
assert(m_ptr == str1);
int nStrLen = nStrLen1 + nStrLen2;
char* ret = m_ptr;
if (m_ptr && nStrLen + 1 < (m_end - m_ptr))
{
if (m_ptr != str1) memcpy(m_ptr, str1, nStrLen1);
memcpy(m_ptr + nStrLen1, str2, nStrLen2);
m_ptr = m_ptr + nStrLen;
*m_ptr++ = 0; // add null termination.
}
else
{
int nNewBlockSize = std::max(nStrLen + 1, (int)m_blockSize);
if (m_ptr == m_start)
{
ReallocBlock(nNewBlockSize * 2); // Reallocate current block.
PREFAST_ASSUME(m_ptr);
memcpy(m_ptr + nStrLen1, str2, nStrLen2);
}
else
{
AllocBlock(nNewBlockSize, nStrLen + 1);
PREFAST_ASSUME(m_ptr);
memcpy(m_ptr, str1, nStrLen1);
memcpy(m_ptr + nStrLen1, str2, nStrLen2);
}
m_ptr = m_ptr + nStrLen;
*m_ptr++ = 0; // add null termination.
ret = m_start;
}
nUsedSpace += nStrLen;
return ret;
}
void GetMemoryUsage(ICrySizer* pSizer) const
{
BLOCK* pBlock = m_blocks;
while (pBlock)
{
pSizer->AddObject(pBlock, offsetof(BLOCK, s) + pBlock->size * sizeof(char));
pBlock = pBlock->next;
}
pBlock = m_free_blocks;
while (pBlock)
{
pSizer->AddObject(pBlock, offsetof(BLOCK, s) + pBlock->size * sizeof(char));
pBlock = pBlock->next;
}
}
private:
CSimpleStringPool(const CSimpleStringPool&);
CSimpleStringPool& operator=(const CSimpleStringPool&);
private:
void AllocBlock(int blockSize, int nMinBlockSize)
{
if (m_free_blocks)
{
BLOCK* pBlock = m_free_blocks;
BLOCK* pPrev = 0;
while (pBlock)
{
if (pBlock->size >= nMinBlockSize)
{
// Reuse free block
if (pPrev)
pPrev->next = pBlock->next;
else
m_free_blocks = pBlock->next;
pBlock->next = m_blocks;
m_blocks = pBlock;
m_ptr = pBlock->s;
m_start = pBlock->s;
m_end = pBlock->s + pBlock->size;
return;
}
pPrev = pBlock;
pBlock = pBlock->next;
}
}
size_t nMallocSize = offsetof(BLOCK, s) + blockSize * sizeof(char);
g_nTotalAllocInXmlStringPools += nMallocSize;
BLOCK* pBlock = (BLOCK*)malloc(nMallocSize);
;
assert(pBlock);
pBlock->size = blockSize;
pBlock->next = m_blocks;
m_blocks = pBlock;
m_ptr = pBlock->s;
m_start = pBlock->s;
m_end = pBlock->s + blockSize;
nUsedBlocks++;
}
void ReallocBlock(int blockSize)
{
if (m_reuseStrings)
{
CryFatalError("Can't replace strings in an xml node that reuses strings");
}
BLOCK* pThisBlock = m_blocks;
BLOCK* pPrevBlock = m_blocks->next;
m_blocks = pPrevBlock;
size_t nMallocSize = offsetof(BLOCK, s) + blockSize * sizeof(char);
if (pThisBlock)
{
g_nTotalAllocInXmlStringPools -= (offsetof(BLOCK, s) + pThisBlock->size * sizeof(char));
}
g_nTotalAllocInXmlStringPools += nMallocSize;
BLOCK* pBlock = (BLOCK*)realloc(pThisBlock, nMallocSize);
assert(pBlock);
pBlock->size = blockSize;
pBlock->next = m_blocks;
m_blocks = pBlock;
m_ptr = pBlock->s;
m_start = pBlock->s;
m_end = pBlock->s + blockSize;
}
char* FindExistingString(const char* szString, int nStrLen)
{
SStringData testData(szString, nStrLen);
char* szResult = stl::find_in_map(m_stringToExistingStringMap, testData, NULL);
assert(!szResult || !stricmp(szResult, szString));
return szResult;
}
};
#endif // __SimpleStringPool_h__
| 412 | 0.974761 | 1 | 0.974761 | game-dev | MEDIA | 0.159644 | game-dev | 0.942025 | 1 | 0.942025 |
daydayasobi/TowerDefense-TEngine-Demo | 6,104 | Packages/UniTask/Runtime/Linq/TakeUntilCanceled.cs | using Cysharp.Threading.Tasks.Internal;
using System;
using System.Threading;
namespace Cysharp.Threading.Tasks.Linq
{
public static partial class UniTaskAsyncEnumerable
{
public static IUniTaskAsyncEnumerable<TSource> TakeUntilCanceled<TSource>(this IUniTaskAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
{
Error.ThrowArgumentNullException(source, nameof(source));
return new TakeUntilCanceled<TSource>(source, cancellationToken);
}
}
internal sealed class TakeUntilCanceled<TSource> : IUniTaskAsyncEnumerable<TSource>
{
readonly IUniTaskAsyncEnumerable<TSource> source;
readonly CancellationToken cancellationToken;
public TakeUntilCanceled(IUniTaskAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
{
this.source = source;
this.cancellationToken = cancellationToken;
}
public IUniTaskAsyncEnumerator<TSource> GetAsyncEnumerator(CancellationToken cancellationToken = default)
{
return new _TakeUntilCanceled(source, this.cancellationToken, cancellationToken);
}
sealed class _TakeUntilCanceled : MoveNextSource, IUniTaskAsyncEnumerator<TSource>
{
static readonly Action<object> CancelDelegate1 = OnCanceled1;
static readonly Action<object> CancelDelegate2 = OnCanceled2;
static readonly Action<object> MoveNextCoreDelegate = MoveNextCore;
readonly IUniTaskAsyncEnumerable<TSource> source;
CancellationToken cancellationToken1;
CancellationToken cancellationToken2;
CancellationTokenRegistration cancellationTokenRegistration1;
CancellationTokenRegistration cancellationTokenRegistration2;
bool isCanceled;
IUniTaskAsyncEnumerator<TSource> enumerator;
UniTask<bool>.Awaiter awaiter;
public _TakeUntilCanceled(IUniTaskAsyncEnumerable<TSource> source, CancellationToken cancellationToken1, CancellationToken cancellationToken2)
{
this.source = source;
this.cancellationToken1 = cancellationToken1;
this.cancellationToken2 = cancellationToken2;
if (cancellationToken1.CanBeCanceled)
{
this.cancellationTokenRegistration1 = cancellationToken1.RegisterWithoutCaptureExecutionContext(CancelDelegate1, this);
}
if (cancellationToken1 != cancellationToken2 && cancellationToken2.CanBeCanceled)
{
this.cancellationTokenRegistration2 = cancellationToken2.RegisterWithoutCaptureExecutionContext(CancelDelegate2, this);
}
TaskTracker.TrackActiveTask(this, 3);
}
public TSource Current { get; private set; }
public UniTask<bool> MoveNextAsync()
{
if (cancellationToken1.IsCancellationRequested) isCanceled = true;
if (cancellationToken2.IsCancellationRequested) isCanceled = true;
if (enumerator == null)
{
enumerator = source.GetAsyncEnumerator(cancellationToken2); // use only AsyncEnumerator provided token.
}
if (isCanceled) return CompletedTasks.False;
completionSource.Reset();
SourceMoveNext();
return new UniTask<bool>(this, completionSource.Version);
}
void SourceMoveNext()
{
try
{
awaiter = enumerator.MoveNextAsync().GetAwaiter();
if (awaiter.IsCompleted)
{
MoveNextCore(this);
}
else
{
awaiter.SourceOnCompleted(MoveNextCoreDelegate, this);
}
}
catch (Exception ex)
{
completionSource.TrySetException(ex);
}
}
static void MoveNextCore(object state)
{
var self = (_TakeUntilCanceled)state;
if (self.TryGetResult(self.awaiter, out var result))
{
if (result)
{
if (self.isCanceled)
{
self.completionSource.TrySetResult(false);
}
else
{
self.Current = self.enumerator.Current;
self.completionSource.TrySetResult(true);
}
}
else
{
self.completionSource.TrySetResult(false);
}
}
}
static void OnCanceled1(object state)
{
var self = (_TakeUntilCanceled)state;
if (!self.isCanceled)
{
self.cancellationTokenRegistration2.Dispose();
self.completionSource.TrySetResult(false);
}
}
static void OnCanceled2(object state)
{
var self = (_TakeUntilCanceled)state;
if (!self.isCanceled)
{
self.cancellationTokenRegistration1.Dispose();
self.completionSource.TrySetResult(false);
}
}
public UniTask DisposeAsync()
{
TaskTracker.RemoveTracking(this);
cancellationTokenRegistration1.Dispose();
cancellationTokenRegistration2.Dispose();
if (enumerator != null)
{
return enumerator.DisposeAsync();
}
return default;
}
}
}
} | 412 | 0.831038 | 1 | 0.831038 | game-dev | MEDIA | 0.306836 | game-dev | 0.852806 | 1 | 0.852806 |
EphemeralSpace/ephemeral-space | 2,633 | Content.Server/GameTicking/Rules/MaxTimeRestartRuleSystem.cs | using System.Threading;
using Content.Server.Chat.Managers;
using Content.Server.GameTicking.Rules.Components;
using Content.Shared.GameTicking.Components;
using Timer = Robust.Shared.Timing.Timer;
namespace Content.Server.GameTicking.Rules;
public sealed class MaxTimeRestartRuleSystem : GameRuleSystem<MaxTimeRestartRuleComponent>
{
[Dependency] private readonly IChatManager _chatManager = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<GameRunLevelChangedEvent>(RunLevelChanged);
}
protected override void Started(EntityUid uid, MaxTimeRestartRuleComponent component, GameRuleComponent gameRule, GameRuleStartedEvent args)
{
base.Started(uid, component, gameRule, args);
if(GameTicker.RunLevel == GameRunLevel.InRound)
RestartTimer(component);
}
protected override void Ended(EntityUid uid, MaxTimeRestartRuleComponent component, GameRuleComponent gameRule, GameRuleEndedEvent args)
{
base.Ended(uid, component, gameRule, args);
StopTimer(component);
}
public void RestartTimer(MaxTimeRestartRuleComponent component)
{
// TODO FULL GAME SAVE
component.TimerCancel.Cancel();
component.TimerCancel = new CancellationTokenSource();
Timer.Spawn(component.RoundMaxTime, () => TimerFired(component), component.TimerCancel.Token);
}
public void StopTimer(MaxTimeRestartRuleComponent component)
{
component.TimerCancel.Cancel();
}
private void TimerFired(MaxTimeRestartRuleComponent component)
{
GameTicker.EndRound(Loc.GetString("rule-time-has-run-out"));
_chatManager.DispatchServerAnnouncement(Loc.GetString("rule-restarting-in-seconds",("seconds", (int) component.RoundEndDelay.TotalSeconds)));
// TODO FULL GAME SAVE
Timer.Spawn(component.RoundEndDelay, () => GameTicker.RestartRound());
}
private void RunLevelChanged(GameRunLevelChangedEvent args)
{
var query = EntityQueryEnumerator<MaxTimeRestartRuleComponent, GameRuleComponent>();
while (query.MoveNext(out var uid, out var timer, out var gameRule))
{
if (!GameTicker.IsGameRuleActive(uid, gameRule))
return;
switch (args.New)
{
case GameRunLevel.InRound:
RestartTimer(timer);
break;
case GameRunLevel.PreRoundLobby:
case GameRunLevel.PostRound:
StopTimer(timer);
break;
}
}
}
}
| 412 | 0.959025 | 1 | 0.959025 | game-dev | MEDIA | 0.92908 | game-dev | 0.960902 | 1 | 0.960902 |
design-to-production/D2P-Components | 1,801 | D2P_Core/Utility/IO.cs | using D2P_Core.Interfaces;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace D2P_Core.Utility
{
public static class IO
{
public static void Export(IComponent component, string directoryPath)
{
component.ActiveDoc.Objects.UnselectAll();
foreach (var rhObj in component.RHObjects)
{
rhObj.Select(true, false, true, true, true, true);
}
var fileName = Path.Combine(directoryPath, component.ShortName + ".3dm");
component.ActiveDoc.ExportSelected(fileName);
component.ActiveDoc.Objects.UnselectAll();
}
public static void ExportWithHeadless(IComponent component, string directoryPath)
{
var headlessDoc = RHDoc.CreateHeadless(component.ActiveDoc);
RHDoc.AddToRhinoDoc(component, headlessDoc);
RHDoc.Purge(headlessDoc);
var fileName = Path.Combine(directoryPath, component.ShortName + ".3dm");
headlessDoc.Export(fileName);
}
public static void ExportWithHeadless(IEnumerable<IComponent> components, string directory, string fileName)
{
if (!components.Any())
return;
var activeDoc = components.FirstOrDefault()?.ActiveDoc;
var headlessDoc = RHDoc.CreateHeadless(activeDoc);
foreach (var component in components)
{
RHDoc.AddToRhinoDoc(component, headlessDoc);
}
RHDoc.Purge(headlessDoc);
var filePath = Path.Combine(directory, fileName);
if (!Path.HasExtension(filePath))
filePath = Path.ChangeExtension(filePath, "3dm");
headlessDoc.Export(filePath);
}
}
}
| 412 | 0.874219 | 1 | 0.874219 | game-dev | MEDIA | 0.133142 | game-dev | 0.874996 | 1 | 0.874996 |
tekkub/wow-ui-source | 4,609 | AddOns/Blizzard_SharedMapDataProviders/ActiveQuestDataProvider.lua | ActiveQuestDataProviderMixin = CreateFromMixins(MapCanvasDataProviderMixin);
function ActiveQuestDataProviderMixin:OnAdded(mapCanvas)
MapCanvasDataProviderMixin.OnAdded(self, mapCanvas);
self:RegisterEvent("QUEST_LOG_UPDATE");
self:RegisterEvent("QUEST_WATCH_LIST_CHANGED");
self:RegisterEvent("QUEST_POI_UPDATE");
self:RegisterEvent("SUPER_TRACKED_QUEST_CHANGED");
end
function ActiveQuestDataProviderMixin:OnEvent(event, ...)
if event == "QUEST_LOG_UPDATE" then
self:RefreshAllData();
elseif event == "QUEST_WATCH_LIST_CHANGED" then
self:RefreshAllData();
elseif event == "QUEST_POI_UPDATE" then
self:RefreshAllData();
elseif event == "SUPER_TRACKED_QUEST_CHANGED" then
self:RefreshAllData();
end
end
function ActiveQuestDataProviderMixin:RemoveAllData()
self:GetMap():RemoveAllPinsByTemplate("ActiveQuestPinTemplate");
end
function ActiveQuestDataProviderMixin:RefreshAllData(fromOnShow)
self:RemoveAllData();
local mapAreaID = self:GetMap():GetMapID();
for zoneIndex = 1, C_MapCanvas.GetNumZones(mapAreaID) do
local zoneMapID, zoneName, zoneDepth, left, right, top, bottom = C_MapCanvas.GetZoneInfo(mapAreaID, zoneIndex);
if zoneDepth <= 1 then -- Exclude subzones
local activeQuestInfo = GetQuestsForPlayerByMapID(zoneMapID, mapAreaID);
if activeQuestInfo then
local superTrackedQuestID = GetSuperTrackedQuestID();
for i, info in ipairs(activeQuestInfo) do
if (IsQuestComplete(info.questID) or info.questID == superTrackedQuestID) and not QuestUtils_IsQuestWorldQuest(info.questID) then
self:AddActiveQuest(info.questID, info.x, info.y);
end
end
end
end
end
end
function ActiveQuestDataProviderMixin:AddActiveQuest(questID, x, y)
local pin = self:GetMap():AcquirePin("ActiveQuestPinTemplate");
pin.questID = questID;
local isSuperTracked = questID == GetSuperTrackedQuestID();
if ( isSuperTracked ) then
pin:SetFrameLevel(100);
else
pin:SetFrameLevel(50);
end
pin.Number:ClearAllPoints();
pin.Number:SetPoint("CENTER");
if IsQuestComplete(questID) then
-- If the quest is super tracked we want to show the selected circle behind it.
if ( isSuperTracked ) then
pin.Texture:SetSize(89, 90);
pin.Highlight:SetSize(89, 90);
pin.Number:SetSize(74, 74);
pin.Number:ClearAllPoints();
pin.Number:SetPoint("CENTER", -1, -1);
pin.Texture:SetTexture("Interface/WorldMap/UI-QuestPoi-NumberIcons");
pin.Texture:SetTexCoord(0.500, 0.625, 0.375, 0.5);
pin.Highlight:SetTexture("Interface/WorldMap/UI-QuestPoi-NumberIcons");
pin.Highlight:SetTexCoord(0.625, 0.750, 0.875, 1);
pin.Number:SetTexture("Interface/WorldMap/UI-WorldMap-QuestIcon");
pin.Number:SetTexCoord(0, 0.5, 0, 0.5);
pin.Number:Show();
else
pin.Texture:SetSize(95, 95);
pin.Highlight:SetSize(95, 95);
pin.Number:SetSize(85, 85);
pin.Texture:SetTexture("Interface/WorldMap/UI-WorldMap-QuestIcon");
pin.Highlight:SetTexture("Interface/WorldMap/UI-WorldMap-QuestIcon");
pin.Texture:SetTexCoord(0, 0.5, 0, 0.5);
pin.Highlight:SetTexCoord(0.5, 1, 0, 0.5);
pin.Number:Hide();
end
elseif ( isSuperTracked ) then
pin.style = "numeric"; -- for tooltip
pin.Texture:SetSize(75, 75);
pin.Highlight:SetSize(75, 75);
pin.Number:SetSize(85, 85);
pin.Texture:SetTexture("Interface/WorldMap/UI-QuestPoi-NumberIcons");
pin.Highlight:SetTexture("Interface/WorldMap/UI-QuestPoi-NumberIcons");
pin.Texture:SetTexCoord(0.500, 0.625, 0.375, 0.5);
pin.Highlight:SetTexCoord(0.625, 0.750, 0.375, 0.5);
-- try to match the number with tracker POI if possible
local questNumber = 1;
local poiButton = QuestPOI_FindButton(ObjectiveTrackerFrame.BlocksFrame, questID);
if ( poiButton and poiButton.style == "numeric" ) then
questNumber = poiButton.index;
end
pin.Number:SetTexCoord(QuestPOI_CalculateNumericTexCoords(questNumber, QUEST_POI_COLOR_BLACK));
pin.Number:Show();
end
pin:SetPosition(x, y);
pin:Show();
end
--[[ Active Quest Pin ]]--
ActiveQuestPinMixin = CreateFromMixins(MapCanvasPinMixin);
function ActiveQuestPinMixin:OnLoad()
self:SetAlphaLimits(1.0, 1.0, 1.0);
self:SetScalingLimits(1, 1.5, 0.50);
self.UpdateTooltip = self.OnMouseEnter;
-- Flight points can nudge quest pins.
self:SetNudgeTargetFactor(0.015);
self:SetNudgeZoomedOutFactor(1.0);
self:SetNudgeZoomedInFactor(0.25);
end
function ActiveQuestPinMixin:OnMouseEnter()
WorldMap_HijackTooltip(self:GetMap());
WorldMapQuestPOI_SetTooltip(self, GetQuestLogIndexByID(self.questID));
end
function ActiveQuestPinMixin:OnMouseLeave()
WorldMapPOIButton_OnLeave(self);
WorldMap_RestoreTooltip();
end | 412 | 0.895991 | 1 | 0.895991 | game-dev | MEDIA | 0.712207 | game-dev | 0.891704 | 1 | 0.891704 |
kessiler/muOnline-season6 | 1,134 | client/zClient/OffTrade.cpp | #include "stdafx.h"
#include "OffTrade.h"
#include "TMemory.h"
#ifdef __ALIEN__
cOffTrade gOffTrade;
void cOffTrade::Init()
{
this->TypeShop = 0;
SetOp((LPVOID)0x007E44F1, (LPVOID)this->ShowPrice, ASM::CALL);
SetOp((LPVOID)0x007E4603, (LPVOID)this->ShowTwoString, ASM::CALL);
}
void cOffTrade::RecvPShop(PMSG_ANS_BUYLIST_FROM_PSHOP *Data)
{
if(!strcmp(Data->szPShopText,WCOIN_SHOP))
{
this->TypeShop = 1;
}
else if(!strcmp(Data->szPShopText,SOUL_SHOP))
{
this->TypeShop = 2;
}
else
{
this->TypeShop = 0;
}
}
void cOffTrade::ShowPrice(DWORD a1, const char *a2, char *Price)
{
if(gOffTrade.TypeShop == 1)
{
pShowPrice(a1,"Selling Price: %s WCoin",Price);
}
else if(gOffTrade.TypeShop == 2)
{
pShowPrice(a1,"Selling Price: %s Jewel Of Soul",Price);
}
else
{
pShowPrice(a1,"Selling Price: %s Zen",Price);
}
}
void cOffTrade::ShowTwoString(DWORD a1, const char *a2)
{
if(gOffTrade.TypeShop == 1)
{
pShowPrice(a1,"You are short of WCoin");
}
else if(gOffTrade.TypeShop == 2)
{
pShowPrice(a1,"You are short of Soul");
}
else
{
pShowPrice(a1,"You are short of Zen");
}
}
#endif | 412 | 0.846431 | 1 | 0.846431 | game-dev | MEDIA | 0.357563 | game-dev | 0.863335 | 1 | 0.863335 |
Nexus-Mods/Nexus-Mod-Manager | 3,455 | Game Modes/Sims4/Sims4GameModeDescriptor.cs | using System;
using System.IO;
using System.Drawing;
using System.Collections.Generic;
namespace Nexus.Client.Games.Sims4
{
/// <summary>
/// Provides common information about Sims4 based games.
/// </summary>
public class Sims4GameModeDescriptor : GameModeDescriptorBase
{
private static string[] EXECUTABLES = { @"Game\Bin\TS4_x64.exe" };
private const string MODE_ID = "TheSims4";
private static readonly List<string> STOP_FOLDERS = new List<string> { "Mods", "Tray" };
#region Properties
/// <summary>
/// Gets the directory where Sims4 plugins are installed.
/// </summary>
/// <value>The directory where Sims4 plugins are installed.</value>
public override string PluginDirectory
{
get
{
string strPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
strPath = Path.Combine(strPath, @"Electronic Arts\The Sims 4");
if (!Directory.Exists(strPath))
Directory.CreateDirectory(strPath);
return strPath;
}
}
/// <summary>
/// Gets the path to which mod files should be installed.
/// </summary>
/// <value>The path to which mod files should be installed.</value>
public override string InstallationPath
{
get
{
string strPath = string.Empty;
if (EnvironmentInfo.Settings.InstallationPaths.ContainsKey(ModeId))
{
strPath = EnvironmentInfo.Settings.InstallationPaths[ModeId];
}
if (string.IsNullOrEmpty(strPath))
{
strPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
strPath = Path.Combine(strPath, @"Electronic Arts\The Sims 4");
EnvironmentInfo.Settings.InstallationPaths[ModeId] = strPath;
EnvironmentInfo.Settings.Save();
}
return strPath;
}
}
/// <summary>
/// Gets the display name of the game mode.
/// </summary>
/// <value>The display name of the game mode.</value>
public override string Name
{
get
{
return "The Sims 4";
}
}
/// <summary>
/// Gets the unique id of the game mode.
/// </summary>
/// <value>The unique id of the game mode.</value>
public override string ModeId
{
get
{
return MODE_ID;
}
}
/// <summary>
/// Gets the list of possible executable files for the game.
/// </summary>
/// <value>The list of possible executable files for the game.</value>
public override string[] GameExecutables
{
get
{
return EXECUTABLES;
}
}
/// <summary>
/// Gets a list of possible folders that should be looked for in mod archives to determine
/// file structure.
/// </summary>
/// <value>A list of possible folders that should be looked for in mod archives to determine
/// file structure.</value>
public override IEnumerable<string> StopFolders
{
get
{
return STOP_FOLDERS;
}
}
/// <summary>
/// Gets the theme to use for this game mode.
/// </summary>
/// <value>The theme to use for this game mode.</value>
public override Theme ModeTheme
{
get
{
return new Theme(Properties.Resources.Sims4_logo, Color.FromArgb(59, 145, 16), null);
}
}
#endregion
#region Constructors
/// <summary>
/// A simple constructor that initializes the object with the given dependencies.
/// </summary>
/// <param name="p_eifEnvironmentInfo">The application's envrionment info.</param>
public Sims4GameModeDescriptor(IEnvironmentInfo p_eifEnvironmentInfo)
: base(p_eifEnvironmentInfo)
{
}
#endregion
}
}
| 412 | 0.678522 | 1 | 0.678522 | game-dev | MEDIA | 0.813887 | game-dev | 0.863575 | 1 | 0.863575 |
Secrets-of-Sosaria/World | 5,066 | Data/Scripts/Items/Misc/Scrolls/ScrollofAlacrity.cs | /***************************************************************************
* ScrollofAlacrity.cs
* -------------------
* begin : June 1, 2009
* copyright : (C) Shai'Tan Malkier aka Callandor2k
* email : ShaiTanMalkier@gmail.com
*
* $Id: ScrollofAlacrity.cs 1 2009-06-1 04:28:39Z Callandor2k $
*
***************************************************************************/
/***************************************************************************
*
* This Script/File is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
using Server;
using Server.Gumps;
using Server.Network;
using Server.Mobiles;
using System.Collections;
using Server.Engines.Quests;
using System.Collections.Generic;
namespace Server.Items
{
public class ScrollofAlacrity : SpecialScroll
{
public override int LabelNumber { get { return 1078604; } } // Scroll of Alacrity
public override int Message { get { return 1078602; } } /*using a Scroll of Transcendence for a given skill will permanently increase your current
*level in that skill by the amount of points displayed on the scroll.
*As you may not gain skills beyond your maximum skill cap, any excess points will be lost.*/
public override string DefaultTitle { get { return String.Format( "Scroll of Alacrity:" ); } }
public override string GetNameLocalized()
{
return Name;
}
public override string GetName()
{
return Name;
}
public ScrollofAlacrity() : this( SkillName.Alchemy )
{
}
[Constructable]
public ScrollofAlacrity( SkillName skill ) : base( skill, 0.0 )
{
Name = "Scroll of Alacrity";
ItemID = 0x14EF;
Hue = 0x4AB;
}
public ScrollofAlacrity(Serial serial) : base(serial)
{
}
public override void GetProperties(ObjectPropertyList list)
{
base.GetProperties(list);
list.Add(1071345, "{0} 15 Minutes", SkillInfo.Table[(int)Skill].Name ); // Skill: ~1_val~
}
public override bool CanUse( Mobile from )
{
if ( !base.CanUse( from ) )
return false;
PlayerMobile pm = from as PlayerMobile;
if ( pm == null )
return false;
#region Mondain's Legacy
/* to add when skillgain quests will be implemented
for (int i = pm.Quests.Count - 1; i >= 0; i--)
{
BaseQuest quest = pm.Quests[i];
for (int j = quest.Objectives.Count - 1; j >= 0; j--)
{
BaseObjective objective = quest.Objectives[j];
if (objective is ApprenticeObjective)
{
from.SendMessage("You are already under the effect of an enhanced skillgain quest.");
return false;
}
}
}
*/
#endregion
#region Scroll of Alacrity
if (pm.AcceleratedStart > DateTime.Now)
{
from.SendLocalizedMessage(1077951); // You are already under the effect of an accelerated skillgain scroll.
return false;
}
#endregion
return true;
}
public override void Use( Mobile from )
{
if ( !CanUse( from ) )
return;
PlayerMobile pm = from as PlayerMobile;
if ( pm == null )
return;
double tskill = from.Skills[Skill].Base;
double tcap = from.Skills[Skill].Cap;
if ( tskill >= tcap || from.Skills[Skill].Lock != SkillLock.Up )
{
from.SendLocalizedMessage( 1094935 ); /*You cannot increase this skill at this time. The skill may be locked or set to lower in your skill menu.
*If you are at your total skill cap, you must use a Powerscroll to increase your current skill cap.*/
return;
}
from.SendLocalizedMessage( 1077956 ); // You are infused with intense energy. You are under the effects of an accelerated skillgain scroll.
Effects.PlaySound( from.Location, from.Map, 0x1E9 );
Effects.SendTargetParticles( from, 0x373A, 35, 45, 0x00, 0x00, 9502, (EffectLayer)255, 0x100 );
pm.AcceleratedStart = DateTime.Now + TimeSpan.FromMinutes(15);
Timer t = (Timer)m_Table[from];
m_Table[from] = Timer.DelayCall( TimeSpan.FromMinutes( 15 ), new TimerStateCallback( Expire_Callback ), from );
pm.AcceleratedSkill = Skill;
Delete();
}
private static Hashtable m_Table = new Hashtable();
private static void Expire_Callback(object state)
{
Mobile m = (Mobile)state;
m_Table.Remove(m);
m.PlaySound(0x1F8);
m.SendLocalizedMessage(1077957);// The intense energy dissipates. You are no longer under the effects of an accelerated skillgain scroll.
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = ( InheritsItem ? 0 : reader.ReadInt() ); //Required for SpecialScroll insertion
LootType = LootType.Cursed;
Insured = false;
}
}
}
| 412 | 0.791642 | 1 | 0.791642 | game-dev | MEDIA | 0.985413 | game-dev | 0.88621 | 1 | 0.88621 |
ProjectIgnis/CardScripts | 1,315 | official/c59482302.lua | --A・ボム
--Ally Salvo
local s,id=GetID()
function s.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetCategory(CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_BATTLE_DESTROYED)
e1:SetCondition(s.condition)
e1:SetTarget(s.target)
e1:SetOperation(s.operation)
c:RegisterEffect(e1)
end
function s.condition(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsLocation(LOCATION_GRAVE) and e:GetHandler():IsReason(REASON_BATTLE)
and e:GetHandler():GetReasonCard():IsAttribute(ATTRIBUTE_LIGHT)
end
function s.filter(c,e)
return c:IsCanBeEffectTarget(e)
end
function s.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsOnField() and s.filter(chkc,e) end
if chk==0 then return true end
local g=Duel.GetMatchingGroup(s.filter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,nil,e)
if #g>1 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local sg=g:Select(tp,2,2,nil)
Duel.SetTargetCard(sg)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,sg,2,0,0)
end
end
function s.operation(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS)
if not g then return end
local dg=g:Filter(Card.IsRelateToEffect,nil,e)
Duel.Destroy(dg,REASON_EFFECT)
end | 412 | 0.849976 | 1 | 0.849976 | game-dev | MEDIA | 0.989219 | game-dev | 0.927143 | 1 | 0.927143 |
rds1983/DigitalRune | 4,440 | Source/DigitalRune.Geometry/Partitioning/BVH/Compressed BVH/CompressedAabbTree_Node.cs | // DigitalRune Engine - Copyright (C) DigitalRune GmbH
// This file is subject to the terms and conditions defined in
// file 'LICENSE.TXT', which is part of this source code package.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace DigitalRune.Geometry.Partitioning
{
partial class CompressedAabbTree
{
/// <summary>
/// Represents a node of an <see cref="CompressedAabbTree"/>.
/// </summary>
/// <remarks>
/// <para>
/// The minimum and maximum of the AABB are stored as quantized 16-bit integer values.
/// </para>
/// <para>
/// The <see cref="CompressedAabbTree"/> supports a stackless, non-recursive traversal of the
/// tree. The tree is traversed in pre-order traversal order. The nodes are stored in the order
/// as they are visited in the traversal: The left child follows the parent node. The right
/// child follows after the left subtree. If a node is a leaf then the right sibling directly
/// follows. The leaf nodes store the actual items of the AABB tree. Each non-leaf stores an
/// 'escape offset'. This offset points to the node that follows in the traversal if we stop
/// traversing a left subtree and continue with its right subtree. By using an escape offset we
/// do not need to store the root of the right subtree on a stack (implicitly or explicitly).
/// </para>
/// <para>
/// The field <see cref="EscapeOffsetOrItem"/> is negative if the node is an internal node and
/// the field contains an escape offset (<c>escapeOffset = -node.EscapeOffsetOrItem</c>). The
/// value is positive if the node is a leaf and contains an item index.
/// </para>
/// </remarks>
[StructLayout(LayoutKind.Explicit)]
internal struct Node
{
/// <summary>
/// The quantized minimum of the AABB (x component).
/// </summary>
[FieldOffset(0)]
public ushort MinimumX;
/// <summary>
/// The quantized minimum of the AABB (y component).
/// </summary>
[FieldOffset(2)]
public ushort MinimumY;
/// <summary>
/// The quantized minimum of the AABB (z component).
/// </summary>
[FieldOffset(4)]
public ushort MinimumZ;
/// <summary>
/// The quantized maximum of the AABB (x component).
/// </summary>
[FieldOffset(6)]
public ushort MaximumX;
/// <summary>
/// The quantized maximum of the AABB (y component).
/// </summary>
[FieldOffset(8)]
public ushort MaximumY;
/// <summary>
/// The quantized maximum of the AABB (z component).
/// </summary>
[FieldOffset(10)]
public ushort MaximumZ;
/// <summary>
/// The escape offset (if negative) or the item index.
/// </summary>
[FieldOffset(12)]
internal int EscapeOffsetOrItem;
/// <summary>
/// Gets a value indicating whether this instance is leaf node.
/// </summary>
/// <value>
/// <see langword="true"/> if this instance is leaf; otherwise, <see langword="false"/> if it
/// is an internal node.
/// </value>
public bool IsLeaf
{
get { return EscapeOffsetOrItem >= 0; }
}
/// <summary>
/// Gets or sets the data held in this node.
/// </summary>
/// <value>The data of this node.</value>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="value"/> is negative.
/// </exception>
public int Item
{
get
{
Debug.Assert(IsLeaf, "AABB tree node does not contain data.");
return EscapeOffsetOrItem;
}
set
{
if (value < 0)
throw new ArgumentOutOfRangeException("value", "A compressed AABB tree cannot store negative values.");
EscapeOffsetOrItem = value;
}
}
/// <summary>
/// Gets or sets the escape offset of this node.
/// </summary>
/// <value>The escape offset of this node.</value>
public int EscapeOffset
{
get
{
Debug.Assert(!IsLeaf, "AABB tree node does not contain an escape offset.");
return -EscapeOffsetOrItem;
}
set
{
Debug.Assert(value > 0, "Invalid escape offset.");
EscapeOffsetOrItem = -value;
}
}
}
}
}
| 412 | 0.806164 | 1 | 0.806164 | game-dev | MEDIA | 0.594564 | game-dev | 0.884624 | 1 | 0.884624 |
filiph/egamebook | 5,505 | edgehead/lib/src/fight/bite/actions/finish_bite.dart | import 'package:edgehead/fractal_stories/action.dart';
import 'package:edgehead/fractal_stories/actor.dart';
import 'package:edgehead/fractal_stories/anatomy/body_part.dart';
import 'package:edgehead/fractal_stories/anatomy/deal_tearing_damage.dart';
import 'package:edgehead/fractal_stories/context.dart';
import 'package:edgehead/fractal_stories/simulation.dart';
import 'package:edgehead/fractal_stories/storyline/storyline.dart';
import 'package:edgehead/fractal_stories/world_state.dart';
import 'package:edgehead/src/fight/bite/bite_situation.dart';
import 'package:edgehead/src/fight/common/attacker_situation.dart';
import 'package:edgehead/src/fight/common/drop_weapon.dart';
import 'package:edgehead/src/fight/common/fall.dart';
import 'package:edgehead/src/fight/common/humanoid_pain_or_death.dart';
class FinishBite extends OtherActorAction {
static final FinishBite singleton = FinishBite();
static const String className = "FinishBite";
@override
final String? helpMessage = null;
@override
final bool isAggressive = true;
/// The action that initiated the bite might have been proactive, but
/// the finish is just that, a finish.
@override
final bool isProactive = false;
@override
final bool isImplicit = true;
@override
final bool rerollable = true;
@override
final Resource rerollResource = Resource.stamina;
@override
List<String> get commandPathTemplate => const [];
@override
String get name => className;
@override
String get rollReasonTemplate => "(WARNING should not be user-visible)";
@override
String applyFailure(ActionContext context, Actor enemy) {
throw UnimplementedError();
}
@override
String applySuccess(ActionContext context, Actor enemy) {
Actor a = context.actor;
Simulation sim = context.simulation;
WorldStateBuilder w = context.outputWorld;
Storyline s = context.outputStoryline;
final damage = a.currentDamageCapability.tearingDamage;
final situation = context.world.currentSituation! as AttackerSituation;
assert(situation.name == biteSituationName);
final designation = situation.attackDirection.toBodyPartDesignation();
assert(a.currentWeaponOrBodyPart != null);
final result =
executeTearingHit(enemy, a.currentWeaponOrBodyPart!, designation);
w.updateActorById(enemy.id, (b) => b.replace(result.victim));
final thread = getThreadId(sim, w, biteSituationName);
bool killed = !result.victim.isAnimated && !result.victim.isInvincible;
if (!killed) {
a.report(
s,
"<subject> {sink<s> <subject's> teeth|bite<s>} into "
"<objectOwner's> <object>",
objectOwner: result.victim,
object: result.touchedPart,
positive: true,
actionThread: thread);
// Summarize.
a.report(s, "<subject> {lunge<s>|launch<es> <subjectPronounSelf>}",
positive: true, actionThread: thread, replacesThread: true);
a.report(
s,
"<subject> {sink<s> <subject's> teeth|bite<s>} into "
"<objectOwner's> <object>",
objectOwner: result.victim,
object: result.touchedPart,
positive: true,
actionThread: thread,
replacesThread: true);
if (result.disabled &&
(result.touchedPart.function == BodyPartFunction.damageDealing ||
result.touchedPart.function == BodyPartFunction.mobile ||
result.touchedPart.function == BodyPartFunction.wielding)) {
result.touchedPart.report(s, "<subject> go<es> limp",
negative: true, actionThread: thread);
}
if (result.willDropCurrentWeapon) {
final weapon = dropCurrentWeapon(w, result.victim.id, forced: true);
result.victim.report(s, "<subject> drop<s> <object>",
object: weapon, negative: true, actionThread: thread);
}
if (result.willFall) {
result.victim.report(s, "<subject> fall<s> {|down|to the ground}",
negative: true, actionThread: thread);
makeActorFall(context.world, w, s, result.victim);
}
inflictPain(context, result.victim.id, damage, result.touchedPart);
if (result.wasBlinding) {
result.victim.report(s, "<subject> <is> now blind", negative: true);
}
} else {
a.report(
s,
"<subject's> teeth {rip|tear|bite} into "
"<objectOwner's> <object>",
objectOwner: result.victim,
object: result.touchedPart,
positive: true,
actionThread: thread);
// Summarize.
a.report(s, "<subject> {lunge<s>|launch<es> <subjectPronounSelf>}",
positive: true, actionThread: thread, replacesThread: true);
a.report(
s,
"<subject's> teeth {rip|tear|bite} into "
"<objectOwner's> <object>",
objectOwner: result.victim,
object: result.touchedPart,
positive: true,
actionThread: thread,
replacesThread: true);
killHumanoid(context, result.victim.id);
}
return "${a.name} bites${killed ? ' (and kills)' : ''} ${enemy.name} "
"($result)";
}
@override
ReasonedSuccessChance getSuccessChance(
Actor a, Simulation sim, WorldState w, Actor enemy) =>
ReasonedSuccessChance.sureSuccess;
@override
bool isApplicable(ApplicabilityContext c, Actor a, Simulation sim,
WorldState w, Actor enemy) =>
a.currentDamageCapability.isTearing;
}
| 412 | 0.876288 | 1 | 0.876288 | game-dev | MEDIA | 0.835005 | game-dev | 0.927472 | 1 | 0.927472 |
NASA-AMMOS/VICAR | 2,901 | vos/tae/src/IV_2.6/src/libInterviews/X11-sensor.c | /*
* Copyright (c) 1987, 1988, 1989 Stanford University
*
* Permission to use, copy, modify, distribute, and sell this software and its
* documentation for any purpose is hereby granted without fee, provided
* that the above copyright notice appear in all copies and that both that
* copyright notice and this permission notice appear in supporting
* documentation, and that the name of Stanford not be used in advertising or
* publicity pertaining to distribution of the software without specific,
* written prior permission. Stanford makes no representations about
* the suitability of this software for any purpose. It is provided "as is"
* without express or implied warranty.
*
* STANFORD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
* IN NO EVENT SHALL STANFORD BE LIABLE FOR ANY SPECIAL, INDIRECT OR
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
* DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* X11-dependent sensor code
*/
/*
* Change Log:
* 19-mar-93 HP compiler does not like some kinds of initialization...rt
*/
#include "itable.h"
#include <InterViews/sensor.h>
#include <InterViews/X11/Xlib.h>
#include <InterViews/X11/eventrep.h>
#include <InterViews/X11/worldrep.h>
Mask motionmask = PointerMotionMask;
Mask keymask = KeyPressMask;
Mask entermask = EnterWindowMask;
Mask leavemask = LeaveWindowMask;
Mask focusmask = FocusChangeMask;
Mask substructmask = SubstructureRedirectMask;
Mask upmask = ButtonPressMask|ButtonReleaseMask|OwnerGrabButtonMask;
Mask downmask = ButtonPressMask|ButtonReleaseMask|OwnerGrabButtonMask;
Mask initmask = PointerMotionHintMask;
static Sensor* grabber;
boolean Sensor::Interesting(Event& e) {
register XEvent& x = e.Rep()->event();
switch (x.type) {
case MotionNotify:
e.GetMotionInfo();
return true;
case KeyPress:
e.GetKeyInfo();
return ButtonIsSet(down, e.button);
case ButtonPress:
e.GetButtonInfo(DownEvent);
{
#if defined(hpux) || (defined(sun) && OSMajorVersion >= 5)
boolean b;
b = ButtonIsSet(down, e.button);
#else
boolean b = ButtonIsSet(down, e.button);
#endif
if (b && ButtonIsSet(up, e.button)) {
grabber = this;
} else {
grabber = nil;
}
return b;
}
case ButtonRelease:
e.GetButtonInfo(UpEvent);
return ButtonIsSet(up, e.button) || (grabber != nil);
case FocusIn:
e.eventType = FocusInEvent;
return true;
case FocusOut:
e.eventType = FocusOutEvent;
return true;
case EnterNotify:
return e.GetCrossingInfo(EnterEvent);
case LeaveNotify:
return e.GetCrossingInfo(LeaveEvent);
default:
/* ignore */;
}
return false;
}
| 412 | 0.916771 | 1 | 0.916771 | game-dev | MEDIA | 0.316682 | game-dev | 0.69677 | 1 | 0.69677 |
Aizistral-Studios/Enigmatic-Legacy | 6,538 | src/main/java/com/aizistral/enigmaticlegacy/items/TheInfinitum.java | package com.aizistral.enigmaticlegacy.items;
import java.util.List;
import com.aizistral.enigmaticlegacy.api.generic.SubscribeConfig;
import com.aizistral.enigmaticlegacy.api.items.IEldritch;
import com.aizistral.enigmaticlegacy.handlers.SuperpositionHandler;
import com.aizistral.enigmaticlegacy.helpers.ItemLoreHelper;
import com.aizistral.omniconfig.wrappers.Omniconfig;
import com.aizistral.omniconfig.wrappers.OmniconfigWrapper;
import net.minecraft.ChatFormatting;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.effect.MobEffects;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Rarity;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.item.UseAnim;
import net.minecraft.world.level.Level;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
public class TheInfinitum extends TheAcknowledgment implements IEldritch {
public static Omniconfig.DoubleParameter attackDamage;
public static Omniconfig.DoubleParameter attackSpeed;
public static Omniconfig.PerhapsParameter bossDamageBonus;
public static Omniconfig.PerhapsParameter knockbackBonus;
public static Omniconfig.PerhapsParameter lifestealBonus;
public static Omniconfig.PerhapsParameter undeadProbability;
@SubscribeConfig
public static void onConfig(OmniconfigWrapper builder) {
builder.pushPrefix("TheInfinitum");
attackDamage = builder
.comment("Attack damage of The Infinitum, actual damage shown in tooltip will be is 1 + this_value.")
.max(32768)
.getDouble("AttackDamage", 15);
attackSpeed = builder
.comment("Attack speed of The Infinitum.")
.minMax(32768)
.getDouble("AttackSpeed", -2.0);
bossDamageBonus = builder
.comment("Attack damage bonus of The Infinitum against players and bosses.")
.getPerhaps("BossDamageBonus", 200);
knockbackBonus = builder
.comment("Knockback bonus of The Infinitum. For Phantoms, this value is multiplied by 1.5.")
.getPerhaps("KnockbackPowerBonus", 200);
lifestealBonus = builder
.comment("Lifesteal bonus of The Infinitum.")
.getPerhaps("LifestealBonus", 10);
undeadProbability = builder
.comment("Chance of lethal damage prevention when holding The Infinitum.")
.max(100)
.getPerhaps("UndeadProbability", 85);
builder.popPrefix();
}
public TheInfinitum() {
super(getDefaultProperties().rarity(Rarity.EPIC).stacksTo(1).fireResistant(),
"the_infinitum", attackDamage.getValue(), attackSpeed.getValue());
this.setAllowAllEnchantments(true);
}
@Override
@OnlyIn(Dist.CLIENT)
public void appendHoverText(ItemStack stack, Level world, List<Component> list, TooltipFlag flag) {
if (Screen.hasShiftDown()) {
if (Minecraft.getInstance().player != null && SuperpositionHandler.isTheCursedOne(Minecraft.getInstance().player)) {
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.theInfinitum2");
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.theInfinitum3");
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.void");
}
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.theInfinitum4", ChatFormatting.GOLD, bossDamageBonus + "%");
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.theInfinitum5", ChatFormatting.GOLD, knockbackBonus + "%");
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.theInfinitum6", ChatFormatting.GOLD, lifestealBonus + "%");
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.void");
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.theInfinitum7");
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.void");
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.theInfinitum8");
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.void");
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.theInfinitum9", ChatFormatting.GOLD, undeadProbability + "%");
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.theInfinitum10");
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.void");
ItemLoreHelper.indicateWorthyOnesOnly(list);
} else {
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.theInfinitum1");
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.void");
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.holdShift");
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.void");
ItemLoreHelper.indicateCursedOnesOnly(list);
}
if (stack.isEnchanted()) {
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.void");
}
}
@Override
public boolean hurtEnemy(ItemStack stack, LivingEntity target, LivingEntity attacker) {
if (attacker instanceof ServerPlayer player && SuperpositionHandler.isTheWorthyOne(player)) {
target.addEffect(new MobEffectInstance(MobEffects.WITHER, 160, 3, false, true));
target.addEffect(new MobEffectInstance(MobEffects.CONFUSION, 500, 3, false, true));
target.addEffect(new MobEffectInstance(MobEffects.WEAKNESS, 300, 3, false, true));
target.addEffect(new MobEffectInstance(MobEffects.MOVEMENT_SLOWDOWN, 300, 3, false, true));
target.addEffect(new MobEffectInstance(MobEffects.DIG_SLOWDOWN, 300, 3, false, true));
target.addEffect(new MobEffectInstance(MobEffects.BLINDNESS, 100, 3, false, true));
}
return false;
}
@Override
public InteractionResultHolder<ItemStack> use(Level world, Player player, InteractionHand hand) {
if (!SuperpositionHandler.isTheWorthyOne(player))
return InteractionResultHolder.pass(player.getItemInHand(hand));
if (hand == InteractionHand.MAIN_HAND) {
ItemStack offhandStack = player.getOffhandItem();
if (offhandStack != null && (offhandStack.getItem().getUseAnimation(offhandStack) == UseAnim.BLOCK))
return new InteractionResultHolder<ItemStack>(InteractionResult.PASS, player.getItemInHand(hand));
}
return super.use(world, player, hand);
}
}
| 412 | 0.945612 | 1 | 0.945612 | game-dev | MEDIA | 0.97338 | game-dev | 0.992643 | 1 | 0.992643 |
CallocGD/GD-2.206-Decompiled | 1,214 | headers/Common/SetupCameraRotatePopup.h | #ifndef __SETUPCAMERAROTATEPOPUP_H__
#define __SETUPCAMERAROTATEPOPUP_H__
#include "../includes.h"
/* -- Predefined Subclasses -- */
class SetupTriggerPopup;
class SetupCameraRotatePopup: public SetupTriggerPopup {
public:
static SetupCameraRotatePopup* create(EffectGameObject* p0, cocos2d::CCArray* p1);
bool init(EffectGameObject* p0, cocos2d::CCArray* p1);
void onEasing(cocos2d::CCObject* sender);
void onEasingRate(cocos2d::CCObject* sender);
TodoReturn sliderChanged(cocos2d::CCObject* p0);
TodoReturn sliderDegreesChanged(cocos2d::CCObject* p0);
TodoReturn toggleEasingRateVisibility();
TodoReturn updateCommandDegrees();
TodoReturn updateDegreesLabel();
TodoReturn updateDuration();
TodoReturn updateDurLabel(bool p0);
TodoReturn updateEasingLabel();
TodoReturn updateEasingRateLabel();
TodoReturn updateMoveCommandEasing();
TodoReturn updateMoveCommandEasingRate();
virtual TodoReturn determineStartValues();
virtual void onClose(cocos2d::CCObject* sender);
virtual void textChanged(CCTextInputNode* p0);
virtual TodoReturn valuePopupClosed(ConfigureValuePopup* p0, float p1);
};
#endif /* __SETUPCAMERAROTATEPOPUP_H__ */ | 412 | 0.924587 | 1 | 0.924587 | game-dev | MEDIA | 0.479533 | game-dev | 0.696847 | 1 | 0.696847 |
IzzelAliz/Arclight | 1,074 | arclight-common/src/main/java/io/izzel/arclight/common/mixin/core/world/level/block/state/BlockBehaviour_BlockStateBaseMixin.java | package io.izzel.arclight.common.mixin.core.world.level.block.state;
import io.izzel.arclight.common.mod.util.ArclightCaptures;
import net.minecraft.core.BlockPos;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockBehaviour;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(BlockBehaviour.BlockStateBase.class)
public class BlockBehaviour_BlockStateBaseMixin {
@Inject(method = "entityInside", at = @At("HEAD"))
private void arclight$captureBlockCollide(Level worldIn, BlockPos pos, Entity entityIn, CallbackInfo ci) {
ArclightCaptures.captureDamageEventBlock(pos);
}
@Inject(method = "entityInside", at = @At("RETURN"))
private void arclight$resetBlockCollide(Level worldIn, BlockPos pos, Entity entityIn, CallbackInfo ci) {
ArclightCaptures.captureDamageEventBlock(null);
}
}
| 412 | 0.895405 | 1 | 0.895405 | game-dev | MEDIA | 0.990188 | game-dev | 0.864382 | 1 | 0.864382 |
josh-m/RW-Decompile | 2,467 | Verse/ShootLine.cs | using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace Verse
{
[HasDebugOutput]
public struct ShootLine
{
private IntVec3 source;
private IntVec3 dest;
public IntVec3 Source
{
get
{
return this.source;
}
}
public IntVec3 Dest
{
get
{
return this.dest;
}
}
public ShootLine(IntVec3 source, IntVec3 dest)
{
this.source = source;
this.dest = dest;
}
public void ChangeDestToMissWild(float aimOnChance)
{
float num = ShootTuning.MissDistanceFromAimOnChanceCurves.Evaluate(aimOnChance, Rand.Value);
if (num < 0f)
{
Log.ErrorOnce("Attempted to wild-miss less than zero tiles away", 94302089, false);
}
IntVec3 a;
do
{
Vector2 unitVector = Rand.UnitVector2;
Vector3 b = new Vector3(unitVector.x * num, 0f, unitVector.y * num);
a = (this.dest.ToVector3Shifted() + b).ToIntVec3();
}
while (Vector3.Dot((this.dest - this.source).ToVector3(), (a - this.source).ToVector3()) < 0f);
this.dest = a;
}
public IEnumerable<IntVec3> Points()
{
return GenSight.PointsOnLineOfSight(this.source, this.dest);
}
public override string ToString()
{
return string.Concat(new object[]
{
"(",
this.source,
"->",
this.dest,
")"
});
}
[DebugOutput]
public static void WildMissResults()
{
IntVec3 intVec = new IntVec3(100, 0, 0);
ShootLine shootLine = new ShootLine(IntVec3.Zero, intVec);
IEnumerable<int> enumerable = Enumerable.Range(0, 101);
IEnumerable<int> colValues = Enumerable.Range(0, 12);
int[,] results = new int[enumerable.Count<int>(), colValues.Count<int>()];
foreach (int current in enumerable)
{
for (int i = 0; i < 10000; i++)
{
ShootLine shootLine2 = shootLine;
shootLine2.ChangeDestToMissWild((float)current / 100f);
if (shootLine2.dest.z == 0 && shootLine2.dest.x > intVec.x)
{
results[current, shootLine2.dest.x - intVec.x]++;
}
}
}
DebugTables.MakeTablesDialog<int, int>(colValues, (int cells) => cells.ToString() + "-away\ncell\nhit%", enumerable, (int hitchance) => ((float)hitchance / 100f).ToStringPercent() + " aimon chance", delegate(int cells, int hitchance)
{
float num = (float)hitchance / 100f;
if (cells == 0)
{
return num.ToStringPercent();
}
return ((float)results[hitchance, cells] / 10000f * (1f - num)).ToStringPercent();
}, string.Empty);
}
}
}
| 412 | 0.794891 | 1 | 0.794891 | game-dev | MEDIA | 0.550401 | game-dev,graphics-rendering | 0.90581 | 1 | 0.90581 |
hengband/hengband | 12,636 | src/info-reader/dungeon-reader.cpp | #include "info-reader/dungeon-reader.h"
#include "info-reader/dungeon-info-tokens-table.h"
#include "info-reader/info-reader-util.h"
#include "info-reader/parse-error-types.h"
#include "info-reader/race-info-tokens-table.h"
#include "io/tokenizer.h"
#include "main/angband-headers.h"
#include "system/dungeon/dungeon-definition.h"
#include "system/dungeon/dungeon-list.h"
#include "system/enums/dungeon/dungeon-id.h"
#include "system/monrace/monrace-definition.h"
#include "system/terrain/terrain-definition.h"
#include "system/terrain/terrain-list.h"
#include "util/enum-converter.h"
#include "util/string-processor.h"
#include "view/display-messages.h"
#include <span>
/*!
* @brief テキストトークンを走査してフラグを一つ得る(ダンジョン用)
* @param dungeon ダンジョンへの参照
* @param what 参照元の文字列
* @return 見つけたらtrue
*/
static bool grab_one_dungeon_flag(DungeonDefinition &dungeon, std::string_view what)
{
if (EnumClassFlagGroup<DungeonFeatureType>::grab_one_flag(dungeon.flags, dungeon_flags, what)) {
return true;
}
msg_format(_("未知のダンジョン・フラグ '%s'。", "Unknown dungeon type flag '%s'."), what.data());
return false;
}
/*!
* @brief テキストトークンを走査してフラグを一つ得る(モンスターのダンジョン出現条件用1)
* @param dungeon ダンジョンへの参照
* @param what 参照元の文字列
* @return 見つけたらtrue
*/
static bool grab_one_basic_monster_flag(DungeonDefinition &dungeon, std::string_view what)
{
if (EnumClassFlagGroup<MonsterResistanceType>::grab_one_flag(dungeon.mon_resistance_flags, r_info_flagsr, what)) {
return true;
}
if (EnumClassFlagGroup<MonsterBehaviorType>::grab_one_flag(dungeon.mon_behavior_flags, r_info_behavior_flags, what)) {
return true;
}
if (EnumClassFlagGroup<MonsterVisualType>::grab_one_flag(dungeon.mon_visual_flags, r_info_visual_flags, what)) {
return true;
}
if (EnumClassFlagGroup<MonsterKindType>::grab_one_flag(dungeon.mon_kind_flags, r_info_kind_flags, what)) {
return true;
}
if (EnumClassFlagGroup<MonsterDropType>::grab_one_flag(dungeon.mon_drop_flags, r_info_drop_flags, what)) {
return true;
}
if (EnumClassFlagGroup<MonsterWildernessType>::grab_one_flag(dungeon.mon_wilderness_flags, r_info_wilderness_flags, what)) {
return true;
}
if (EnumClassFlagGroup<MonsterFeatureType>::grab_one_flag(dungeon.mon_feature_flags, r_info_feature_flags, what)) {
return true;
}
if (EnumClassFlagGroup<MonsterPopulationType>::grab_one_flag(dungeon.mon_population_flags, r_info_population_flags, what)) {
return true;
}
if (EnumClassFlagGroup<MonsterSpeakType>::grab_one_flag(dungeon.mon_speak_flags, r_info_speak_flags, what)) {
return true;
}
if (EnumClassFlagGroup<MonsterBrightnessType>::grab_one_flag(dungeon.mon_brightness_flags, r_info_brightness_flags, what)) {
return true;
}
if (EnumClassFlagGroup<MonsterSpecialType>::grab_one_flag(dungeon.mon_special_flags, r_info_special_flags, what)) {
return true;
}
if (EnumClassFlagGroup<MonsterMiscType>::grab_one_flag(dungeon.mon_misc_flags, r_info_misc_flags, what)) {
return true;
}
msg_format(_("未知のモンスター・フラグ '%s'。", "Unknown monster flag '%s'."), what.data());
return false;
}
/*!
* @brief テキストトークンを走査してフラグを一つ得る(モンスターのダンジョン出現条件用2)
* @param dungeon ダンジョンへの参照
* @param what 参照元の文字列
* @return 見つけたらtrue
*/
static bool grab_one_spell_monster_flag(DungeonDefinition &dungeon, std::string_view what)
{
if (EnumClassFlagGroup<MonsterAbilityType>::grab_one_flag(dungeon.mon_ability_flags, r_info_ability_flags, what)) {
return true;
}
msg_format(_("未知のモンスター・フラグ '%s'。", "Unknown monster flag '%s'."), what.data());
return false;
}
static tl::optional<ProbabilityTable<short>> parse_terrain_probability(std::span<const std::string> tokens)
{
const auto &terrains = TerrainList::get_instance();
ProbabilityTable<short> prob_table;
for (auto i = 0; std::cmp_less(i + 1, tokens.size()); i += 2) {
try {
const auto terrain_id = terrains.get_terrain_id(tokens[i]);
const auto prob = static_cast<short>(std::stoi(tokens[i + 1]));
prob_table.entry_item(terrain_id, prob);
} catch (const std::exception &) {
return tl::nullopt;
}
}
return prob_table;
}
/*!
* @brief ダンジョン情報(DungeonsDefinition)のパース関数 /
* @param buf テキスト列
* @param head ヘッダ構造体
* @return エラーコード
*/
errr parse_dungeons_info(std::string_view buf, angband_header *)
{
const auto &tokens = str_split(buf, ':', false);
const auto &terrains = TerrainList::get_instance();
// N:index:name_ja
auto &dungeons = DungeonList::get_instance();
if (tokens[0] == "N") {
if (tokens.size() < 3 || tokens[1].size() == 0) {
return PARSE_ERROR_TOO_FEW_ARGUMENTS;
}
const auto i = std::stoi(tokens[1]);
if (i < error_idx) {
return PARSE_ERROR_NON_SEQUENTIAL_RECORDS;
}
error_idx = i;
DungeonDefinition dungeon;
#ifdef JP
dungeon.name = tokens[2];
#endif
dungeons.emplace(i2enum<DungeonId>(i), std::move(dungeon));
return PARSE_ERROR_NONE;
}
if (dungeons.empty()) {
return PARSE_ERROR_MISSING_RECORD_HEADER;
}
// E:name_en
auto &[dungeon_id, dungeon] = *dungeons.rbegin();
if (tokens[0] == "E") {
#ifndef JP
if (tokens.size() < 2 || tokens[1].size() == 0) {
return PARSE_ERROR_TOO_FEW_ARGUMENTS;
}
dungeon->name = tokens[1];
#endif
return PARSE_ERROR_NONE;
}
// D:text_ja
// D:$text_en
if (tokens[0] == "D") {
if (tokens.size() < 2 || buf.length() < 3) {
return PARSE_ERROR_TOO_FEW_ARGUMENTS;
}
#ifdef JP
if (buf[2] == '$') {
return PARSE_ERROR_NONE;
}
dungeon->text.append(buf.substr(2));
#else
if (buf[2] != '$') {
return PARSE_ERROR_NONE;
}
if (buf.length() == 3) {
return PARSE_ERROR_TOO_FEW_ARGUMENTS;
}
append_english_text(dungeon->text, buf.substr(3));
#endif
return PARSE_ERROR_NONE;
}
// W:min_level:max_level:(1):mode:(2):(3):(4):(5):prob_pit:prob_nest
// (1)minimum player level (unused)
// (2)minimum level of allocating monster
// (3)maximum probability of level boost of allocation monster
// (4)maximum probability of dropping good objects
// (5)maximum probability of dropping great objects
if (tokens[0] == "W") {
if (tokens.size() < 11) {
return PARSE_ERROR_TOO_FEW_ARGUMENTS;
}
info_set_value(dungeon->mindepth, tokens[1]);
info_set_value(dungeon->maxdepth, tokens[2]);
info_set_value(dungeon->min_plev, tokens[3]);
info_set_value(dungeon->mode, tokens[4]);
info_set_value(dungeon->min_m_alloc_level, tokens[5]);
info_set_value(dungeon->max_m_alloc_chance, tokens[6]);
info_set_value(dungeon->obj_good, tokens[7]);
info_set_value(dungeon->obj_great, tokens[8]);
info_set_value(dungeon->pit, tokens[9], 16);
info_set_value(dungeon->nest, tokens[10], 16);
return PARSE_ERROR_NONE;
}
// P:wild_y:wild_x
if (tokens[0] == "P") {
if (tokens.size() < 3) {
return PARSE_ERROR_TOO_FEW_ARGUMENTS;
}
const auto wild_y = std::stoi(tokens[1]);
const auto wild_x = std::stoi(tokens[2]);
dungeon->initialize_position({ wild_y, wild_x });
return PARSE_ERROR_NONE;
}
// L:floor_1:prob_1:floor_2:prob_2:floor_3:prob_3:tunnel_prob
constexpr auto terrain_probability_num = 3;
if (tokens[0] == "L") {
if (tokens.size() < terrain_probability_num * 2 + 2) {
return PARSE_ERROR_TOO_FEW_ARGUMENTS;
}
auto prob_table = parse_terrain_probability(std::span(tokens).subspan(1, terrain_probability_num * 2));
if (!prob_table) {
return PARSE_ERROR_UNDEFINED_TERRAIN_TAG;
}
dungeon->prob_table_floor = std::move(*prob_table);
auto tunnel_idx = terrain_probability_num * 2 + 1;
info_set_value(dungeon->tunnel_percent, tokens[tunnel_idx]);
return PARSE_ERROR_NONE;
}
// A:wall_1:prob_1:wall_2:prob_2:wall_3:prob_3:outer_wall:inner_wall:stream_1:stream_2
if (tokens[0] == "A") {
if (tokens.size() < terrain_probability_num * 2 + 5) {
return PARSE_ERROR_TOO_FEW_ARGUMENTS;
}
auto prob_table = parse_terrain_probability(std::span(tokens).subspan(1, terrain_probability_num * 2));
if (!prob_table) {
return PARSE_ERROR_UNDEFINED_TERRAIN_TAG;
}
dungeon->prob_table_wall = std::move(*prob_table);
try {
const auto tags = std::span(tokens).subspan(terrain_probability_num * 2 + 1, 4);
dungeon->outer_wall = terrains.get_terrain_id(tags[0]);
dungeon->inner_wall = terrains.get_terrain_id(tags[1]);
dungeon->stream1 = terrains.get_terrain_id(tags[2]);
dungeon->stream2 = terrains.get_terrain_id(tags[3]);
return PARSE_ERROR_NONE;
} catch (const std::exception &) {
return PARSE_ERROR_UNDEFINED_TERRAIN_TAG;
}
}
// F:flags
if (tokens[0] == "F") {
if (tokens.size() < 2) {
return PARSE_ERROR_TOO_FEW_ARGUMENTS;
}
const auto &flags = str_split(tokens[1], '|', true);
for (const auto &f : flags) {
if (f.size() == 0) {
continue;
}
const auto &f_tokens = str_split(f, '_');
if (f_tokens.size() == 3) {
if (f_tokens[0] == "FINAL" && f_tokens[1] == "ARTIFACT") {
info_set_value(dungeon->final_artifact, f_tokens[2]);
continue;
}
if (f_tokens[0] == "FINAL" && f_tokens[1] == "OBJECT") {
info_set_value(dungeon->final_object, f_tokens[2]);
continue;
}
if (f_tokens[0] == "FINAL" && f_tokens[1] == "GUARDIAN") {
info_set_value(dungeon->final_guardian, f_tokens[2]);
continue;
}
if (f_tokens[0] == "MONSTER" && f_tokens[1] == "DIV") {
info_set_value(dungeon->special_div, f_tokens[2]);
continue;
}
}
if (!grab_one_dungeon_flag(*dungeon, f)) {
return PARSE_ERROR_INVALID_FLAG;
}
}
return PARSE_ERROR_NONE;
}
// M:Monster flags
if (tokens[0] == "M") {
if (tokens[1] == "X") {
if (tokens.size() < 3) {
return PARSE_ERROR_TOO_FEW_ARGUMENTS;
}
uint32_t sex;
if (!info_grab_one_const(sex, r_info_sex, tokens[2])) {
return PARSE_ERROR_INVALID_FLAG;
}
dungeon->mon_sex = static_cast<MonsterSex>(sex);
return 0;
}
if (tokens.size() < 2) {
return PARSE_ERROR_TOO_FEW_ARGUMENTS;
}
const auto &flags = str_split(tokens[1], '|', true);
for (const auto &f : flags) {
if (f.empty()) {
continue;
}
const auto &m_tokens = str_split(f, '_');
if (m_tokens[0] == "R" && m_tokens[1] == "CHAR") {
dungeon->r_chars.insert(dungeon->r_chars.end(), m_tokens[2].begin(), m_tokens[2].end());
continue;
}
if (!grab_one_basic_monster_flag(*dungeon, f)) {
return PARSE_ERROR_INVALID_FLAG;
}
}
return PARSE_ERROR_NONE;
}
// S: flags
if (tokens[0] == "S") {
if (tokens.size() < 2) {
return PARSE_ERROR_TOO_FEW_ARGUMENTS;
}
const auto &flags = str_split(tokens[1], '|', true);
for (const auto &f : flags) {
if (f.empty()) {
continue;
}
const auto &s_tokens = str_split(f, '_');
if (s_tokens.size() == 3 && s_tokens[1] == "IN") {
if (s_tokens[0] != "1") {
return PARSE_ERROR_GENERIC;
}
continue; //!< @details MonsterRaceDefinitions.jsonc からのコピペ対策
}
if (!grab_one_spell_monster_flag(*dungeon, f)) {
return PARSE_ERROR_INVALID_FLAG;
}
}
return PARSE_ERROR_NONE;
}
return PARSE_ERROR_UNDEFINED_DIRECTIVE;
}
| 412 | 0.989522 | 1 | 0.989522 | game-dev | MEDIA | 0.946042 | game-dev | 0.992638 | 1 | 0.992638 |
CloudburstMC/Nukkit | 1,697 | src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorBasaltDeltaLava.java | package cn.nukkit.level.generator.populator.impl;
import cn.nukkit.block.Block;
import cn.nukkit.block.BlockID;
import cn.nukkit.level.ChunkManager;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.level.generator.populator.type.Populator;
import cn.nukkit.math.NukkitRandom;
import it.unimi.dsi.fastutil.ints.IntArrayList;
public class PopulatorBasaltDeltaLava extends Populator {
private static IntArrayList getHighestWorkableBlocks(ChunkManager level, int x, int z) {
int y;
IntArrayList blockYs = new IntArrayList();
for (y = 128; y > 0; --y) {
int b = level.getBlockIdAt(x, y, z);
if ((b == Block.BASALT || b == Block.BLACKSTONE) &&
level.getBlockIdAt(x, y + 1, z) == 0 &&
level.getBlockIdAt(x + 1, y, z) != 0 &&
level.getBlockIdAt(x - 1, y, z) != 0 &&
level.getBlockIdAt(x, y, z + 1) != 0 &&
level.getBlockIdAt(x, y, z - 1) != 0
) {
blockYs.add(y);
}
}
return blockYs;
}
@Override
public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk) {
int amount = random.nextBoundedInt(64) + 64;
for (int i = 0; i < amount; ++i) {
int x = random.nextRange(chunkX << 4, (chunkX << 4) + 15);
int z = random.nextRange(chunkZ << 4, (chunkZ << 4) + 15);
IntArrayList ys = getHighestWorkableBlocks(level, x, z);
for (int y : ys) {
if (y <= 1) continue;
level.setBlockAt(x, y, z, BlockID.STILL_LAVA);
}
}
}
}
| 412 | 0.73957 | 1 | 0.73957 | game-dev | MEDIA | 0.894759 | game-dev | 0.863333 | 1 | 0.863333 |
chinedufn/dipa | 3,582 | crates/dipa-derive/src/parsed_enum/generate_dipa_impl/single_variant_enum/generate_one_batch_apply_patch_tokens.rs | use crate::dipa_attribute::DipaAttrs;
use crate::multi_field_utils::ChangedFieldIndices;
use crate::parsed_enum::{delta_owned_type_name, ParsedEnum};
use syn::__private::TokenStream2;
impl ParsedEnum {
/// Generate apply_patch tokens for an enum that has a single variant with multiple
/// fields that is using the `field_batching_strategy = "one_batch"`.
pub(super) fn generate_single_variant_multi_field_one_batch_apply_patch_tokens(
&self,
dipa_attrs: &DipaAttrs,
) -> TokenStream2 {
let enum_name = &self.name;
let delta_owned_name = delta_owned_type_name(enum_name);
let variant = &self.variants[0];
let variant_name = &variant.name;
let fields = &variant.fields;
let field_patterns = variant.fields.to_pattern_match_tokens("field_");
let mut patch_blocks = vec![];
for changed_indices in
ChangedFieldIndices::all_changed_index_combinations(fields.len(), dipa_attrs)
{
let change_name = changed_indices.variant_name_ident("", variant_name.span());
let patches = changed_indices.patch_field_idents(variant_name.span());
let mut field_applies = vec![];
for (idx, field_idx) in changed_indices.iter().enumerate() {
let field_idx = *field_idx as usize;
let field = &fields[field_idx];
let field_name = &field.name;
let field_name = format_ident!("field_{}", field_name.to_string());
let patch = &patches[idx];
field_applies.push(quote! {
#field_name.apply_patch(#patch);
})
}
patch_blocks.push(quote! {
#delta_owned_name::#change_name(#(#patches),*) => {
#(#field_applies)*
}
});
}
quote! {
match self {
#enum_name::#variant_name#field_patterns => {
match patch {
#delta_owned_name::NoChange => {}
#(#patch_blocks)*
}
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::assert_tokens_eq;
/// Verify that we properly generate the tokens for determining the delta between two single
/// variant multi field `field_batching_strategy = "one_batch"` enums.
#[test]
fn generates_tokens() {
let parsed_enum = ParsedEnum::new_test_one_variant_two_unnamed_fields();
let tokens =
parsed_enum.generate_single_variant_multi_field_one_batch_apply_patch_tokens(
&DipaAttrs::default(),
);
let expected = quote! {
match self {
MyEnum::MyVariant(field_0, field_1) => {
match patch {
MyEnumDeltaOwned::NoChange => {}
MyEnumDeltaOwned::Change_0(patch0) => {
field_0.apply_patch(patch0);
}
MyEnumDeltaOwned::Change_1(patch1) => {
field_1.apply_patch(patch1);
}
MyEnumDeltaOwned::Change_0_1(patch0, patch1) => {
field_0.apply_patch(patch0);
field_1.apply_patch(patch1);
}
}
}
}
};
assert_tokens_eq(&tokens, &expected);
}
}
| 412 | 0.781021 | 1 | 0.781021 | game-dev | MEDIA | 0.129096 | game-dev | 0.816839 | 1 | 0.816839 |
rollraw/qo0-csgo | 4,518 | base/sdk/datatypes/usercmd.h | #pragma once
#include "vector.h"
#include "qangle.h"
#include "../hash/crc32.h"
// @source: master/game/shared/usercmd.h
#pragma region usercmd_enumerations
// @source: master/game/shared/in_buttons.h
enum ECommandButtons : int
{
IN_ATTACK = (1 << 0),
IN_JUMP = (1 << 1),
IN_DUCK = (1 << 2),
IN_FORWARD = (1 << 3),
IN_BACK = (1 << 4),
IN_USE = (1 << 5),
IN_CANCEL = (1 << 6),
IN_LEFT = (1 << 7),
IN_RIGHT = (1 << 8),
IN_MOVELEFT = (1 << 9),
IN_MOVERIGHT = (1 << 10),
IN_SECOND_ATTACK = (1 << 11),
IN_RUN = (1 << 12),
IN_RELOAD = (1 << 13),
IN_LEFT_ALT = (1 << 14),
IN_RIGHT_ALT = (1 << 15),
IN_SCORE = (1 << 16),
IN_SPEED = (1 << 17),
IN_WALK = (1 << 18),
IN_ZOOM = (1 << 19),
IN_FIRST_WEAPON = (1 << 20),
IN_SECOND_WEAPON = (1 << 21),
IN_BULLRUSH = (1 << 22),
IN_FIRST_GRENADE = (1 << 23),
IN_SECOND_GRENADE = (1 << 24),
IN_MIDDLE_ATTACK = (1 << 25),
IN_USE_OR_RELOAD = (1 << 26)
};
#pragma endregion
#pragma pack(push, 4)
class CUserCmd
{
public:
Q_CLASS_NO_ALLOC();
CUserCmd& operator=(const CUserCmd& other)
{
iCommandNumber = other.iCommandNumber;
nTickCount = other.nTickCount;
angViewPoint = other.angViewPoint;
vecAimDirection = other.vecAimDirection;
flForwardMove = other.flForwardMove;
flSideMove = other.flSideMove;
flUpMove = other.flUpMove;
nButtons = other.nButtons;
uImpulse = other.uImpulse;
iWeaponSelect = other.iWeaponSelect;
iWeaponSubType = other.iWeaponSubType;
iRandomSeed = other.iRandomSeed;
shMouseDeltaX = other.shMouseDeltaX;
shMouseDeltaY = other.shMouseDeltaY;
bHasBeenPredicted = other.bHasBeenPredicted;
angViewPointBackup = other.angViewPointBackup;
nButtonsBackup = other.nButtonsBackup;
iUnknown0 = other.iUnknown0;
iUnknown1 = other.iUnknown1;
return *this;
}
[[nodiscard]] CRC32_t GetChecksum() const
{
// @ida CUserCmd::GetChecksum(): client.dll -> "53 8B D9 83 C8"
CRC32_t uHashCRC = 0U;
CRC32::Init(&uHashCRC);
CRC32::ProcessBuffer(&uHashCRC, &iCommandNumber, sizeof(iCommandNumber));
CRC32::ProcessBuffer(&uHashCRC, &nTickCount, sizeof(nTickCount));
CRC32::ProcessBuffer(&uHashCRC, &angViewPoint, sizeof(angViewPoint));
CRC32::ProcessBuffer(&uHashCRC, &vecAimDirection, sizeof(vecAimDirection));
CRC32::ProcessBuffer(&uHashCRC, &flForwardMove, sizeof(flForwardMove));
CRC32::ProcessBuffer(&uHashCRC, &flSideMove, sizeof(flSideMove));
CRC32::ProcessBuffer(&uHashCRC, &flUpMove, sizeof(flUpMove));
CRC32::ProcessBuffer(&uHashCRC, &nButtons, sizeof(nButtons));
CRC32::ProcessBuffer(&uHashCRC, &uImpulse, sizeof(uImpulse));
CRC32::ProcessBuffer(&uHashCRC, &iWeaponSelect, sizeof(iWeaponSelect));
CRC32::ProcessBuffer(&uHashCRC, &iWeaponSubType, sizeof(iWeaponSubType));
CRC32::ProcessBuffer(&uHashCRC, &iRandomSeed, sizeof(iRandomSeed));
CRC32::ProcessBuffer(&uHashCRC, &shMouseDeltaX, sizeof(shMouseDeltaX));
CRC32::ProcessBuffer(&uHashCRC, &shMouseDeltaY, sizeof(shMouseDeltaY));
CRC32::Final(&uHashCRC);
return uHashCRC;
}
private:
void* pVTable; // 0x00
public:
int iCommandNumber; // 0x04
int nTickCount; // 0x08
QAngle_t angViewPoint; // 0x0C
Vector_t vecAimDirection; // 0x18
float flForwardMove; // 0x24
float flSideMove; // 0x28
float flUpMove; // 0x2C
int nButtons; // 0x30
std::uint8_t uImpulse; // 0x34
int iWeaponSelect; // 0x38
int iWeaponSubType; // 0x3C
int iRandomSeed; // 0x40
short shMouseDeltaX; // 0x44
short shMouseDeltaY; // 0x46
bool bHasBeenPredicted; // 0x48
QAngle_t angViewPointBackup; // 0x4C // @note: instead of 'QAngle angHeadView' there's backup value of view angles that used to detect their change, changed since ~11.06.22 (version 1.38.3.7, build 1490)
int nButtonsBackup; // 0x58 // @note: instead of 'Vector vecHeadOffset' there's single backup value of buttons that used to detect their change, 0x5C/0x60 used for something else but still there, changed since ~11.06.22 (version 1.38.3.7, build 1490) // @ida: (WriteUsercmd) client.dll -> U8["FF 76 ? E8 ? ? ? ? 83 C4 1C" + 0x2] @xref: "headoffset"
private:
int iUnknown0; // 0x5C
int iUnknown1; // 0x60
};
static_assert(sizeof(CUserCmd) == 0x64); // size verify @ida: (CInput::Init_All) client.dll -> U8["83 C1 ? 83 EA 01 75 ED EB 02 33 FF A1" + 0x2]
class CVerifiedUserCmd
{
public:
CUserCmd userCmd; // 0x00
CRC32_t uHashCRC; // 0x64
};
static_assert(sizeof(CVerifiedUserCmd) == 0x68); // size verify @ida: (CInput::Init_All) client.dll -> U8["83 C1 ? 83 EA 01 75 ED EB 02 33 FF 89 BE" + 0x2]
#pragma pack(pop)
| 412 | 0.884799 | 1 | 0.884799 | game-dev | MEDIA | 0.49506 | game-dev | 0.774614 | 1 | 0.774614 |
goatcorp/Dalamud | 145,785 | imgui/Dalamud.Bindings.ImGui/Generated/Functions/Functions.040.cs | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using HexaGen.Runtime;
using System.Numerics;
namespace Dalamud.Bindings.ImGui
{
public unsafe partial class ImGui
{
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, int vMin, int vMax, ref byte format, byte* formatMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, (float)(1.0f), vMin, vMax, (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, float vSpeed, int vMin, int vMax, ref byte format, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, vSpeed, vMin, vMax, (byte*)pformat, (byte*)(default), flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, float vSpeed, int vMin, ref byte format, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, vSpeed, vMin, (int)(0), (byte*)pformat, (byte*)(default), flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, float vSpeed, ref byte format, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, vSpeed, (int)(0), (int)(0), (byte*)pformat, (byte*)(default), flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, ref byte format, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, (float)(1.0f), (int)(0), (int)(0), (byte*)pformat, (byte*)(default), flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, int vMin, ref byte format, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, (float)(1.0f), vMin, (int)(0), (byte*)pformat, (byte*)(default), flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, int vMin, int vMax, ref byte format, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, (float)(1.0f), vMin, vMax, (byte*)pformat, (byte*)(default), flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, float vSpeed, int vMin, ref byte format, byte* formatMax, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, vSpeed, vMin, (int)(0), (byte*)pformat, formatMax, flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, float vSpeed, ref byte format, byte* formatMax, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, vSpeed, (int)(0), (int)(0), (byte*)pformat, formatMax, flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, ref byte format, byte* formatMax, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, (float)(1.0f), (int)(0), (int)(0), (byte*)pformat, formatMax, flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, int vMin, ref byte format, byte* formatMax, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, (float)(1.0f), vMin, (int)(0), (byte*)pformat, formatMax, flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, int vMin, int vMax, ref byte format, byte* formatMax, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, (float)(1.0f), vMin, vMax, (byte*)pformat, formatMax, flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, float vSpeed, int vMin, int vMax, ReadOnlySpan<byte> format, byte* formatMax, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, vSpeed, vMin, vMax, (byte*)pformat, formatMax, flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, float vSpeed, int vMin, int vMax, ReadOnlySpan<byte> format, byte* formatMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, vSpeed, vMin, vMax, (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, float vSpeed, int vMin, int vMax, ReadOnlySpan<byte> format)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, vSpeed, vMin, vMax, (byte*)pformat, (byte*)(default), (ImGuiSliderFlags)(0));
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, float vSpeed, int vMin, ReadOnlySpan<byte> format)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, vSpeed, vMin, (int)(0), (byte*)pformat, (byte*)(default), (ImGuiSliderFlags)(0));
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, float vSpeed, ReadOnlySpan<byte> format)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, vSpeed, (int)(0), (int)(0), (byte*)pformat, (byte*)(default), (ImGuiSliderFlags)(0));
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, ReadOnlySpan<byte> format)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, (float)(1.0f), (int)(0), (int)(0), (byte*)pformat, (byte*)(default), (ImGuiSliderFlags)(0));
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, int vMin, ReadOnlySpan<byte> format)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, (float)(1.0f), vMin, (int)(0), (byte*)pformat, (byte*)(default), (ImGuiSliderFlags)(0));
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, int vMin, int vMax, ReadOnlySpan<byte> format)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, (float)(1.0f), vMin, vMax, (byte*)pformat, (byte*)(default), (ImGuiSliderFlags)(0));
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, float vSpeed, int vMin, ReadOnlySpan<byte> format, byte* formatMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, vSpeed, vMin, (int)(0), (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, float vSpeed, ReadOnlySpan<byte> format, byte* formatMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, vSpeed, (int)(0), (int)(0), (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, ReadOnlySpan<byte> format, byte* formatMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, (float)(1.0f), (int)(0), (int)(0), (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, int vMin, ReadOnlySpan<byte> format, byte* formatMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, (float)(1.0f), vMin, (int)(0), (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, int vMin, int vMax, ReadOnlySpan<byte> format, byte* formatMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, (float)(1.0f), vMin, vMax, (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, float vSpeed, int vMin, int vMax, ReadOnlySpan<byte> format, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, vSpeed, vMin, vMax, (byte*)pformat, (byte*)(default), flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, float vSpeed, int vMin, ReadOnlySpan<byte> format, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, vSpeed, vMin, (int)(0), (byte*)pformat, (byte*)(default), flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, float vSpeed, ReadOnlySpan<byte> format, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, vSpeed, (int)(0), (int)(0), (byte*)pformat, (byte*)(default), flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, ReadOnlySpan<byte> format, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, (float)(1.0f), (int)(0), (int)(0), (byte*)pformat, (byte*)(default), flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, int vMin, ReadOnlySpan<byte> format, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, (float)(1.0f), vMin, (int)(0), (byte*)pformat, (byte*)(default), flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, int vMin, int vMax, ReadOnlySpan<byte> format, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, (float)(1.0f), vMin, vMax, (byte*)pformat, (byte*)(default), flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, float vSpeed, int vMin, ReadOnlySpan<byte> format, byte* formatMax, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, vSpeed, vMin, (int)(0), (byte*)pformat, formatMax, flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, float vSpeed, ReadOnlySpan<byte> format, byte* formatMax, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, vSpeed, (int)(0), (int)(0), (byte*)pformat, formatMax, flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, ReadOnlySpan<byte> format, byte* formatMax, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, (float)(1.0f), (int)(0), (int)(0), (byte*)pformat, formatMax, flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, int vMin, ReadOnlySpan<byte> format, byte* formatMax, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, (float)(1.0f), vMin, (int)(0), (byte*)pformat, formatMax, flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, ref int vCurrentMin, int* vCurrentMax, int vMin, int vMax, ReadOnlySpan<byte> format, byte* formatMax, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMin = &vCurrentMin)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(pStr0, (int*)pvCurrentMin, vCurrentMax, (float)(1.0f), vMin, vMax, (byte*)pformat, formatMax, flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, int vMax, ref byte format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, vMax, (byte*)pformat, formatMax, flags);
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, int vMax, ref byte format, byte* formatMax)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, vMax, (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, int vMax, ref byte format)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, vMax, (byte*)pformat, (byte*)(default), (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, ref byte format)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, (int)(0), (byte*)pformat, (byte*)(default), (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, ref byte format)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, (int)(0), (int)(0), (byte*)pformat, (byte*)(default), (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, ref byte format)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), (int)(0), (int)(0), (byte*)pformat, (byte*)(default), (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, int vMin, ref byte format)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, (int)(0), (byte*)pformat, (byte*)(default), (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, int vMin, int vMax, ref byte format)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, vMax, (byte*)pformat, (byte*)(default), (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, ref byte format, byte* formatMax)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, (int)(0), (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, ref byte format, byte* formatMax)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, (int)(0), (int)(0), (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, ref byte format, byte* formatMax)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), (int)(0), (int)(0), (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, int vMin, ref byte format, byte* formatMax)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, (int)(0), (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, int vMin, int vMax, ref byte format, byte* formatMax)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, vMax, (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, int vMax, ref byte format, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, vMax, (byte*)pformat, (byte*)(default), flags);
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, ref byte format, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, (int)(0), (byte*)pformat, (byte*)(default), flags);
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, ref byte format, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, (int)(0), (int)(0), (byte*)pformat, (byte*)(default), flags);
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, ref byte format, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), (int)(0), (int)(0), (byte*)pformat, (byte*)(default), flags);
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, int vMin, ref byte format, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, (int)(0), (byte*)pformat, (byte*)(default), flags);
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, int vMin, int vMax, ref byte format, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, vMax, (byte*)pformat, (byte*)(default), flags);
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, ref byte format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, (int)(0), (byte*)pformat, formatMax, flags);
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, ref byte format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, (int)(0), (int)(0), (byte*)pformat, formatMax, flags);
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, ref byte format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), (int)(0), (int)(0), (byte*)pformat, formatMax, flags);
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, int vMin, ref byte format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, (int)(0), (byte*)pformat, formatMax, flags);
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, int vMin, int vMax, ref byte format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, vMax, (byte*)pformat, formatMax, flags);
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, int vMax, ReadOnlySpan<byte> format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, vMax, (byte*)pformat, formatMax, flags);
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, int vMax, ReadOnlySpan<byte> format, byte* formatMax)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, vMax, (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, int vMax, ReadOnlySpan<byte> format)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, vMax, (byte*)pformat, (byte*)(default), (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, ReadOnlySpan<byte> format)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, (int)(0), (byte*)pformat, (byte*)(default), (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, ReadOnlySpan<byte> format)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, (int)(0), (int)(0), (byte*)pformat, (byte*)(default), (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, ReadOnlySpan<byte> format)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), (int)(0), (int)(0), (byte*)pformat, (byte*)(default), (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, int vMin, ReadOnlySpan<byte> format)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, (int)(0), (byte*)pformat, (byte*)(default), (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, int vMin, int vMax, ReadOnlySpan<byte> format)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, vMax, (byte*)pformat, (byte*)(default), (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, ReadOnlySpan<byte> format, byte* formatMax)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, (int)(0), (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, ReadOnlySpan<byte> format, byte* formatMax)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, (int)(0), (int)(0), (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, ReadOnlySpan<byte> format, byte* formatMax)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), (int)(0), (int)(0), (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, int vMin, ReadOnlySpan<byte> format, byte* formatMax)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, (int)(0), (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, int vMin, int vMax, ReadOnlySpan<byte> format, byte* formatMax)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, vMax, (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, int vMax, ReadOnlySpan<byte> format, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, vMax, (byte*)pformat, (byte*)(default), flags);
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, ReadOnlySpan<byte> format, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, (int)(0), (byte*)pformat, (byte*)(default), flags);
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, ReadOnlySpan<byte> format, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, (int)(0), (int)(0), (byte*)pformat, (byte*)(default), flags);
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, ReadOnlySpan<byte> format, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), (int)(0), (int)(0), (byte*)pformat, (byte*)(default), flags);
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, int vMin, ReadOnlySpan<byte> format, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, (int)(0), (byte*)pformat, (byte*)(default), flags);
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, int vMin, int vMax, ReadOnlySpan<byte> format, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, vMax, (byte*)pformat, (byte*)(default), flags);
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, ReadOnlySpan<byte> format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, (int)(0), (byte*)pformat, formatMax, flags);
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, ReadOnlySpan<byte> format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, (int)(0), (int)(0), (byte*)pformat, formatMax, flags);
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, ReadOnlySpan<byte> format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), (int)(0), (int)(0), (byte*)pformat, formatMax, flags);
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, int vMin, ReadOnlySpan<byte> format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, (int)(0), (byte*)pformat, formatMax, flags);
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, int vMin, int vMax, ReadOnlySpan<byte> format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, vMax, (byte*)pformat, formatMax, flags);
return ret != 0;
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, int vMax, string format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (format != null)
{
pStrSize0 = Utils.GetByteCountUTF8(format);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(format, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, vMax, pStr0, formatMax, flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, int vMax, string format, byte* formatMax)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (format != null)
{
pStrSize0 = Utils.GetByteCountUTF8(format);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(format, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, vMax, pStr0, formatMax, (ImGuiSliderFlags)(0));
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, int vMax, string format)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (format != null)
{
pStrSize0 = Utils.GetByteCountUTF8(format);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(format, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, vMax, pStr0, (byte*)(default), (ImGuiSliderFlags)(0));
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, string format)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (format != null)
{
pStrSize0 = Utils.GetByteCountUTF8(format);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(format, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, (int)(0), pStr0, (byte*)(default), (ImGuiSliderFlags)(0));
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, string format)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (format != null)
{
pStrSize0 = Utils.GetByteCountUTF8(format);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(format, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, (int)(0), (int)(0), pStr0, (byte*)(default), (ImGuiSliderFlags)(0));
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, string format)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (format != null)
{
pStrSize0 = Utils.GetByteCountUTF8(format);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(format, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), (int)(0), (int)(0), pStr0, (byte*)(default), (ImGuiSliderFlags)(0));
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, int vMin, string format)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (format != null)
{
pStrSize0 = Utils.GetByteCountUTF8(format);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(format, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, (int)(0), pStr0, (byte*)(default), (ImGuiSliderFlags)(0));
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, int vMin, int vMax, string format)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (format != null)
{
pStrSize0 = Utils.GetByteCountUTF8(format);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(format, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, vMax, pStr0, (byte*)(default), (ImGuiSliderFlags)(0));
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, string format, byte* formatMax)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (format != null)
{
pStrSize0 = Utils.GetByteCountUTF8(format);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(format, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, (int)(0), pStr0, formatMax, (ImGuiSliderFlags)(0));
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, string format, byte* formatMax)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (format != null)
{
pStrSize0 = Utils.GetByteCountUTF8(format);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(format, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, (int)(0), (int)(0), pStr0, formatMax, (ImGuiSliderFlags)(0));
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, string format, byte* formatMax)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (format != null)
{
pStrSize0 = Utils.GetByteCountUTF8(format);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(format, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), (int)(0), (int)(0), pStr0, formatMax, (ImGuiSliderFlags)(0));
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, int vMin, string format, byte* formatMax)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (format != null)
{
pStrSize0 = Utils.GetByteCountUTF8(format);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(format, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, (int)(0), pStr0, formatMax, (ImGuiSliderFlags)(0));
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, int vMin, int vMax, string format, byte* formatMax)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (format != null)
{
pStrSize0 = Utils.GetByteCountUTF8(format);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(format, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, vMax, pStr0, formatMax, (ImGuiSliderFlags)(0));
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, int vMax, string format, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (format != null)
{
pStrSize0 = Utils.GetByteCountUTF8(format);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(format, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, vMax, pStr0, (byte*)(default), flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, string format, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (format != null)
{
pStrSize0 = Utils.GetByteCountUTF8(format);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(format, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, (int)(0), pStr0, (byte*)(default), flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, string format, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (format != null)
{
pStrSize0 = Utils.GetByteCountUTF8(format);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(format, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, (int)(0), (int)(0), pStr0, (byte*)(default), flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, string format, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (format != null)
{
pStrSize0 = Utils.GetByteCountUTF8(format);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(format, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), (int)(0), (int)(0), pStr0, (byte*)(default), flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, int vMin, string format, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (format != null)
{
pStrSize0 = Utils.GetByteCountUTF8(format);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(format, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, (int)(0), pStr0, (byte*)(default), flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, int vMin, int vMax, string format, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (format != null)
{
pStrSize0 = Utils.GetByteCountUTF8(format);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(format, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, vMax, pStr0, (byte*)(default), flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, string format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (format != null)
{
pStrSize0 = Utils.GetByteCountUTF8(format);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(format, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, (int)(0), pStr0, formatMax, flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, string format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (format != null)
{
pStrSize0 = Utils.GetByteCountUTF8(format);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(format, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, vSpeed, (int)(0), (int)(0), pStr0, formatMax, flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, string format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (format != null)
{
pStrSize0 = Utils.GetByteCountUTF8(format);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(format, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), (int)(0), (int)(0), pStr0, formatMax, flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, int vMin, string format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (format != null)
{
pStrSize0 = Utils.GetByteCountUTF8(format);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(format, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, (int)(0), pStr0, formatMax, flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(byte* label, int* vCurrentMin, ref int vCurrentMax, int vMin, int vMax, string format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (format != null)
{
pStrSize0 = Utils.GetByteCountUTF8(format);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(format, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
byte ret = DragIntRange2Native(label, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, vMax, pStr0, formatMax, flags);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ref byte label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, int vMax, ref byte format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (byte* plabel = &label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, vMax, (byte*)pformat, formatMax, flags);
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ref byte label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, int vMax, ref byte format, byte* formatMax)
{
fixed (byte* plabel = &label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, vMax, (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ref byte label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, int vMax, ref byte format)
{
fixed (byte* plabel = &label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, vMax, (byte*)pformat, (byte*)(default), (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ref byte label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, ref byte format)
{
fixed (byte* plabel = &label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, (int)(0), (byte*)pformat, (byte*)(default), (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ref byte label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, ref byte format)
{
fixed (byte* plabel = &label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, vSpeed, (int)(0), (int)(0), (byte*)pformat, (byte*)(default), (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ref byte label, int* vCurrentMin, ref int vCurrentMax, ref byte format)
{
fixed (byte* plabel = &label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), (int)(0), (int)(0), (byte*)pformat, (byte*)(default), (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ref byte label, int* vCurrentMin, ref int vCurrentMax, int vMin, ref byte format)
{
fixed (byte* plabel = &label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, (int)(0), (byte*)pformat, (byte*)(default), (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ref byte label, int* vCurrentMin, ref int vCurrentMax, int vMin, int vMax, ref byte format)
{
fixed (byte* plabel = &label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, vMax, (byte*)pformat, (byte*)(default), (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ref byte label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, ref byte format, byte* formatMax)
{
fixed (byte* plabel = &label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, (int)(0), (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ref byte label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, ref byte format, byte* formatMax)
{
fixed (byte* plabel = &label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, vSpeed, (int)(0), (int)(0), (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ref byte label, int* vCurrentMin, ref int vCurrentMax, ref byte format, byte* formatMax)
{
fixed (byte* plabel = &label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), (int)(0), (int)(0), (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ref byte label, int* vCurrentMin, ref int vCurrentMax, int vMin, ref byte format, byte* formatMax)
{
fixed (byte* plabel = &label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, (int)(0), (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ref byte label, int* vCurrentMin, ref int vCurrentMax, int vMin, int vMax, ref byte format, byte* formatMax)
{
fixed (byte* plabel = &label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, vMax, (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ref byte label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, int vMax, ref byte format, ImGuiSliderFlags flags)
{
fixed (byte* plabel = &label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, vMax, (byte*)pformat, (byte*)(default), flags);
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ref byte label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, ref byte format, ImGuiSliderFlags flags)
{
fixed (byte* plabel = &label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, (int)(0), (byte*)pformat, (byte*)(default), flags);
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ref byte label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, ref byte format, ImGuiSliderFlags flags)
{
fixed (byte* plabel = &label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, vSpeed, (int)(0), (int)(0), (byte*)pformat, (byte*)(default), flags);
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ref byte label, int* vCurrentMin, ref int vCurrentMax, ref byte format, ImGuiSliderFlags flags)
{
fixed (byte* plabel = &label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), (int)(0), (int)(0), (byte*)pformat, (byte*)(default), flags);
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ref byte label, int* vCurrentMin, ref int vCurrentMax, int vMin, ref byte format, ImGuiSliderFlags flags)
{
fixed (byte* plabel = &label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, (int)(0), (byte*)pformat, (byte*)(default), flags);
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ref byte label, int* vCurrentMin, ref int vCurrentMax, int vMin, int vMax, ref byte format, ImGuiSliderFlags flags)
{
fixed (byte* plabel = &label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, vMax, (byte*)pformat, (byte*)(default), flags);
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ref byte label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, ref byte format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (byte* plabel = &label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, (int)(0), (byte*)pformat, formatMax, flags);
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ref byte label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, ref byte format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (byte* plabel = &label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, vSpeed, (int)(0), (int)(0), (byte*)pformat, formatMax, flags);
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ref byte label, int* vCurrentMin, ref int vCurrentMax, ref byte format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (byte* plabel = &label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), (int)(0), (int)(0), (byte*)pformat, formatMax, flags);
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ref byte label, int* vCurrentMin, ref int vCurrentMax, int vMin, ref byte format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (byte* plabel = &label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, (int)(0), (byte*)pformat, formatMax, flags);
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ref byte label, int* vCurrentMin, ref int vCurrentMax, int vMin, int vMax, ref byte format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (byte* plabel = &label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = &format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, vMax, (byte*)pformat, formatMax, flags);
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ReadOnlySpan<byte> label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, int vMax, ReadOnlySpan<byte> format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (byte* plabel = label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, vMax, (byte*)pformat, formatMax, flags);
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ReadOnlySpan<byte> label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, int vMax, ReadOnlySpan<byte> format, byte* formatMax)
{
fixed (byte* plabel = label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, vMax, (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ReadOnlySpan<byte> label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, int vMax, ReadOnlySpan<byte> format)
{
fixed (byte* plabel = label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, vMax, (byte*)pformat, (byte*)(default), (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ReadOnlySpan<byte> label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, ReadOnlySpan<byte> format)
{
fixed (byte* plabel = label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, (int)(0), (byte*)pformat, (byte*)(default), (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ReadOnlySpan<byte> label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, ReadOnlySpan<byte> format)
{
fixed (byte* plabel = label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, vSpeed, (int)(0), (int)(0), (byte*)pformat, (byte*)(default), (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ReadOnlySpan<byte> label, int* vCurrentMin, ref int vCurrentMax, ReadOnlySpan<byte> format)
{
fixed (byte* plabel = label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), (int)(0), (int)(0), (byte*)pformat, (byte*)(default), (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ReadOnlySpan<byte> label, int* vCurrentMin, ref int vCurrentMax, int vMin, ReadOnlySpan<byte> format)
{
fixed (byte* plabel = label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, (int)(0), (byte*)pformat, (byte*)(default), (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ReadOnlySpan<byte> label, int* vCurrentMin, ref int vCurrentMax, int vMin, int vMax, ReadOnlySpan<byte> format)
{
fixed (byte* plabel = label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, vMax, (byte*)pformat, (byte*)(default), (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ReadOnlySpan<byte> label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, ReadOnlySpan<byte> format, byte* formatMax)
{
fixed (byte* plabel = label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, (int)(0), (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ReadOnlySpan<byte> label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, ReadOnlySpan<byte> format, byte* formatMax)
{
fixed (byte* plabel = label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, vSpeed, (int)(0), (int)(0), (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ReadOnlySpan<byte> label, int* vCurrentMin, ref int vCurrentMax, ReadOnlySpan<byte> format, byte* formatMax)
{
fixed (byte* plabel = label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), (int)(0), (int)(0), (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ReadOnlySpan<byte> label, int* vCurrentMin, ref int vCurrentMax, int vMin, ReadOnlySpan<byte> format, byte* formatMax)
{
fixed (byte* plabel = label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, (int)(0), (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ReadOnlySpan<byte> label, int* vCurrentMin, ref int vCurrentMax, int vMin, int vMax, ReadOnlySpan<byte> format, byte* formatMax)
{
fixed (byte* plabel = label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, vMax, (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ReadOnlySpan<byte> label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, int vMax, ReadOnlySpan<byte> format, ImGuiSliderFlags flags)
{
fixed (byte* plabel = label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, vMax, (byte*)pformat, (byte*)(default), flags);
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ReadOnlySpan<byte> label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, ReadOnlySpan<byte> format, ImGuiSliderFlags flags)
{
fixed (byte* plabel = label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, (int)(0), (byte*)pformat, (byte*)(default), flags);
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ReadOnlySpan<byte> label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, ReadOnlySpan<byte> format, ImGuiSliderFlags flags)
{
fixed (byte* plabel = label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, vSpeed, (int)(0), (int)(0), (byte*)pformat, (byte*)(default), flags);
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ReadOnlySpan<byte> label, int* vCurrentMin, ref int vCurrentMax, ReadOnlySpan<byte> format, ImGuiSliderFlags flags)
{
fixed (byte* plabel = label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), (int)(0), (int)(0), (byte*)pformat, (byte*)(default), flags);
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ReadOnlySpan<byte> label, int* vCurrentMin, ref int vCurrentMax, int vMin, ReadOnlySpan<byte> format, ImGuiSliderFlags flags)
{
fixed (byte* plabel = label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, (int)(0), (byte*)pformat, (byte*)(default), flags);
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ReadOnlySpan<byte> label, int* vCurrentMin, ref int vCurrentMax, int vMin, int vMax, ReadOnlySpan<byte> format, ImGuiSliderFlags flags)
{
fixed (byte* plabel = label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, vMax, (byte*)pformat, (byte*)(default), flags);
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ReadOnlySpan<byte> label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, ReadOnlySpan<byte> format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (byte* plabel = label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, (int)(0), (byte*)pformat, formatMax, flags);
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ReadOnlySpan<byte> label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, ReadOnlySpan<byte> format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (byte* plabel = label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, vSpeed, (int)(0), (int)(0), (byte*)pformat, formatMax, flags);
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ReadOnlySpan<byte> label, int* vCurrentMin, ref int vCurrentMax, ReadOnlySpan<byte> format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (byte* plabel = label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), (int)(0), (int)(0), (byte*)pformat, formatMax, flags);
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ReadOnlySpan<byte> label, int* vCurrentMin, ref int vCurrentMax, int vMin, ReadOnlySpan<byte> format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (byte* plabel = label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, (int)(0), (byte*)pformat, formatMax, flags);
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ReadOnlySpan<byte> label, int* vCurrentMin, ref int vCurrentMax, int vMin, int vMax, ReadOnlySpan<byte> format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (byte* plabel = label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, vMax, (byte*)pformat, formatMax, flags);
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, int vMax, string format, byte* formatMax, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr1 = null;
int pStrSize1 = 0;
if (format != null)
{
pStrSize1 = Utils.GetByteCountUTF8(format);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
pStr1 = Utils.Alloc<byte>(pStrSize1 + 1);
}
else
{
byte* pStrStack1 = stackalloc byte[pStrSize1 + 1];
pStr1 = pStrStack1;
}
int pStrOffset1 = Utils.EncodeStringUTF8(format, pStr1, pStrSize1);
pStr1[pStrOffset1] = 0;
}
byte ret = DragIntRange2Native(pStr0, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, vMax, pStr1, formatMax, flags);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr1);
}
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, int vMax, string format, byte* formatMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr1 = null;
int pStrSize1 = 0;
if (format != null)
{
pStrSize1 = Utils.GetByteCountUTF8(format);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
pStr1 = Utils.Alloc<byte>(pStrSize1 + 1);
}
else
{
byte* pStrStack1 = stackalloc byte[pStrSize1 + 1];
pStr1 = pStrStack1;
}
int pStrOffset1 = Utils.EncodeStringUTF8(format, pStr1, pStrSize1);
pStr1[pStrOffset1] = 0;
}
byte ret = DragIntRange2Native(pStr0, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, vMax, pStr1, formatMax, (ImGuiSliderFlags)(0));
if (pStrSize1 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr1);
}
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, int vMax, string format)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr1 = null;
int pStrSize1 = 0;
if (format != null)
{
pStrSize1 = Utils.GetByteCountUTF8(format);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
pStr1 = Utils.Alloc<byte>(pStrSize1 + 1);
}
else
{
byte* pStrStack1 = stackalloc byte[pStrSize1 + 1];
pStr1 = pStrStack1;
}
int pStrOffset1 = Utils.EncodeStringUTF8(format, pStr1, pStrSize1);
pStr1[pStrOffset1] = 0;
}
byte ret = DragIntRange2Native(pStr0, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, vMax, pStr1, (byte*)(default), (ImGuiSliderFlags)(0));
if (pStrSize1 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr1);
}
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, string format)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr1 = null;
int pStrSize1 = 0;
if (format != null)
{
pStrSize1 = Utils.GetByteCountUTF8(format);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
pStr1 = Utils.Alloc<byte>(pStrSize1 + 1);
}
else
{
byte* pStrStack1 = stackalloc byte[pStrSize1 + 1];
pStr1 = pStrStack1;
}
int pStrOffset1 = Utils.EncodeStringUTF8(format, pStr1, pStrSize1);
pStr1[pStrOffset1] = 0;
}
byte ret = DragIntRange2Native(pStr0, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, (int)(0), pStr1, (byte*)(default), (ImGuiSliderFlags)(0));
if (pStrSize1 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr1);
}
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, string format)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr1 = null;
int pStrSize1 = 0;
if (format != null)
{
pStrSize1 = Utils.GetByteCountUTF8(format);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
pStr1 = Utils.Alloc<byte>(pStrSize1 + 1);
}
else
{
byte* pStrStack1 = stackalloc byte[pStrSize1 + 1];
pStr1 = pStrStack1;
}
int pStrOffset1 = Utils.EncodeStringUTF8(format, pStr1, pStrSize1);
pStr1[pStrOffset1] = 0;
}
byte ret = DragIntRange2Native(pStr0, vCurrentMin, (int*)pvCurrentMax, vSpeed, (int)(0), (int)(0), pStr1, (byte*)(default), (ImGuiSliderFlags)(0));
if (pStrSize1 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr1);
}
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, int* vCurrentMin, ref int vCurrentMax, string format)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr1 = null;
int pStrSize1 = 0;
if (format != null)
{
pStrSize1 = Utils.GetByteCountUTF8(format);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
pStr1 = Utils.Alloc<byte>(pStrSize1 + 1);
}
else
{
byte* pStrStack1 = stackalloc byte[pStrSize1 + 1];
pStr1 = pStrStack1;
}
int pStrOffset1 = Utils.EncodeStringUTF8(format, pStr1, pStrSize1);
pStr1[pStrOffset1] = 0;
}
byte ret = DragIntRange2Native(pStr0, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), (int)(0), (int)(0), pStr1, (byte*)(default), (ImGuiSliderFlags)(0));
if (pStrSize1 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr1);
}
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, int* vCurrentMin, ref int vCurrentMax, int vMin, string format)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr1 = null;
int pStrSize1 = 0;
if (format != null)
{
pStrSize1 = Utils.GetByteCountUTF8(format);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
pStr1 = Utils.Alloc<byte>(pStrSize1 + 1);
}
else
{
byte* pStrStack1 = stackalloc byte[pStrSize1 + 1];
pStr1 = pStrStack1;
}
int pStrOffset1 = Utils.EncodeStringUTF8(format, pStr1, pStrSize1);
pStr1[pStrOffset1] = 0;
}
byte ret = DragIntRange2Native(pStr0, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, (int)(0), pStr1, (byte*)(default), (ImGuiSliderFlags)(0));
if (pStrSize1 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr1);
}
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, int* vCurrentMin, ref int vCurrentMax, int vMin, int vMax, string format)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr1 = null;
int pStrSize1 = 0;
if (format != null)
{
pStrSize1 = Utils.GetByteCountUTF8(format);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
pStr1 = Utils.Alloc<byte>(pStrSize1 + 1);
}
else
{
byte* pStrStack1 = stackalloc byte[pStrSize1 + 1];
pStr1 = pStrStack1;
}
int pStrOffset1 = Utils.EncodeStringUTF8(format, pStr1, pStrSize1);
pStr1[pStrOffset1] = 0;
}
byte ret = DragIntRange2Native(pStr0, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, vMax, pStr1, (byte*)(default), (ImGuiSliderFlags)(0));
if (pStrSize1 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr1);
}
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, string format, byte* formatMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr1 = null;
int pStrSize1 = 0;
if (format != null)
{
pStrSize1 = Utils.GetByteCountUTF8(format);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
pStr1 = Utils.Alloc<byte>(pStrSize1 + 1);
}
else
{
byte* pStrStack1 = stackalloc byte[pStrSize1 + 1];
pStr1 = pStrStack1;
}
int pStrOffset1 = Utils.EncodeStringUTF8(format, pStr1, pStrSize1);
pStr1[pStrOffset1] = 0;
}
byte ret = DragIntRange2Native(pStr0, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, (int)(0), pStr1, formatMax, (ImGuiSliderFlags)(0));
if (pStrSize1 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr1);
}
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, string format, byte* formatMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr1 = null;
int pStrSize1 = 0;
if (format != null)
{
pStrSize1 = Utils.GetByteCountUTF8(format);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
pStr1 = Utils.Alloc<byte>(pStrSize1 + 1);
}
else
{
byte* pStrStack1 = stackalloc byte[pStrSize1 + 1];
pStr1 = pStrStack1;
}
int pStrOffset1 = Utils.EncodeStringUTF8(format, pStr1, pStrSize1);
pStr1[pStrOffset1] = 0;
}
byte ret = DragIntRange2Native(pStr0, vCurrentMin, (int*)pvCurrentMax, vSpeed, (int)(0), (int)(0), pStr1, formatMax, (ImGuiSliderFlags)(0));
if (pStrSize1 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr1);
}
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, int* vCurrentMin, ref int vCurrentMax, string format, byte* formatMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr1 = null;
int pStrSize1 = 0;
if (format != null)
{
pStrSize1 = Utils.GetByteCountUTF8(format);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
pStr1 = Utils.Alloc<byte>(pStrSize1 + 1);
}
else
{
byte* pStrStack1 = stackalloc byte[pStrSize1 + 1];
pStr1 = pStrStack1;
}
int pStrOffset1 = Utils.EncodeStringUTF8(format, pStr1, pStrSize1);
pStr1[pStrOffset1] = 0;
}
byte ret = DragIntRange2Native(pStr0, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), (int)(0), (int)(0), pStr1, formatMax, (ImGuiSliderFlags)(0));
if (pStrSize1 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr1);
}
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, int* vCurrentMin, ref int vCurrentMax, int vMin, string format, byte* formatMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr1 = null;
int pStrSize1 = 0;
if (format != null)
{
pStrSize1 = Utils.GetByteCountUTF8(format);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
pStr1 = Utils.Alloc<byte>(pStrSize1 + 1);
}
else
{
byte* pStrStack1 = stackalloc byte[pStrSize1 + 1];
pStr1 = pStrStack1;
}
int pStrOffset1 = Utils.EncodeStringUTF8(format, pStr1, pStrSize1);
pStr1[pStrOffset1] = 0;
}
byte ret = DragIntRange2Native(pStr0, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, (int)(0), pStr1, formatMax, (ImGuiSliderFlags)(0));
if (pStrSize1 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr1);
}
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, int* vCurrentMin, ref int vCurrentMax, int vMin, int vMax, string format, byte* formatMax)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr1 = null;
int pStrSize1 = 0;
if (format != null)
{
pStrSize1 = Utils.GetByteCountUTF8(format);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
pStr1 = Utils.Alloc<byte>(pStrSize1 + 1);
}
else
{
byte* pStrStack1 = stackalloc byte[pStrSize1 + 1];
pStr1 = pStrStack1;
}
int pStrOffset1 = Utils.EncodeStringUTF8(format, pStr1, pStrSize1);
pStr1[pStrOffset1] = 0;
}
byte ret = DragIntRange2Native(pStr0, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, vMax, pStr1, formatMax, (ImGuiSliderFlags)(0));
if (pStrSize1 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr1);
}
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, int vMax, string format, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr1 = null;
int pStrSize1 = 0;
if (format != null)
{
pStrSize1 = Utils.GetByteCountUTF8(format);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
pStr1 = Utils.Alloc<byte>(pStrSize1 + 1);
}
else
{
byte* pStrStack1 = stackalloc byte[pStrSize1 + 1];
pStr1 = pStrStack1;
}
int pStrOffset1 = Utils.EncodeStringUTF8(format, pStr1, pStrSize1);
pStr1[pStrOffset1] = 0;
}
byte ret = DragIntRange2Native(pStr0, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, vMax, pStr1, (byte*)(default), flags);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr1);
}
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, string format, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr1 = null;
int pStrSize1 = 0;
if (format != null)
{
pStrSize1 = Utils.GetByteCountUTF8(format);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
pStr1 = Utils.Alloc<byte>(pStrSize1 + 1);
}
else
{
byte* pStrStack1 = stackalloc byte[pStrSize1 + 1];
pStr1 = pStrStack1;
}
int pStrOffset1 = Utils.EncodeStringUTF8(format, pStr1, pStrSize1);
pStr1[pStrOffset1] = 0;
}
byte ret = DragIntRange2Native(pStr0, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, (int)(0), pStr1, (byte*)(default), flags);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr1);
}
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, string format, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr1 = null;
int pStrSize1 = 0;
if (format != null)
{
pStrSize1 = Utils.GetByteCountUTF8(format);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
pStr1 = Utils.Alloc<byte>(pStrSize1 + 1);
}
else
{
byte* pStrStack1 = stackalloc byte[pStrSize1 + 1];
pStr1 = pStrStack1;
}
int pStrOffset1 = Utils.EncodeStringUTF8(format, pStr1, pStrSize1);
pStr1[pStrOffset1] = 0;
}
byte ret = DragIntRange2Native(pStr0, vCurrentMin, (int*)pvCurrentMax, vSpeed, (int)(0), (int)(0), pStr1, (byte*)(default), flags);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr1);
}
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, int* vCurrentMin, ref int vCurrentMax, string format, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr1 = null;
int pStrSize1 = 0;
if (format != null)
{
pStrSize1 = Utils.GetByteCountUTF8(format);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
pStr1 = Utils.Alloc<byte>(pStrSize1 + 1);
}
else
{
byte* pStrStack1 = stackalloc byte[pStrSize1 + 1];
pStr1 = pStrStack1;
}
int pStrOffset1 = Utils.EncodeStringUTF8(format, pStr1, pStrSize1);
pStr1[pStrOffset1] = 0;
}
byte ret = DragIntRange2Native(pStr0, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), (int)(0), (int)(0), pStr1, (byte*)(default), flags);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr1);
}
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, int* vCurrentMin, ref int vCurrentMax, int vMin, string format, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr1 = null;
int pStrSize1 = 0;
if (format != null)
{
pStrSize1 = Utils.GetByteCountUTF8(format);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
pStr1 = Utils.Alloc<byte>(pStrSize1 + 1);
}
else
{
byte* pStrStack1 = stackalloc byte[pStrSize1 + 1];
pStr1 = pStrStack1;
}
int pStrOffset1 = Utils.EncodeStringUTF8(format, pStr1, pStrSize1);
pStr1[pStrOffset1] = 0;
}
byte ret = DragIntRange2Native(pStr0, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, (int)(0), pStr1, (byte*)(default), flags);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr1);
}
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, int* vCurrentMin, ref int vCurrentMax, int vMin, int vMax, string format, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr1 = null;
int pStrSize1 = 0;
if (format != null)
{
pStrSize1 = Utils.GetByteCountUTF8(format);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
pStr1 = Utils.Alloc<byte>(pStrSize1 + 1);
}
else
{
byte* pStrStack1 = stackalloc byte[pStrSize1 + 1];
pStr1 = pStrStack1;
}
int pStrOffset1 = Utils.EncodeStringUTF8(format, pStr1, pStrSize1);
pStr1[pStrOffset1] = 0;
}
byte ret = DragIntRange2Native(pStr0, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, vMax, pStr1, (byte*)(default), flags);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr1);
}
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, string format, byte* formatMax, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr1 = null;
int pStrSize1 = 0;
if (format != null)
{
pStrSize1 = Utils.GetByteCountUTF8(format);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
pStr1 = Utils.Alloc<byte>(pStrSize1 + 1);
}
else
{
byte* pStrStack1 = stackalloc byte[pStrSize1 + 1];
pStr1 = pStrStack1;
}
int pStrOffset1 = Utils.EncodeStringUTF8(format, pStr1, pStrSize1);
pStr1[pStrOffset1] = 0;
}
byte ret = DragIntRange2Native(pStr0, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, (int)(0), pStr1, formatMax, flags);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr1);
}
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, string format, byte* formatMax, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr1 = null;
int pStrSize1 = 0;
if (format != null)
{
pStrSize1 = Utils.GetByteCountUTF8(format);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
pStr1 = Utils.Alloc<byte>(pStrSize1 + 1);
}
else
{
byte* pStrStack1 = stackalloc byte[pStrSize1 + 1];
pStr1 = pStrStack1;
}
int pStrOffset1 = Utils.EncodeStringUTF8(format, pStr1, pStrSize1);
pStr1[pStrOffset1] = 0;
}
byte ret = DragIntRange2Native(pStr0, vCurrentMin, (int*)pvCurrentMax, vSpeed, (int)(0), (int)(0), pStr1, formatMax, flags);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr1);
}
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, int* vCurrentMin, ref int vCurrentMax, string format, byte* formatMax, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr1 = null;
int pStrSize1 = 0;
if (format != null)
{
pStrSize1 = Utils.GetByteCountUTF8(format);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
pStr1 = Utils.Alloc<byte>(pStrSize1 + 1);
}
else
{
byte* pStrStack1 = stackalloc byte[pStrSize1 + 1];
pStr1 = pStrStack1;
}
int pStrOffset1 = Utils.EncodeStringUTF8(format, pStr1, pStrSize1);
pStr1[pStrOffset1] = 0;
}
byte ret = DragIntRange2Native(pStr0, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), (int)(0), (int)(0), pStr1, formatMax, flags);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr1);
}
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, int* vCurrentMin, ref int vCurrentMax, int vMin, string format, byte* formatMax, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr1 = null;
int pStrSize1 = 0;
if (format != null)
{
pStrSize1 = Utils.GetByteCountUTF8(format);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
pStr1 = Utils.Alloc<byte>(pStrSize1 + 1);
}
else
{
byte* pStrStack1 = stackalloc byte[pStrSize1 + 1];
pStr1 = pStrStack1;
}
int pStrOffset1 = Utils.EncodeStringUTF8(format, pStr1, pStrSize1);
pStr1[pStrOffset1] = 0;
}
byte ret = DragIntRange2Native(pStr0, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, (int)(0), pStr1, formatMax, flags);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr1);
}
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(string label, int* vCurrentMin, ref int vCurrentMax, int vMin, int vMax, string format, byte* formatMax, ImGuiSliderFlags flags)
{
byte* pStr0 = null;
int pStrSize0 = 0;
if (label != null)
{
pStrSize0 = Utils.GetByteCountUTF8(label);
if (pStrSize0 >= Utils.MaxStackallocSize)
{
pStr0 = Utils.Alloc<byte>(pStrSize0 + 1);
}
else
{
byte* pStrStack0 = stackalloc byte[pStrSize0 + 1];
pStr0 = pStrStack0;
}
int pStrOffset0 = Utils.EncodeStringUTF8(label, pStr0, pStrSize0);
pStr0[pStrOffset0] = 0;
}
fixed (int* pvCurrentMax = &vCurrentMax)
{
byte* pStr1 = null;
int pStrSize1 = 0;
if (format != null)
{
pStrSize1 = Utils.GetByteCountUTF8(format);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
pStr1 = Utils.Alloc<byte>(pStrSize1 + 1);
}
else
{
byte* pStrStack1 = stackalloc byte[pStrSize1 + 1];
pStr1 = pStrStack1;
}
int pStrOffset1 = Utils.EncodeStringUTF8(format, pStr1, pStrSize1);
pStr1[pStrOffset1] = 0;
}
byte ret = DragIntRange2Native(pStr0, vCurrentMin, (int*)pvCurrentMax, (float)(1.0f), vMin, vMax, pStr1, formatMax, flags);
if (pStrSize1 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr1);
}
if (pStrSize0 >= Utils.MaxStackallocSize)
{
Utils.Free(pStr0);
}
return ret != 0;
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ref byte label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, int vMax, ReadOnlySpan<byte> format, byte* formatMax, ImGuiSliderFlags flags)
{
fixed (byte* plabel = &label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, vMax, (byte*)pformat, formatMax, flags);
return ret != 0;
}
}
}
}
/// <summary>
/// To be documented.
/// </summary>
public static bool DragIntRange2(ref byte label, int* vCurrentMin, ref int vCurrentMax, float vSpeed, int vMin, int vMax, ReadOnlySpan<byte> format, byte* formatMax)
{
fixed (byte* plabel = &label)
{
fixed (int* pvCurrentMax = &vCurrentMax)
{
fixed (byte* pformat = format)
{
byte ret = DragIntRange2Native((byte*)plabel, vCurrentMin, (int*)pvCurrentMax, vSpeed, vMin, vMax, (byte*)pformat, formatMax, (ImGuiSliderFlags)(0));
return ret != 0;
}
}
}
}
}
}
| 412 | 0.89395 | 1 | 0.89395 | game-dev | MEDIA | 0.423153 | game-dev,graphics-rendering | 0.808501 | 1 | 0.808501 |
Flotapponnier/Bobavim | 1,442 | static/js/game_js_modules/tutorialHints_js_modules/hintEvents.js | import { createHintSystem } from "./hintDisplay.js";
import {
getHintContainer,
setHintContainer,
getCurrentMapId,
setCurrentMapId,
setHintVisible,
} from "./hintState.js";
// Initialize the hint system when the game loads
export function initializeTutorialHints() {
// Check if we're in a tutorial map by fetching game state
fetchCurrentMapInfo();
}
async function fetchCurrentMapInfo() {
try {
const response = await fetch(window.API_ENDPOINTS.GAME_STATE);
if (response.ok) {
const gameData = await response.json();
if (gameData.success && gameData.current_map) {
const mapInfo = gameData.current_map;
setCurrentMapId(mapInfo.id);
// Show hint system for tutorial difficulty maps, map 10 (Big boba cross), and map 14 (Inception)
if (
mapInfo.difficulty === "tutorial" ||
mapInfo.id === 10 ||
mapInfo.id === 14
) {
createHintSystem(mapInfo.id);
}
}
}
} catch (error) {
logger.error("Failed to fetch game state for tutorial hints:", error);
}
}
// Function to remove hint system (called when leaving tutorial maps)
export function removeTutorialHints() {
const hintContainer = getHintContainer();
if (hintContainer && hintContainer.parentNode) {
hintContainer.parentNode.removeChild(hintContainer);
setHintContainer(null);
setCurrentMapId(null);
setHintVisible(false);
}
}
| 412 | 0.901455 | 1 | 0.901455 | game-dev | MEDIA | 0.769114 | game-dev | 0.929382 | 1 | 0.929382 |
antlr/antlrcs | 4,992 | Runtime/Antlr3.Runtime/Misc/FastQueue.cs | /*
* [The "BSD licence"]
* Copyright (c) 2005-2008 Terence Parr
* All rights reserved.
*
* Conversion to C#:
* Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
namespace Antlr.Runtime.Misc
{
using System.Collections.Generic;
using ArgumentException = System.ArgumentException;
using InvalidOperationException = System.InvalidOperationException;
/** A queue that can dequeue and get(i) in O(1) and grow arbitrarily large.
* A linked list is fast at dequeue but slow at get(i). An array is
* the reverse. This is O(1) for both operations.
*
* List grows until you dequeue last element at end of buffer. Then
* it resets to start filling at 0 again. If adds/removes are balanced, the
* buffer will not grow too large.
*
* No iterator stuff as that's not how we'll use it.
*/
public class FastQueue<T>
{
/** <summary>dynamically-sized buffer of elements</summary> */
internal List<T> _data = new List<T>();
/** <summary>index of next element to fill</summary> */
internal int _p = 0;
public virtual int Count
{
get
{
return _data.Count - _p;
}
}
/// <summary>
/// How deep have we gone?
/// </summary>
public virtual int Range
{
get;
protected set;
}
/** <summary>
* Return element {@code i} elements ahead of current element. {@code i==0}
* gets current element. This is not an absolute index into {@link #data}
* since {@code p} defines the start of the real list.
* </summary>
*/
public virtual T this[int i]
{
get
{
int absIndex = _p + i;
if (absIndex >= _data.Count)
throw new ArgumentException(string.Format("queue index {0} > last index {1}", absIndex, _data.Count - 1));
if (absIndex < 0)
throw new ArgumentException(string.Format("queue index {0} < 0", absIndex));
if (absIndex > Range)
Range = absIndex;
return _data[absIndex];
}
}
/** <summary>Get and remove first element in queue</summary> */
public virtual T Dequeue()
{
if (Count == 0)
throw new InvalidOperationException();
T o = this[0];
_p++;
// have we hit end of buffer?
if ( _p == _data.Count )
{
// if so, it's an opportunity to start filling at index 0 again
Clear(); // size goes to 0, but retains memory
}
return o;
}
public virtual void Enqueue( T o )
{
_data.Add( o );
}
public virtual T Peek()
{
return this[0];
}
public virtual void Clear()
{
_p = 0;
_data.Clear();
}
/** <summary>Return string of current buffer contents; non-destructive</summary> */
public override string ToString()
{
System.Text.StringBuilder buf = new System.Text.StringBuilder();
int n = Count;
for ( int i = 0; i < n; i++ )
{
buf.Append( this[i] );
if ( ( i + 1 ) < n )
buf.Append( " " );
}
return buf.ToString();
}
}
}
| 412 | 0.92319 | 1 | 0.92319 | game-dev | MEDIA | 0.224857 | game-dev | 0.968684 | 1 | 0.968684 |
monun/kommand | 3,105 | kommand-core/v1.19.2/src/main/kotlin/io/github/monun/kommand/internal/compat/v1_19_2/NMSKommandSource.kt | /*
* Kommand
* Copyright (C) 2021 Monun
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package io.github.monun.kommand.internal.compat.v1_19_2
import io.github.monun.kommand.KommandSource
import io.github.monun.kommand.ref.getValue
import io.github.monun.kommand.ref.weak
import io.github.monun.kommand.internal.compat.v1_19_2.wrapper.NMSEntityAnchor
import io.github.monun.kommand.wrapper.EntityAnchor
import io.github.monun.kommand.wrapper.Position3D
import io.github.monun.kommand.wrapper.Rotation
import io.papermc.paper.brigadier.PaperBrigadier
import net.kyori.adventure.text.Component
import net.minecraft.commands.CommandSourceStack
import org.bukkit.Location
import org.bukkit.World
import org.bukkit.command.CommandSender
import org.bukkit.entity.Entity
import org.bukkit.entity.Player
import java.util.*
class NMSKommandSource private constructor(
handle: CommandSourceStack
) : KommandSource {
companion object {
private val refs = WeakHashMap<CommandSourceStack, NMSKommandSource>()
fun wrapSource(source: CommandSourceStack): NMSKommandSource =
refs.computeIfAbsent(source) {
NMSKommandSource(source)
}
}
private val handle by weak(handle)
override val displayName: Component
get() = PaperBrigadier.componentFromMessage(handle.displayName)
override val sender: CommandSender
get() = handle.bukkitSender
override val entity: Entity
get() = handle.entityOrException.bukkitEntity
override val entityOrNull: Entity?
get() = handle.entity?.bukkitEntity
override val player: Player
get() = handle.playerOrException.bukkitEntity
override val playerOrNull: Player?
get() = handle.entity?.bukkitEntity?.takeIf { it is Player } as Player?
override val position: Position3D
get() = handle.position.run { Position3D(x, y, z) }
override val rotation: Rotation
get() = handle.rotation.run { Rotation(x, y) }
override val anchor: EntityAnchor
get() = NMSEntityAnchor(handle.anchor)
override val world: World
get() = handle.level.world
override val location: Location
get() = position.toLocation(handle.level.world, rotation)
override fun hasPermission(level: Int): Boolean {
return handle.hasPermission(level)
}
override fun hasPermission(level: Int, bukkitPermission: String): Boolean {
return handle.hasPermission(level, bukkitPermission)
}
} | 412 | 0.862614 | 1 | 0.862614 | game-dev | MEDIA | 0.86105 | game-dev | 0.879242 | 1 | 0.879242 |
proletariatgames/unreal.hx | 1,580 | Haxe/Externs/UE4.19/unreal/umg/UWrapBox.hx | /**
*
* WARNING! This file was autogenerated by:
* _ _ _ _ __ __
* | | | | | | |\ \ / /
* | | | | |_| | \ V /
* | | | | _ | / \
* | |_| | | | |/ /^\ \
* \___/\_| |_/\/ \/
*
* This file was autogenerated by UnrealHxGenerator using UHT definitions.
* It only includes UPROPERTYs and UFUNCTIONs. Do not modify it!
* In order to add more definitions, create or edit a type with the same name/package, but with an `_Extra` suffix
**/
package unreal.umg;
/**
Arranges widgets left-to-right. When the widgets exceed the Width it will place widgets on the next line.
* Many Children
* Flows
* Wraps
**/
@:umodule("UMG")
@:glueCppIncludes("UMG.h")
@:uextern @:uclass extern class UWrapBox extends unreal.umg.UPanelWidget {
/**
Use explicit wrap width whenever possible. It greatly simplifies layout calculations and reduces likelihood of "wiggling UI"
**/
@:uproperty public var bExplicitWrapWidth : Bool;
/**
When this width is exceeded, elements will start appearing on the next line.
**/
@:uproperty public var WrapWidth : unreal.Float32;
/**
The inner slot padding goes between slots sharing borders
**/
@:uproperty public var InnerSlotPadding : unreal.FVector2D;
/**
Sets the inner slot padding goes between slots sharing borders
**/
@:ufunction(BlueprintCallable) @:final public function SetInnerSlotPadding(InPadding : unreal.FVector2D) : Void;
@:ufunction(BlueprintCallable) @:final public function AddChildWrapBox(Content : unreal.umg.UWidget) : unreal.umg.UWrapBoxSlot;
}
| 412 | 0.700512 | 1 | 0.700512 | game-dev | MEDIA | 0.328136 | game-dev | 0.548921 | 1 | 0.548921 |
Super-Santa/EssentialAddons | 1,682 | src/main/kotlin/me/supersanta/essential_addons/commands/FlyCommand.kt | package me.supersanta.essential_addons.commands
import com.mojang.brigadier.builder.LiteralArgumentBuilder
import com.mojang.brigadier.context.CommandContext
import me.supersanta.essential_addons.EssentialSettings
import me.supersanta.essential_addons.utils.requires
import me.supersanta.essential_addons.utils.sendToActionBar
import net.casual.arcade.commands.CommandTree
import net.casual.arcade.commands.executes
import net.casual.arcade.utils.ComponentUtils.gold
import net.casual.arcade.utils.ComponentUtils.lime
import net.casual.arcade.utils.ComponentUtils.red
import net.minecraft.commands.CommandBuildContext
import net.minecraft.commands.CommandSourceStack
import net.minecraft.network.chat.Component
object FlyCommand: CommandTree {
override fun create(buildContext: CommandBuildContext): LiteralArgumentBuilder<CommandSourceStack> {
return CommandTree.buildLiteral("fly") {
requires(EssentialSettings::commandFly, "command.fly")
executes(::toggleFlying)
}
}
private fun toggleFlying(context: CommandContext<CommandSourceStack>) {
val player = context.source.playerOrException
if (player.abilities.mayfly) {
player.abilities.mayfly = false
player.abilities.flying = false
player.sendToActionBar(
Component.literal("Flying ").append(Component.literal("Disabled").red()).gold()
)
} else {
player.abilities.mayfly = true
player.sendToActionBar(
Component.literal("Flying ").append(Component.literal("Enabled").lime()).gold()
)
}
player.onUpdateAbilities()
}
} | 412 | 0.865788 | 1 | 0.865788 | game-dev | MEDIA | 0.976961 | game-dev | 0.815551 | 1 | 0.815551 |
PowerNukkitX/PowerNukkitX | 1,924 | src/main/java/cn/nukkit/recipe/SmithingTransformRecipe.java | /*
* https://PowerNukkit.org - The Nukkit you know but Powerful!
* Copyright (C) 2020 José Roberto de Araújo Júnior
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cn.nukkit.recipe;
import cn.nukkit.item.Item;
import cn.nukkit.recipe.descriptor.ItemDescriptor;
import org.jetbrains.annotations.NotNull;
/**
* The type Smithing recipe for upgrade equipment.
*
* @author joserobjr
* @since 2020 -09-28
*/
public class SmithingTransformRecipe extends BaseRecipe {
public SmithingTransformRecipe(@NotNull String recipeId, Item result, ItemDescriptor base, ItemDescriptor addition, ItemDescriptor template) {
super(recipeId);
this.ingredients.add(base);
this.ingredients.add(addition);
this.ingredients.add(template);
this.results.add(result);
}
@Override
public boolean match(Input input) {
return false;
}
public Item getResult() {
return results.getFirst();
}
@Override
public RecipeType getType() {
return RecipeType.SMITHING_TRANSFORM;
}
public ItemDescriptor getBase() {
return ingredients.getFirst();
}
public ItemDescriptor getAddition() {
return ingredients.get(1);
}
public ItemDescriptor getTemplate() {
return ingredients.get(2);
}
}
| 412 | 0.797183 | 1 | 0.797183 | game-dev | MEDIA | 0.75733 | game-dev | 0.541096 | 1 | 0.541096 |
quisquous/cactbot | 3,417 | ui/jobs/combo_tracker.ts | import { EventEmitter } from 'eventemitter3';
import {
kComboActions,
kComboBreakers,
kComboBreakers620,
kComboBreakers630,
kComboDelay,
} from './constants';
import { FfxivVersion } from './jobs';
import { Player } from './player';
type StartMap = {
[s: string]: {
id: string;
next: StartMap;
};
};
export type ComboCallback = (id: string | undefined, combo: ComboTracker) => void;
/**
* Track combos that the current player uses.
*
* Emit `combo` event for each combo/comboBreakers skill
* - when cast in combo, skill => its HexID
* - when cast out of combo/cast comboBreakers, skill => undefined
*/
export class ComboTracker extends EventEmitter<{ combo: ComboCallback }> {
player: Player;
comboDelayMs: number;
comboTimer?: number;
comboBreakers: readonly string[];
startMap: StartMap;
considerNext: StartMap;
isFinalSkill: boolean;
constructor(
{ comboBreakers, player, comboDelayMs }: {
player: Player;
comboBreakers: readonly string[];
comboDelayMs: number;
},
) {
super();
this.player = player;
this.comboDelayMs = comboDelayMs;
this.comboTimer = undefined;
this.comboBreakers = comboBreakers;
// A tree of nodes.
this.startMap = {}; // {} key => { id: str, next: { key => node } }
this.considerNext = this.startMap;
this.isFinalSkill = false;
// register events
this.player.on('action/you', (id) => this.HandleAbility(id));
this.player.on('hp', ({ hp }) => {
if (hp === 0)
this.AbortCombo();
});
// Combos are job specific.
this.player.on('job', () => this.AbortCombo());
}
AddCombo(skillList: string[]): void {
let nextMap: StartMap = this.startMap;
skillList.forEach((id) => {
const node = {
id: id,
next: {},
};
let nextEntry = nextMap[id];
if (!nextEntry)
nextEntry = nextMap[id] = node;
nextMap = nextEntry.next;
});
}
HandleAbility(id: string): void {
if (id in this.considerNext) {
this.StateTransition(id, this.considerNext[id]);
return;
}
if (this.comboBreakers.includes(id))
this.AbortCombo(id);
}
StateTransition(id?: string, nextState?: StartMap[string]): void {
window.clearTimeout(this.comboTimer);
this.comboTimer = undefined;
this.isFinalSkill = (nextState && Object.keys(nextState.next).length === 0) ?? false;
if (!nextState || this.isFinalSkill) {
this.considerNext = this.startMap;
} else {
this.considerNext = Object.assign({}, this.startMap, nextState?.next);
this.comboTimer = window.setTimeout(() => {
this.AbortCombo();
}, this.comboDelayMs);
}
// If not aborting, then this is a valid combo skill.
this.emit('combo', nextState ? id : undefined, this);
}
AbortCombo(id?: string): void {
this.StateTransition(id);
}
static setup(ffxivVersion: FfxivVersion, player: Player): ComboTracker {
let breakers;
if (ffxivVersion < 630)
breakers = kComboBreakers620;
else if (ffxivVersion < 640)
breakers = kComboBreakers630;
else
breakers = kComboBreakers;
const comboTracker = new ComboTracker({
player: player,
comboBreakers: breakers,
comboDelayMs: kComboDelay * 1000,
});
kComboActions.forEach((skillList) => comboTracker.AddCombo(skillList));
return comboTracker;
}
}
| 412 | 0.745539 | 1 | 0.745539 | game-dev | MEDIA | 0.609886 | game-dev | 0.95254 | 1 | 0.95254 |
EssentialsX/Essentials | 1,250 | providers/NMSReflectionProvider/src/main/java/net/ess3/nms/refl/providers/ReflSyncCommandsProvider.java | package net.ess3.nms.refl.providers;
import net.ess3.nms.refl.ReflUtil;
import net.ess3.provider.SyncCommandsProvider;
import net.essentialsx.providers.ProviderData;
import org.bukkit.Bukkit;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
@ProviderData(description = "Reflection Sync Commands Provider")
public class ReflSyncCommandsProvider implements SyncCommandsProvider {
private final MethodHandle nmsSyncCommands;
public ReflSyncCommandsProvider() {
MethodHandle syncCommands = null;
final Class<?> nmsClass = ReflUtil.getOBCClass("CraftServer");
try {
syncCommands = MethodHandles.lookup().findVirtual(nmsClass, "syncCommands", MethodType.methodType(void.class));
} catch (final Exception ignored) {
// This will fail below 1.13, this is okay, we will fail silently!
}
nmsSyncCommands = syncCommands;
}
@Override
public void syncCommands() {
if (nmsSyncCommands != null) {
try {
nmsSyncCommands.invoke(Bukkit.getServer());
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
}
}
| 412 | 0.897641 | 1 | 0.897641 | game-dev | MEDIA | 0.405772 | game-dev | 0.934948 | 1 | 0.934948 |
doomeer/kalandralang | 1,061 | examples/alt-aug.kld | # This example shows how to use Orbs of Alteration and Orbs of Augmentation
# to obtain +1 to Level of All Skill Gems on an Agate Amulet.
# First, we start from an Agate Amulet with magic rarity.
buy "Metadata/Items/Amulets/Amulet9"
scour
transmute
assert (prefix_count + suffix_count) <= 2
# Then we spam.
until has "GlobalSkillGemLevel1" do {
if prefix_count = 0 then {
# No prefix: we use an Orb of Augmentation to get one.
augment
}
else {
# There is a prefix: use a Orb of Alteration.
# +1 to Level of All Skill Gems is a prefix, so there is no point
# in trying to use an Orb of Augmentation.
alt
}
# After using either an Orb of Augmentation or an Orb of Alteration,
# we check whether the amulet has the mod we want.
# This is the condition of the "until" instruction: "GlobalSkillGemLevel1"
# is the identifier for +1 to Level of All Skill Gems.
# If the item doesn't have the mod, we continue the loop.
}
# And now the current item has +1 to Level of All Skill Gems.
# It may or may not have a suffix too.
| 412 | 0.887559 | 1 | 0.887559 | game-dev | MEDIA | 0.361543 | game-dev | 0.549539 | 1 | 0.549539 |
fioprotocol/fio | 4,792 | libraries/wasm-jit/Include/WAST/TestScript.h | #pragma once
#include "Inline/BasicTypes.h"
#include "WAST.h"
#include "Runtime/TaggedValue.h"
#include <vector>
#include <memory>
namespace WAST {
struct Command {
enum Type {
_register,
action,
assert_return,
assert_return_canonical_nan,
assert_return_arithmetic_nan,
assert_trap,
assert_invalid,
assert_malformed,
assert_unlinkable
};
const Type type;
const TextFileLocus locus;
Command(Type inType, TextFileLocus &&inLocus) : type(inType), locus(inLocus) {}
};
// Parse a test script from a string. Returns true if it succeeds, and writes the test commands to outTestCommands.
WAST_API void parseTestCommands(
const char *string,
Uptr stringLength,
std::vector<std::unique_ptr<Command>> &outTestCommands,
std::vector<Error> &outErrors);
// Actions
enum class ActionType {
_module,
invoke,
get,
};
struct Action {
const ActionType type;
const TextFileLocus locus;
Action(ActionType inType, TextFileLocus &&inLocus) : type(inType), locus(inLocus) {}
};
struct ModuleAction : Action {
std::string internalModuleName;
std::unique_ptr<IR::Module> module;
ModuleAction(TextFileLocus &&inLocus, std::string &&inInternalModuleName, IR::Module *inModule)
: Action(ActionType::_module, std::move(inLocus)), internalModuleName(inInternalModuleName),
module(inModule) {}
};
struct InvokeAction : Action {
std::string internalModuleName;
std::string exportName;
std::vector<Runtime::Value> arguments;
InvokeAction(TextFileLocus &&inLocus, std::string &&inInternalModuleName, std::string &&inExportName,
std::vector<Runtime::Value> &&inArguments)
: Action(ActionType::invoke, std::move(inLocus)), internalModuleName(inInternalModuleName),
exportName(inExportName), arguments(inArguments) {}
};
struct GetAction : Action {
std::string internalModuleName;
std::string exportName;
GetAction(TextFileLocus &&inLocus, std::string &&inInternalModuleName, std::string &&inExportName)
: Action(ActionType::get, std::move(inLocus)), internalModuleName(inInternalModuleName),
exportName(inExportName) {}
};
// Commands
struct RegisterCommand : Command {
std::string moduleName;
std::string internalModuleName;
RegisterCommand(TextFileLocus &&inLocus, std::string &&inModuleName, std::string &&inInternalModuleName)
: Command(Command::_register, std::move(inLocus)), moduleName(inModuleName),
internalModuleName(inInternalModuleName) {}
};
struct ActionCommand : Command {
std::unique_ptr<Action> action;
ActionCommand(TextFileLocus &&inLocus, Action *inAction)
: Command(Command::action, std::move(inLocus)), action(inAction) {}
};
struct AssertReturnCommand : Command {
std::unique_ptr<Action> action;
Runtime::Result expectedReturn;
AssertReturnCommand(TextFileLocus &&inLocus, Action *inAction, Runtime::Result inExpectedReturn)
: Command(Command::assert_return, std::move(inLocus)), action(inAction),
expectedReturn(inExpectedReturn) {}
};
struct AssertReturnNaNCommand : Command {
std::unique_ptr<Action> action;
AssertReturnNaNCommand(Command::Type inType, TextFileLocus &&inLocus, Action *inAction)
: Command(inType, std::move(inLocus)), action(inAction) {}
};
struct AssertTrapCommand : Command {
std::unique_ptr<Action> action;
Runtime::Exception::Cause expectedCause;
AssertTrapCommand(TextFileLocus &&inLocus, Action *inAction, Runtime::Exception::Cause inExpectedCause)
: Command(Command::assert_trap, std::move(inLocus)), action(inAction), expectedCause(inExpectedCause) {}
};
struct AssertInvalidOrMalformedCommand : Command {
bool wasInvalidOrMalformed;
AssertInvalidOrMalformedCommand(Command::Type inType, TextFileLocus &&inLocus, bool inWasInvalidOrMalformed)
: Command(inType, std::move(inLocus)), wasInvalidOrMalformed(inWasInvalidOrMalformed) {}
};
struct AssertUnlinkableCommand : Command {
std::unique_ptr<ModuleAction> moduleAction;
AssertUnlinkableCommand(TextFileLocus &&inLocus, ModuleAction *inModuleAction)
: Command(Command::assert_unlinkable, std::move(inLocus)), moduleAction(inModuleAction) {}
};
} | 412 | 0.919 | 1 | 0.919 | game-dev | MEDIA | 0.657889 | game-dev | 0.892322 | 1 | 0.892322 |
ThePaperLuigi/The-Stars-Above | 10,954 | Projectiles/Summon/Takodachi/TakonomiconLaser.cs | using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using Terraria;
using Terraria.GameContent;
using Terraria.Enums;
using Terraria.ModLoader;
using static Terraria.ModLoader.ModContent;
using StarsAbove.Buffs.Summon.Takonomicon;
using StarsAbove.Systems;
namespace StarsAbove.Projectiles.Summon.Takodachi
{
// The following laser shows a channeled ability, after charging up the laser will be fired
// Using custom drawing, dust effects, and custom collision checks for tiles
public class TakonomiconLaser : ModProjectile
{
// Use a different style for constant so it is very clear in code when a constant is used
// The maximum charge value
private const float MAX_CHARGE = 10f;
//The distance charge particle from the player center
private const float MOVE_DISTANCE = 28f;
// The actual distance is stored in the ai0 field
// By making a property to handle this it makes our life easier, and the accessibility more readable
public float Distance
{
get => Projectile.ai[0];
set => Projectile.ai[0] = value;
}
// The actual charge value is stored in the localAI0 field
public float Charge
{
get => Projectile.localAI[0];
set => Projectile.localAI[0] = value;
}
// Are we at max charge? With c#6 you can simply use => which indicates this is a get only property
public bool IsAtMaxCharge => Charge == MAX_CHARGE;
public override void SetDefaults()
{
Projectile.width = 10;
Projectile.height = 10;
Projectile.friendly = true;
Projectile.penetrate = -1;
Projectile.tileCollide = false;
Projectile.minion = true;
Projectile.DamageType = DamageClass.Summon;
Projectile.hide = false;
Projectile.timeLeft = 900;
}
public override bool PreDraw(ref Color lightColor)
{
// We start drawing the laser if we have charged up
if (IsAtMaxCharge)
{
DrawLaser(Main.spriteBatch, (Texture2D)TextureAssets.Projectile[Projectile.type], Main.player[Projectile.owner].Center,
Projectile.velocity, 10, Projectile.damage, -1.57f, 1f, 1000f, Color.White, (int)MOVE_DISTANCE);
}
return false;
}
// The core function of drawing a laser
public void DrawLaser(SpriteBatch spriteBatch, Texture2D texture, Vector2 start, Vector2 unit, float step, int damage, float rotation = 0f, float scale = 1f, float maxDist = 2000f, Color color = default, int transDist = 50)
{
float r = unit.ToRotation() + rotation;
// Draws the laser 'body'
for (float i = transDist; i <= Distance; i += step)
{
Color c = Color.White;
var origin = start + i * unit;
spriteBatch.Draw(texture, origin - Main.screenPosition,
new Rectangle(0, 26, 28, 26), i < transDist ? Color.Transparent : c, r,
new Vector2(28 * .5f, 26 * .5f), scale, 0, 0);
}
// Draws the laser 'tail'
spriteBatch.Draw(texture, start + unit * (transDist - step) - Main.screenPosition,
new Rectangle(0, 0, 28, 26), Color.White, r, new Vector2(28 * .5f, 26 * .5f), scale, 0, 0);
// Draws the laser 'head'
spriteBatch.Draw(texture, start + (Distance + step) * unit - Main.screenPosition,
new Rectangle(0, 52, 28, 26), Color.White, r, new Vector2(28 * .5f, 26 * .5f), scale, 0, 0);
}
// Change the way of collision check of the projectile
public override bool? Colliding(Rectangle projHitbox, Rectangle targetHitbox)
{
// We can only collide if we are at max charge, which is when the laser is actually fired
if (!IsAtMaxCharge) return false;
Player player = Main.player[Projectile.owner];
Vector2 unit = Projectile.velocity;
float point = 0f;
// Run an AABB versus Line check to look for collisions, look up AABB collision first to see how it works
// It will look for collisions on the given line using AABB
return Collision.CheckAABBvLineCollision(targetHitbox.TopLeft(), targetHitbox.Size(), player.Center,
player.Center + unit * Distance, 22, ref point);
}
// Set custom immunity time on hitting an NPC
public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone)
{
target.immune[Projectile.owner] = 4;
}
// The AI of the projectile
public override void AI()
{
Player player = Main.player[Projectile.owner];
Projectile.position = player.Center + Projectile.velocity * MOVE_DISTANCE;
//projectile.timeLeft = 2;
// By separating large AI into methods it becomes very easy to see the flow of the AI in a broader sense
// First we update player variables that are needed to channel the laser
// Then we run our charging laser logic
// If we are fully charged, we proceed to update the laser's position
// Finally we spawn some effects like dusts and light
UpdatePlayer(player);
ChargeLaser(player);
// If laser is not charged yet, stop the AI here.
if (Charge < MAX_CHARGE) return;
SetLaserPosition(player);
SpawnDusts(player);
CastLights();
}
private void SpawnDusts(Player player)
{
Vector2 unit = Projectile.velocity * -1;
Vector2 dustPos = player.Center + Projectile.velocity * Distance;
for (int i = 0; i < 2; ++i)
{
float num1 = Projectile.velocity.ToRotation() + (Main.rand.Next(2) == 1 ? -1.0f : 1.0f) * 1.57f;
float num2 = (float)(Main.rand.NextDouble() * 0.8f + 1.0f);
Vector2 dustVel = new Vector2((float)Math.Cos(num1) * num2, (float)Math.Sin(num1) * num2);
Dust dust = Main.dust[Dust.NewDust(dustPos, 0, 0, 223, dustVel.X, dustVel.Y)];
dust.noGravity = true;
dust.scale = 1.2f;
dust = Dust.NewDustDirect(Main.player[Projectile.owner].Center, 0, 0, 31,
-unit.X * Distance, -unit.Y * Distance);
dust.fadeIn = 0f;
dust.noGravity = true;
dust.scale = 0.88f;
dust.color = Color.Pink;
}
}
/*
* Sets the end of the laser position based on where it collides with something
*/
private void SetLaserPosition(Player player)
{
for (Distance = MOVE_DISTANCE; Distance <= 2200f; Distance += 5f)
{
var start = player.Center + Projectile.velocity * Distance;
if (!Collision.CanHit(player.Center, 1, 1, start, 1, 1))
{
Distance -= 5f;
break;
}
}
}
private void ChargeLaser(Player player)
{
// Kill the projectile if the player stops channeling
if (!player.HasBuff(BuffType<TakodachiLaserBuff>()))
{
Projectile.Kill();
}
else
{
// Do we still have enough mana? If not, we kill the projectile because we cannot use it anymore
/*if (Main.time % 10 < 1 && !player.CheckMana(player.inventory[player.selectedItem].mana, true))
{
//projectile.Kill();
}*/
Vector2 offset = Projectile.velocity;
offset *= MOVE_DISTANCE - 20;
Vector2 pos = player.Center + offset - new Vector2(10, 10);
if (Charge < MAX_CHARGE)
{
Charge++;
}
int chargeFact = (int)(Charge / 20f);
Vector2 dustVelocity = Vector2.UnitX * 18f;
dustVelocity = dustVelocity.RotatedBy(Projectile.rotation - 1.57f);
Vector2 spawnPos = Projectile.Center + dustVelocity;
for (int k = 0; k < chargeFact + 1; k++)
{
Vector2 spawn = spawnPos + ((float)Main.rand.NextDouble() * 6.28f).ToRotationVector2() * (12f - chargeFact * 2);
Dust dust = Main.dust[Dust.NewDust(pos, 20, 20, 223, Projectile.velocity.X / 2f, Projectile.velocity.Y / 2f)];
dust.velocity = Vector2.Normalize(spawnPos - spawn) * 1.5f * (10f - chargeFact * 2f) / 10f;
dust.noGravity = true;
dust.scale = Main.rand.Next(10, 20) * 0.05f;
}
}
}
private void UpdatePlayer(Player player)
{
// Multiplayer support here, only run this code if the client running it is the owner of the projectile
if (Projectile.owner == Main.myPlayer)
{
Vector2 diff = player.GetModPlayer<WeaponPlayer>().takoTarget - player.Center;
diff.Normalize();
Projectile.velocity = diff;
Projectile.direction = player.GetModPlayer<WeaponPlayer>().takoTarget.X > player.Center.X ? 1 : -1;
Projectile.netUpdate = true;
}
int dir = Projectile.direction;
player.ChangeDir(dir); // Set player direction to where we are shooting
player.heldProj = Projectile.whoAmI; // Update player's held projectile
player.itemTime = 2; // Set item time to 2 frames while we are used
player.itemAnimation = 2; // Set item animation time to 2 frames while we are used
player.itemRotation = (float)Math.Atan2(Projectile.velocity.Y * dir, Projectile.velocity.X * dir); // Set the item rotation to where we are shooting
}
private void CastLights()
{
// Cast a light along the line of the laser
DelegateMethods.v3_1 = new Vector3(0.8f, 0.8f, 1f);
Utils.PlotTileLine(Projectile.Center, Projectile.Center + Projectile.velocity * (Distance - MOVE_DISTANCE), 26, DelegateMethods.CastLight);
}
public override bool ShouldUpdatePosition() => false;
/*
* Update CutTiles so the laser will cut tiles (like grass)
*/
public override void CutTiles()
{
DelegateMethods.tilecut_0 = TileCuttingContext.AttackProjectile;
Vector2 unit = Projectile.velocity;
Utils.PlotTileLine(Projectile.Center, Projectile.Center + unit * Distance, (Projectile.width + 16) * Projectile.scale, DelegateMethods.CutTiles);
}
}
}
| 412 | 0.926987 | 1 | 0.926987 | game-dev | MEDIA | 0.992087 | game-dev | 0.986225 | 1 | 0.986225 |
mapbox/mapbox-ar-unity | 1,037 | Assets/UnityARKitPlugin/Plugins/iOS/UnityARKit/Helpers/UnityARGeneratePlane.cs | using System;
using System.Collections.Generic;
namespace UnityEngine.XR.iOS
{
public class UnityARGeneratePlane : MonoBehaviour
{
public GameObject planePrefab;
private UnityARAnchorManager unityARAnchorManager;
// Use this for initialization
void Start () {
unityARAnchorManager = new UnityARAnchorManager();
UnityARUtility.InitializePlanePrefab (planePrefab);
}
void OnDestroy()
{
unityARAnchorManager.Destroy ();
}
void OnGUI()
{
List<ARPlaneAnchorGameObject> arpags = unityARAnchorManager.GetCurrentPlaneAnchors ();
if (arpags.Count >= 1) {
//ARPlaneAnchor ap = arpags [0].planeAnchor;
//GUI.Box (new Rect (100, 100, 800, 60), string.Format ("Center: x:{0}, y:{1}, z:{2}", ap.center.x, ap.center.y, ap.center.z));
//GUI.Box(new Rect(100, 200, 800, 60), string.Format ("Extent: x:{0}, y:{1}, z:{2}", ap.extent.x, ap.extent.y, ap.extent.z));
}
}
}
}
| 412 | 0.732782 | 1 | 0.732782 | game-dev | MEDIA | 0.923224 | game-dev | 0.894871 | 1 | 0.894871 |
HyperMC-Team/OpenRoxy | 2,514 | src/main/java/net/minecraft/item/ItemBed.java | package net.minecraft.item;
import net.minecraft.block.Block;
import net.minecraft.block.BlockBed;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
public class ItemBed
extends Item {
public ItemBed() {
this.setCreativeTab(CreativeTabs.tabDecorations);
}
@Override
public boolean onItemUse(ItemStack stack, EntityPlayer playerIn, World worldIn, BlockPos pos, EnumFacing side, float hitX, float hitY, float hitZ) {
if (worldIn.isRemote) {
return true;
}
if (side != EnumFacing.UP) {
return false;
}
IBlockState iblockstate = worldIn.getBlockState(pos);
Block block = iblockstate.getBlock();
boolean flag = block.isReplaceable(worldIn, pos);
if (!flag) {
pos = pos.up();
}
int i = MathHelper.floor_double((double)(playerIn.rotationYaw * 4.0f / 360.0f) + 0.5) & 3;
EnumFacing enumfacing = EnumFacing.getHorizontal(i);
BlockPos blockpos = pos.offset(enumfacing);
if (playerIn.canPlayerEdit(pos, side, stack) && playerIn.canPlayerEdit(blockpos, side, stack)) {
boolean flag3;
boolean flag1 = worldIn.getBlockState(blockpos).getBlock().isReplaceable(worldIn, blockpos);
boolean flag2 = flag || worldIn.isAirBlock(pos);
boolean bl = flag3 = flag1 || worldIn.isAirBlock(blockpos);
if (flag2 && flag3 && World.doesBlockHaveSolidTopSurface(worldIn, pos.down()) && World.doesBlockHaveSolidTopSurface(worldIn, blockpos.down())) {
IBlockState iblockstate1 = Blocks.bed.getDefaultState().withProperty(BlockBed.OCCUPIED, false).withProperty(BlockBed.FACING, enumfacing).withProperty(BlockBed.PART, BlockBed.EnumPartType.FOOT);
if (worldIn.setBlockState(pos, iblockstate1, 3)) {
IBlockState iblockstate2 = iblockstate1.withProperty(BlockBed.PART, BlockBed.EnumPartType.HEAD);
worldIn.setBlockState(blockpos, iblockstate2, 3);
}
--stack.stackSize;
return true;
}
return false;
}
return false;
}
}
| 412 | 0.760823 | 1 | 0.760823 | game-dev | MEDIA | 0.998334 | game-dev | 0.85279 | 1 | 0.85279 |
SolarMoonQAQ/Spark-Core | 2,555 | src/main/java/com/jme3/bullet/objects/infos/Aero.java | /*
* Copyright (c) 2019 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.bullet.objects.infos;
/**
* Enumerate the implemented aerodynamic models for a SoftBodyConfig.
*
* @author Stephen Gold sgold@sonic.net
* @see SoftBodyConfig#aerodynamics()
*/
public enum Aero {
// *************************************************************************
// values
/**
* Vertex normals are oriented toward velocity.
*/
V_Point,
/**
* Vertex normals are flipped to match velocity.
*/
V_TwoSided,
/**
* Vertex normals are flipped to match velocity. Lift and drag forces are
* applied.
*/
V_TwoSidedLiftDrag,
/**
* Vertex normals are taken as they are.
*/
V_OneSided,
/**
* Face normals are flipped to match velocity.
*/
F_TwoSided,
/**
* Face normals are flipped to match velocity. Lift and drag forces are
* applied.
*/
F_TwoSidedLiftDrag,
/**
* Face normals are taken as they are.
*/
F_OneSided
}
| 412 | 0.631605 | 1 | 0.631605 | game-dev | MEDIA | 0.436403 | game-dev | 0.582523 | 1 | 0.582523 |
PacktPublishing/Mastering-Cpp-Game-Development | 2,129 | Chapter08/Include/bullet/BulletDynamics/Featherstone/btMultiBodyPoint2Point.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2013 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.
*/
///This file was written by Erwin Coumans
#ifndef BT_MULTIBODY_POINT2POINT_H
#define BT_MULTIBODY_POINT2POINT_H
#include "btMultiBodyConstraint.h"
//#define BTMBP2PCONSTRAINT_BLOCK_ANGULAR_MOTION_TEST
class btMultiBodyPoint2Point : public btMultiBodyConstraint
{
protected:
btRigidBody* m_rigidBodyA;
btRigidBody* m_rigidBodyB;
btVector3 m_pivotInA;
btVector3 m_pivotInB;
public:
btMultiBodyPoint2Point(btMultiBody* body, int link, btRigidBody* bodyB, const btVector3& pivotInA, const btVector3& pivotInB);
btMultiBodyPoint2Point(btMultiBody* bodyA, int linkA, btMultiBody* bodyB, int linkB, const btVector3& pivotInA, const btVector3& pivotInB);
virtual ~btMultiBodyPoint2Point();
virtual void finalizeMultiDof();
virtual int getIslandIdA() const;
virtual int getIslandIdB() const;
virtual void createConstraintRows(btMultiBodyConstraintArray& constraintRows,
btMultiBodyJacobianData& data,
const btContactSolverInfo& infoGlobal);
const btVector3& getPivotInB() const
{
return m_pivotInB;
}
void setPivotInB(const btVector3& pivotInB)
{
m_pivotInB = pivotInB;
}
virtual void debugDraw(class btIDebugDraw* drawer);
};
#endif //BT_MULTIBODY_POINT2POINT_H
| 412 | 0.711704 | 1 | 0.711704 | game-dev | MEDIA | 0.989606 | game-dev | 0.672453 | 1 | 0.672453 |
cms-sw/cmssw | 4,261 | FWCore/Common/src/LuminosityBlockBase.cc | // -*- C++ -*-
//
// Package: FWCore/Common
// Class : LuminosityBlockBase
//
// Implementation:
// <Notes on implementation>
//
// Original Author: Eric Vaandering
// Created: Tue Jan 12 15:31:00 CDT 2010
//
// system include files
#include <vector>
#include <map>
// user include files
#include "FWCore/Common/interface/LuminosityBlockBase.h"
//#include "FWCore/Common/interface/TriggerNames.h"
//#include "DataFormats/Provenance/interface/ParameterSetID.h"
//#include "DataFormats/Common/interface/TriggerResults.h"
//#include "FWCore/Utilities/interface/Exception.h"
//#include "FWCore/Utilities/interface/ThreadSafeRegistry.h"
//#include "FWCore/ParameterSet/interface/ParameterSet.h"
//#include "FWCore/ParameterSet/interface/Registry.h"
namespace edm {
// typedef std::map<edm::ParameterSetID, edm::TriggerNames> TriggerNamesMap;
// static TriggerNamesMap triggerNamesMap;
// static TriggerNamesMap::const_iterator previousTriggerName;
LuminosityBlockBase::LuminosityBlockBase() {}
LuminosityBlockBase::~LuminosityBlockBase() {}
/* TriggerNames const*
EventBase::triggerNames_(edm::TriggerResults const& triggerResults) {
// If the current and previous requests are for the same TriggerNames
// then just return it.
if (!triggerNamesMap.empty() &&
previousTriggerName->first == triggerResults.parameterSetID()) {
return &previousTriggerName->second;
}
// If TriggerNames was already created and cached here in the map,
// then look it up and return that one
TriggerNamesMap::const_iterator iter =
triggerNamesMap.find(triggerResults.parameterSetID());
if (iter != triggerNamesMap.end()) {
previousTriggerName = iter;
return &iter->second;
}
// Look for the parameter set containing the trigger names in the parameter
// set registry using the ID from TriggerResults as the key used to find it.
edm::ParameterSet pset;
edm::pset::Registry* psetRegistry = edm::pset::Registry::instance();
if (psetRegistry->getMapped(triggerResults.parameterSetID(),
pset)) {
if (pset.existsAs<std::vector<std::string> >("@trigger_paths", true)) {
TriggerNames triggerNames(pset);
// This should never happen
if (triggerNames.size() != triggerResults.size()) {
throw cms::Exception("LogicError")
<< "edm::EventBase::triggerNames_ Encountered vector\n"
"of trigger names and a TriggerResults object with\n"
"different sizes. This should be impossible.\n"
"Please send information to reproduce this problem to\n"
"the edm developers.\n";
}
std::pair<TriggerNamesMap::iterator, bool> ret =
triggerNamesMap.insert(std::pair<edm::ParameterSetID, edm::TriggerNames>(triggerResults.parameterSetID(), triggerNames));
previousTriggerName = ret.first;
return &(ret.first->second);
}
}
// For backward compatibility to very old data
if (triggerResults.getTriggerNames().size() > 0U) {
edm::ParameterSet fakePset;
fakePset.addParameter<std::vector<std::string> >("@trigger_paths", triggerResults.getTriggerNames());
fakePset.registerIt();
TriggerNames triggerNames(fakePset);
// This should never happen
if (triggerNames.size() != triggerResults.size()) {
throw cms::Exception("LogicError")
<< "edm::EventBase::triggerNames_ Encountered vector\n"
"of trigger names and a TriggerResults object with\n"
"different sizes. This should be impossible.\n"
"Please send information to reproduce this problem to\n"
"the edm developers (2).\n";
}
std::pair<TriggerNamesMap::iterator, bool> ret =
triggerNamesMap.insert(std::pair<edm::ParameterSetID, edm::TriggerNames>(fakePset.id(), triggerNames));
previousTriggerName = ret.first;
return &(ret.first->second);
}
return 0;
}*/
} // namespace edm
| 412 | 0.968385 | 1 | 0.968385 | game-dev | MEDIA | 0.35397 | game-dev | 0.899681 | 1 | 0.899681 |
imchillin/Anamnesis | 6,173 | Anamnesis/Actor/Pages/ActionPage.xaml.cs | // © Anamnesis.
// Licensed under the MIT license.
namespace Anamnesis.Actor.Pages;
using Anamnesis.Actor.Views;
using Anamnesis.GameData.Excel;
using Anamnesis.GameData.Interfaces;
using Anamnesis.Keyboard;
using Anamnesis.Memory;
using Anamnesis.Services;
using Anamnesis.Styles;
using Anamnesis.Styles.Drawers;
using PropertyChanged;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Controls;
[AddINotifyPropertyChangedInterface]
public partial class ActionPage : UserControl
{
public ActionPage()
{
this.InitializeComponent();
this.ContentArea.DataContext = this;
this.LipSyncTypes = GenerateLipList();
HotkeyService.RegisterHotkeyHandler("ActionPage.ResumeAll", this.OnResumeAll);
HotkeyService.RegisterHotkeyHandler("ActionPage.PauseAll", this.OnPauseAll);
}
public static GposeService GposeService => GposeService.Instance;
public static AnimationService AnimationService => AnimationService.Instance;
public static PoseService PoseService => PoseService.Instance;
public ActorMemory? Actor { get; private set; }
public IEnumerable<ActionTimeline> LipSyncTypes { get; private set; }
public UserAnimationOverride AnimationOverride { get; private set; } = new();
public ConditionalWeakTable<ActorMemory, UserAnimationOverride> UserAnimationOverrides { get; private set; } = [];
private static IEnumerable<ActionTimeline> GenerateLipList()
{
// Grab "no animation" and all "speak/" animations, which are the only ones valid in this slot
IEnumerable<ActionTimeline> lips = GameDataService.ActionTimelines.Where(x => x.AnimationId == 0 || (x.Key?.StartsWith("speak/") ?? false));
return lips;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
this.OnActorChanged(this.DataContext as ActorMemory);
}
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
this.OnActorChanged(this.DataContext as ActorMemory);
}
private void OnActorChanged(ActorMemory? actor)
{
if (this.Actor != null) // Save the current settings
this.UserAnimationOverrides.AddOrUpdate(this.Actor, this.AnimationOverride);
this.Actor = actor;
Application.Current.Dispatcher.InvokeAsync(() =>
{
bool hasValidSelection = actor != null && actor.ObjectKind.IsSupportedType();
this.IsEnabled = hasValidSelection;
});
if (actor != null)
{
if (this.UserAnimationOverrides.TryGetValue(actor, out UserAnimationOverride? userAnimationOverride))
{
this.AnimationOverride = userAnimationOverride;
}
else
{
this.AnimationOverride = new()
{
BaseAnimationId = actor.Animation!.AnimationIds![(int)AnimationMemory.AnimationSlots.FullBody].Value,
BlendAnimationId = 0,
};
}
}
}
private void OnBaseAnimationSearchClicked(object sender, RoutedEventArgs e)
{
if (this.Actor == null)
return;
AnimationSelector animSelector = SelectorDrawer.Show<AnimationSelector, IAnimation>(null, (animation) =>
{
if (animation == null || animation.Timeline == null)
return;
this.AnimationOverride.BaseAnimationId = animation.Timeline.Value.AnimationId;
});
animSelector.LocalAnimationSlotFilter = new()
{
IncludeBlendable = false,
IncludeFullBody = true,
SlotsLocked = true,
};
}
private void OnBlendAnimationSearchClicked(object sender, RoutedEventArgs e)
{
if (this.Actor == null)
return;
AnimationSelector animSelector = SelectorDrawer.Show<AnimationSelector, IAnimation>(null, (animation) =>
{
if (animation == null || animation.Timeline == null)
return;
this.AnimationOverride.BlendAnimationId = animation.Timeline.Value.AnimationId;
});
animSelector.LocalAnimationSlotFilter = new()
{
IncludeBlendable = true,
IncludeFullBody = true,
SlotsLocked = false,
};
}
private void OnApplyOverrideAnimation(object sender, RoutedEventArgs e)
{
if (this.Actor?.IsValid != true)
return;
AnimationService.ApplyAnimationOverride(this.Actor, this.AnimationOverride.BaseAnimationId, this.AnimationOverride.Interrupt);
}
private void OnDrawWeaponOverrideAnimation(object sender, RoutedEventArgs e)
{
if (this.Actor?.IsValid != true)
return;
AnimationService.DrawWeapon(this.Actor);
}
private async void OnBlendAnimation(object sender, RoutedEventArgs e)
{
if (this.Actor?.IsValid != true)
return;
await AnimationService.BlendAnimation(this.Actor, this.AnimationOverride.BlendAnimationId);
this.AnimationBlendButton.Focus(); // Refocus on the button as the blend lock changes state in the function call above
}
private void OnIdleOverrideAnimation(object sender, RoutedEventArgs e)
{
if (this.Actor?.IsValid != true)
return;
AnimationService.ApplyIdle(this.Actor);
}
private void OnResetOverrideAnimation(object sender, RoutedEventArgs e)
{
if (this.Actor?.IsValid != true)
return;
AnimationService.ResetAnimationOverride(this.Actor);
}
private void OnResumeAll(object sender, RoutedEventArgs e) => this.OnResumeAll();
private void OnResumeAll()
{
if (!GposeService.Instance.IsGpose)
return;
AnimationService.Instance.SpeedControlEnabled = true;
foreach (var target in TargetService.Instance.PinnedActors.ToList())
{
if (target.IsValid && target.Memory != null && target.Memory.IsValid)
{
target.Memory.Animation!.LinkSpeeds = true;
target.Memory.Animation!.Speeds![0].Value = 1.0f;
}
}
}
private void OnPauseAll(object sender, RoutedEventArgs e) => this.OnPauseAll();
private void OnPauseAll()
{
if (!GposeService.Instance.IsGpose)
return;
AnimationService.Instance.SpeedControlEnabled = true;
foreach (var target in TargetService.Instance.PinnedActors.ToList())
{
if (target.IsValid && target.Memory != null && target.Memory.IsValid)
{
target.Memory.Animation!.LinkSpeeds = true;
target.Memory.Animation!.Speeds![0].Value = 0.0f;
}
}
}
[AddINotifyPropertyChangedInterface]
public class UserAnimationOverride
{
public ushort BaseAnimationId { get; set; } = 0;
public ushort BlendAnimationId { get; set; } = 0;
public bool Interrupt { get; set; } = true;
}
}
| 412 | 0.801508 | 1 | 0.801508 | game-dev | MEDIA | 0.827443 | game-dev | 0.962867 | 1 | 0.962867 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.