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
b3dgs/lionengine
3,012
lionengine-game/src/main/java/com/b3dgs/lionengine/game/MoverModel.java
/* * Copyright (C) 2013-2024 Byron 3D Games Studio (www.b3dgs.com) Pierre-Alexandre (contact@b3dgs.com) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.b3dgs.lionengine.game; /** * Mover model implementation. */ public class MoverModel implements Mover { /** Current x. */ private double x; /** Current y. */ private double y; /** Old x. */ private double oldX; /** Old y. */ private double oldY; /** * Create model. */ public MoverModel() { super(); } @Override public void backup() { oldX = x; oldY = y; } @Override public void moveLocation(double extrp, Direction direction, Direction... directions) { double vx = direction.getDirectionHorizontal(); double vy = direction.getDirectionVertical(); for (final Direction current : directions) { vx += current.getDirectionHorizontal(); vy += current.getDirectionVertical(); } setLocation(x + vx * extrp, y + vy * extrp); } @Override public void moveLocationX(double extrp, double vx) { setLocationX(x + vx * extrp); } @Override public void moveLocationY(double extrp, double vy) { setLocationY(y + vy * extrp); } @Override public void moveLocation(double extrp, double vx, double vy) { setLocation(x + vx * extrp, y + vy * extrp); } @Override public void teleport(double x, double y) { teleportX(x); teleportY(y); } @Override public void teleportX(double x) { this.x = x + 0.0; oldX = this.x; } @Override public void teleportY(double y) { this.y = y + 0.0; oldY = this.y; } @Override public void setLocation(double x, double y) { setLocationX(x); setLocationY(y); } @Override public void setLocationX(double x) { this.x = x + 0.0; } @Override public void setLocationY(double y) { this.y = y + 0.0; } @Override public double getX() { return x; } @Override public double getY() { return y; } @Override public double getOldX() { return oldX; } @Override public double getOldY() { return oldY; } }
412
0.856544
1
0.856544
game-dev
MEDIA
0.765334
game-dev
0.967886
1
0.967886
FakeFishGames/Barotrauma
7,677
Barotrauma/BarotraumaShared/SharedSource/Events/EventActions/NPCOperateItemAction.cs
using Barotrauma.Extensions; using Barotrauma.Items.Components; using System.Collections.Generic; using System.Linq; using System; namespace Barotrauma { /// <summary> /// Makes an NPC select an item, and operate it if it's something AI characters can operate. /// </summary> class NPCOperateItemAction : EventAction { [Serialize("", IsPropertySaveable.Yes, description: "Tag of the NPC(s) that should operate the item.")] public Identifier NPCTag { get; set; } [Serialize("", IsPropertySaveable.Yes, description: "Tag of the item to operate. If it's not something AI characters can or know how to operate, such as a cabinet or an engine, the NPC will just select it.")] public Identifier TargetTag { get; set; } [Serialize("Controller", IsPropertySaveable.Yes, description: "Name of the component to operate. For example, the Controller component of a periscope or the Reactor component of a nuclear reactor.")] public Identifier ItemComponentName { get; set; } [Serialize("", IsPropertySaveable.Yes, description: "Identifier of the option, if there are several ways the item can be operated. For example, \"powerup\" or \"shutdown\" when operating a reactor.")] public Identifier OrderOption { get; set; } [Serialize(false, IsPropertySaveable.Yes, description: "Should the character equip the item before attempting to operate it (only valid if the item is equippable).")] public bool RequireEquip { get; set; } [Serialize(true, IsPropertySaveable.Yes, description: "Should the character start or stop operating the item.")] public bool Operate { get; set; } [Serialize(-1, IsPropertySaveable.Yes, description: "Maximum number of NPCs the action can target. For example, you could only make a specific number of security officers man a periscope.")] public int MaxTargets { get; set; } [Serialize(AIObjectiveManager.MaxObjectivePriority, IsPropertySaveable.Yes, description: "AI priority for the action. Uses 100 by default, which is the absolute maximum for any objectives, " + "meaning nothing can be prioritized over it, including the emergency objectives, such as find safety and combat." + "Setting the priority to 70 would function like a regular order, but with the highest priority." + "A priority of 60 would make the objective work like a lowest priority order." + "So, if we'll want the character to operate the item, but still be able to find safety, defend themselves when attacked, or flee from dangers," + "it's better to use e.g. 70 instead of 100.")] public float Priority { get => _priority; set => _priority = Math.Clamp(value, AIObjectiveManager.LowestOrderPriority, AIObjectiveManager.MaxObjectivePriority); } private float _priority; [Serialize(true, IsPropertySaveable.Yes, description: "The event actions reset when a GoTo action makes the event jump to a different point. Should the NPC stop operating the item when the event resets?")] public bool AbandonOnReset { get; set; } private bool isFinished = false; public NPCOperateItemAction(ScriptedEvent parentEvent, ContentXElement element) : base(parentEvent, element) { } private List<Character> affectedNpcs = null; private Item target = null; public override void Update(float deltaTime) { if (isFinished) { return; } var potentialTargets = ParentEvent.GetTargets(TargetTag).OfType<Item>(); var nonSelectedItems = potentialTargets.Where(it => it.GetComponent<Controller>()?.User == null); target = nonSelectedItems.Any() ? nonSelectedItems.GetRandomUnsynced() : potentialTargets.GetRandomUnsynced(); if (target == null) { return; } int targetCount = 0; affectedNpcs = ParentEvent.GetTargets(NPCTag).Where(c => c is Character).Select(c => c as Character).ToList(); foreach (var npc in affectedNpcs) { if (npc.Removed) { continue; } if (npc.AIController is not HumanAIController humanAiController) { continue; } if (Operate) { var itemComponent = target.Components.FirstOrDefault(ic => ItemComponentName == ic.Name); if (itemComponent == null) { DebugConsole.AddWarning($"Error in NPCOperateItemAction: could not find the component \"{ItemComponentName}\" in item \"{target.Name}\"."); } else { var newObjective = new AIObjectiveOperateItem(itemComponent, npc, humanAiController.ObjectiveManager, OrderOption, RequireEquip) { OverridePriority = Priority }; humanAiController.ObjectiveManager.AddObjective(newObjective); humanAiController.ObjectiveManager.WaitTimer = 0.0f; humanAiController.ObjectiveManager.Objectives.RemoveAll(o => o is AIObjectiveGoTo gotoOjective); } } else { foreach (var objective in humanAiController.ObjectiveManager.Objectives) { if (objective is AIObjectiveOperateItem operateItemObjective && operateItemObjective.Component.Item == target) { objective.Abandon = true; } } } targetCount++; if (MaxTargets > -1 && targetCount >= MaxTargets) { break; } } isFinished = true; } public override bool IsFinished(ref string goTo) { return isFinished; } public override void Reset() { if (affectedNpcs != null && target != null && AbandonOnReset) { foreach (var npc in affectedNpcs) { if (npc.Removed || npc.AIController is not HumanAIController humanAiController) { continue; } foreach (var operateItemObjective in humanAiController.ObjectiveManager.GetActiveObjectives<AIObjectiveOperateItem>()) { if (operateItemObjective.Component.Item == target) { operateItemObjective.Abandon = true; } } } target = null; affectedNpcs = null; } isFinished = false; } public override string ToDebugString() { return $"{ToolBox.GetDebugSymbol(isFinished)} {nameof(AIObjectiveOperateItem)} -> (NPCTag: {NPCTag.ColorizeObject()}, TargetTag: {TargetTag.ColorizeObject()}, Operate: {Operate.ColorizeObject()})"; } } }
412
0.930596
1
0.930596
game-dev
MEDIA
0.958241
game-dev
0.957224
1
0.957224
mayao11/PracticalGameAI
1,414
AI_Enemy3_Behavior/Assets/Behavior Designer/Runtime/Basic Tasks/Transform/GetLocalScale.cs
using UnityEngine; namespace BehaviorDesigner.Runtime.Tasks.Basic.UnityTransform { [TaskCategory("Basic/Transform")] [TaskDescription("Stores the local scale of the Transform. Returns Success.")] public class GetLocalScale : Action { [Tooltip("The GameObject that the task operates on. If null the task GameObject is used.")] public SharedGameObject targetGameObject; [Tooltip("The local scale of the Transform")] [RequiredField] public SharedVector3 storeValue; private Transform targetTransform; private GameObject prevGameObject; public override void OnStart() { var currentGameObject = GetDefaultGameObject(targetGameObject.Value); if (currentGameObject != prevGameObject) { targetTransform = currentGameObject.GetComponent<Transform>(); prevGameObject = currentGameObject; } } public override TaskStatus OnUpdate() { if (targetTransform == null) { Debug.LogWarning("Transform is null"); return TaskStatus.Failure; } storeValue.Value = targetTransform.localScale; return TaskStatus.Success; } public override void OnReset() { targetGameObject = null; storeValue = Vector3.zero; } } }
412
0.877247
1
0.877247
game-dev
MEDIA
0.952187
game-dev
0.901238
1
0.901238
ceramic-engine/ceramic
61,530
runtime/src/ceramic/Particles.hx
package ceramic; import ceramic.Shortcuts.*; /** * A visual container that manages a particle emitter with convenient automatic emission modes. * * Particles extends Visual to provide a high-level wrapper around ParticleEmitter, * adding features like automatic continuous emission and timed burst intervals. * This makes it easier to create self-contained particle effects that can be * added to the scene and configured with minimal code. * * The class is generic, allowing use of custom ParticleEmitter subclasses for * specialized particle behaviors. * * Key features: * - Automatic continuous emission with `autoEmit` * - Automatic burst intervals with `autoExplodeInterval` * - Forwards all emitter properties with `emitter*` prefix * - Lifecycle management - destroying particles destroys the emitter * * ```haxe * // Create auto-emitting smoke * var smoke = new Particles(); * smoke.autoEmit = true; * smoke.emitterInterval = 0.05; * smoke.emitterLifespan(0.5, 1.0); * smoke.emitterSpeedStart(50, 100); * smoke.emitterAlphaEnd(0); * scene.add(smoke); * * // Create periodic explosions * var explosions = new Particles(); * explosions.autoExplodeInterval = 2.0; // Every 2 seconds * explosions.autoExplodeQuantity = 50; * explosions.emitterSpeedStart(100, 300); * scene.add(explosions); * * // Use custom emitter * var custom = new Particles(new MyCustomEmitter()); * ``` * * @see ParticleEmitter The underlying emitter being managed * @see ParticleItem Individual particle data */ class Particles<T:ParticleEmitter> extends Visual { /** * The particle emitter managed by this visual. * * Can be accessed directly for advanced configuration or * to call methods like `explode()` and `emitParticle()`. * Most common properties are also exposed with `emitter*` prefix. */ @component public var emitter:T; /** * Creates a new Particles visual with an optional custom emitter. * * @param emitter Optional custom ParticleEmitter instance or subclass. * If not provided, creates a standard ParticleEmitter. */ public function new(?emitter:T) { super(); if (emitter != null) { this.emitter = emitter; } else { this.emitter = cast new ParticleEmitter(); } init(); } /** * Initializes the particles system. * * Sets up lifecycle binding so that destroying the emitter * also destroys this visual container. */ function init() { // When the emitter is destroyed, visual gets destroyed as well #if cs (cast emitter:ParticleEmitter) #else emitter #end.onDestroy(this, _ -> { destroy(); }); } /** * Whether to automatically emit particles continuously. * * When set to true, starts continuous emission using `emitterInterval`. * When set to false, stops emission (existing particles continue). * * Default: false * * ```haxe * particles.emitterInterval = 0.1; // Configure interval first * particles.autoEmit = true; // Start emitting * ``` */ public var autoEmit(default,set):Bool = false; function set_autoEmit(autoEmit:Bool):Bool { if (this.autoEmit != autoEmit) { this.autoEmit = autoEmit; if (autoEmit) { #if cs (cast emitter:ParticleEmitter) #else emitter #end.emitContinuously(emitterInterval); } else { #if cs (cast emitter:ParticleEmitter) #else emitter #end.stop(); } } return autoEmit; } /** * Timer cleanup function for auto-explode intervals. */ var clearExplodeInterval:Void->Void = null; /** * Interval in seconds between automatic burst emissions. * * When set to a positive value, triggers burst emissions of * `autoExplodeQuantity` particles at regular intervals. * Set to -1 to disable automatic bursts. * * Default: -1 (disabled) * * ```haxe * // Burst 30 particles every 1.5 seconds * particles.autoExplodeQuantity = 30; * particles.autoExplodeInterval = 1.5; * ``` */ public var autoExplodeInterval(default,set):Float = -1; function set_autoExplodeInterval(autoExplodeInterval:Float):Float { if (this.autoExplodeInterval != autoExplodeInterval) { this.autoExplodeInterval = autoExplodeInterval; computeAutoExplode(); } return autoExplodeInterval; } /** * Number of particles to emit in each automatic burst. * * Used with `autoExplodeInterval` to create periodic bursts. * Only takes effect when `autoExplodeInterval` is positive. * * Default: 64 * * @see autoExplodeInterval */ public var autoExplodeQuantity(default,set):Int = 64; function set_autoExplodeQuantity(autoExplodeQuantity:Int):Int { if (this.autoExplodeQuantity != autoExplodeQuantity) { this.autoExplodeQuantity = autoExplodeQuantity; computeAutoExplode(); } return autoExplodeQuantity; } /** * Updates the automatic explosion timer based on current settings. * * Clears any existing timer and creates a new one if both * interval and quantity are positive. */ function computeAutoExplode() { if (clearExplodeInterval != null) { clearExplodeInterval(); clearExplodeInterval = null; } if (autoExplodeInterval > 0 && autoExplodeQuantity > 0) { clearExplodeInterval = Timer.interval(this, autoExplodeInterval, doAutoExplode); } } /** * Executes an automatic burst emission. * * Called by the interval timer to emit the configured * quantity of particles. */ function doAutoExplode() { #if cs (cast emitter:ParticleEmitter) #else emitter #end.explode(autoExplodeQuantity); } /// Helpers forwarding to emitter // The following properties forward to the underlying emitter for convenience. // This allows configuring the emitter through the Particles instance without // directly accessing the emitter property. /** * Determines whether the emitter is currently paused. It is totally safe to directly toggle this. */ public var emitterPaused(get,set):Bool; inline function get_emitterPaused():Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.paused; inline function set_emitterPaused(paused:Bool):Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.paused = paused; /** * How often a particle is emitted, if currently emitting. * Can be modified at the middle of an emission safely; */ public var emitterInterval(get,set):Float; inline function get_emitterInterval():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.interval; inline function set_emitterInterval(interval:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.interval = interval; /** * How particles should be launched. If `CIRCLE` (default), particles will use `launchAngle` and `speed`. * Otherwise, particles will just use `velocityX` and `velocityY`. */ public var emitterLaunchMode(get,set):ParticlesLaunchMode; inline function get_emitterLaunchMode():ParticlesLaunchMode return #if cs (cast emitter:ParticleEmitter) #else emitter #end.launchMode; inline function set_emitterLaunchMode(launchMode:ParticlesLaunchMode):ParticlesLaunchMode return #if cs (cast emitter:ParticleEmitter) #else emitter #end.launchMode = launchMode; /** * Apply particle scale to underlying visual or not. */ public var emitterVisualScaleActive(get,set):Bool; inline function get_emitterVisualScaleActive():Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.visualScaleActive; inline function set_emitterVisualScaleActive(visualScaleActive:Bool):Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.visualScaleActive = visualScaleActive; /** * Keep the scale ratio of the particle. Uses the `scaleX` value for reference. */ public var emitterKeepScaleRatio(get,set):Bool; inline function get_emitterKeepScaleRatio():Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.keepScaleRatio; inline function set_emitterKeepScaleRatio(keepScaleRatio:Bool):Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.keepScaleRatio = keepScaleRatio; /** * Apply particle color to underlying visual or not. */ public var emitterVisualColorActive(get,set):Bool; inline function get_emitterVisualColorActive():Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.visualColorActive; inline function set_emitterVisualColorActive(visualColorActive:Bool):Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.visualColorActive = visualColorActive; /** * Apply particle alpha to underlying visual or not. */ public var emitterVisualAlphaActive(get,set):Bool; inline function get_emitterVisualAlphaActive():Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.visualAlphaActive; inline function set_emitterVisualAlphaActive(visualAlphaActive:Bool):Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.visualAlphaActive = visualAlphaActive; /** * Apply particle position (x & y) to underlying visual or not. */ public var emitterVisualPositionActive(get,set):Bool; inline function get_emitterVisualPositionActive():Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.visualPositionActive; inline function set_emitterVisualPositionActive(visualPositionActive:Bool):Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.visualPositionActive = visualPositionActive; /** * Apply particle angle to underlying visual rotation or not. */ public var emitterVisualRotationActive(get,set):Bool; inline function get_emitterVisualRotationActive():Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.visualRotationActive; inline function set_emitterVisualRotationActive(visualRotationActive:Bool):Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.visualRotationActive = visualRotationActive; /** * The width of the emission area. * If not defined (`-1`), will use visual's width bound to this `ParticleEmitter` object, if any */ public var emitterWidth(get,set):Float; inline function get_emitterWidth():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.width; inline function set_emitterWidth(width:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.width = width; /** * The height of the emission area. * If not defined (`-1`), will use visual's height bound to this `ParticleEmitter` object, if any */ public var emitterHeight(get,set):Float; inline function get_emitterHeight():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.height; inline function set_emitterHeight(height:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.height = height; /** * The x position of the emission, relative to particles parent (if any) */ public var emitterX(get,set):Float; inline function get_emitterX():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.x; inline function set_emitterX(x:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.x = x; /** * The y position of the emission, relative to particles parent (if any) */ public var emitterY(get,set):Float; inline function get_emitterY():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.y; inline function set_emitterY(y:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.y = y; /** * Enable or disable the velocity range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. Only used with `SQUARE`. */ public var emitterVelocityActive(get,set):Bool; inline function get_emitterVelocityActive():Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.velocityActive; inline function set_emitterVelocityActive(velocityActive:Bool):Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.velocityActive = velocityActive; /** * If you are using `acceleration`, you can use `maxVelocity` with it * to cap the speed automatically (very useful!). */ public var emitterMaxVelocityX(get,set):Float; inline function get_emitterMaxVelocityX():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.maxVelocityX; inline function set_emitterMaxVelocityX(maxVelocityX:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.maxVelocityX = maxVelocityX; /** * If you are using `acceleration`, you can use `maxVelocity` with it * to cap the speed automatically (very useful!). */ public var emitterMaxVelocityY(get,set):Float; inline function get_emitterMaxVelocityY():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.maxVelocityY; inline function set_emitterMaxVelocityY(maxVelocityY:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.maxVelocityY = maxVelocityY; /** * Sets the velocity range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. Only used with `SQUARE`. */ public var emitterVelocityStartMinX(get,set):Float; inline function get_emitterVelocityStartMinX():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.velocityStartMinX; inline function set_emitterVelocityStartMinX(velocityStartMinX:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.velocityStartMinX = velocityStartMinX; /** * Sets the velocity range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. Only used with `SQUARE`. */ public var emitterVelocityStartMinY(get,set):Float; inline function get_emitterVelocityStartMinY():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.velocityStartMinY; inline function set_emitterVelocityStartMinY(velocityStartMinY:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.velocityStartMinY = velocityStartMinY; /** * Sets the velocity range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. Only used with `SQUARE`. */ public var emitterVelocityStartMaxX(get,set):Float; inline function get_emitterVelocityStartMaxX():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.velocityStartMaxX; inline function set_emitterVelocityStartMaxX(velocityStartMaxX:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.velocityStartMaxX = velocityStartMaxX; /** * Sets the velocity range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. Only used with `SQUARE`. */ public var emitterVelocityStartMaxY(get,set):Float; inline function get_emitterVelocityStartMaxY():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.velocityStartMaxY; inline function set_emitterVelocityStartMaxY(velocityStartMaxY:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.velocityStartMaxY = velocityStartMaxY; /** * Sets the velocity range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. Only used with `SQUARE`. */ public var emitterVelocityEndMinX(get,set):Float; inline function get_emitterVelocityEndMinX():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.velocityEndMinX; inline function set_emitterVelocityEndMinX(velocityEndMinX:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.velocityEndMinX = velocityEndMinX; /** * Sets the velocity range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. Only used with `SQUARE`. */ public var emitterVelocityEndMinY(get,set):Float; inline function get_emitterVelocityEndMinY():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.velocityEndMinY; inline function set_emitterVelocityEndMinY(velocityEndMinY:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.velocityEndMinY = velocityEndMinY; /** * Sets the velocity range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. Only used with `SQUARE`. */ public var emitterVelocityEndMaxX(get,set):Float; inline function get_emitterVelocityEndMaxX():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.velocityEndMaxX; inline function set_emitterVelocityEndMaxX(velocityEndMaxX:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.velocityEndMaxX = velocityEndMaxX; /** * Sets the velocity range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. Only used with `SQUARE`. */ public var emitterVelocityEndMaxY(get,set):Float; inline function get_emitterVelocityEndMaxY():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.velocityEndMaxY; inline function set_emitterVelocityEndMaxY(velocityEndMaxY:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.velocityEndMaxY = velocityEndMaxY; /** * Set the speed range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. Only used with `CIRCLE`. */ public var emitterSpeedStartMin(get,set):Float; inline function get_emitterSpeedStartMin():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.speedStartMin; inline function set_emitterSpeedStartMin(speedStartMin:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.speedStartMin = speedStartMin; /** * Set the speed range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. Only used with `CIRCLE`. */ public var emitterSpeedStartMax(get,set):Float; inline function get_emitterSpeedStartMax():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.speedStartMax; inline function set_emitterSpeedStartMax(speedStartMax:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.speedStartMax = speedStartMax; /** * Set the speed range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. Only used with `CIRCLE`. */ public var emitterSpeedEndMin(get,set):Float; inline function get_emitterSpeedEndMin():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.speedEndMin; inline function set_emitterSpeedEndMin(speedEndMin:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.speedEndMin = speedEndMin; /** * Set the speed range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. Only used with `CIRCLE`. */ public var emitterSpeedEndMax(get,set):Float; inline function get_emitterSpeedEndMax():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.speedEndMax; inline function set_emitterSpeedEndMax(speedEndMax:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.speedEndMax = speedEndMax; /** * Use in conjunction with angularAcceleration for fluid spin speed control. */ public var emitterMaxAngularVelocity(get,set):Float; inline function get_emitterMaxAngularVelocity():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.maxAngularVelocity; inline function set_emitterMaxAngularVelocity(maxAngularVelocity:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.maxAngularVelocity = maxAngularVelocity; /** * Enable or disable the angular acceleration range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterAngularAccelerationActive(get,set):Bool; inline function get_emitterAngularAccelerationActive():Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angularAccelerationActive; inline function set_emitterAngularAccelerationActive(angularAccelerationActive:Bool):Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angularAccelerationActive = angularAccelerationActive; /** * Set the angular acceleration range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterAngularAccelerationStartMin(get,set):Float; inline function get_emitterAngularAccelerationStartMin():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angularAccelerationStartMin; inline function set_emitterAngularAccelerationStartMin(angularAccelerationStartMin:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angularAccelerationStartMin = angularAccelerationStartMin; /** * Set the angular acceleration range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterAngularAccelerationStartMax(get,set):Float; inline function get_emitterAngularAccelerationStartMax():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angularAccelerationStartMax; inline function set_emitterAngularAccelerationStartMax(angularAccelerationStartMax:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angularAccelerationStartMax = angularAccelerationStartMax; /** * Enable or disable the angular drag range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterAngularDragActive(get,set):Bool; inline function get_emitterAngularDragActive():Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angularDragActive; inline function set_emitterAngularDragActive(angularDragActive:Bool):Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angularDragActive = angularDragActive; /** * Set the angular drag range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterAngularDragStartMin(get,set):Float; inline function get_emitterAngularDragStartMin():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angularDragStartMin; inline function set_emitterAngularDragStartMin(angularDragStartMin:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angularDragStartMin = angularDragStartMin; /** * Set the angular drag range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterAngularDragStartMax(get,set):Float; inline function get_emitterAngularDragStartMax():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angularDragStartMax; inline function set_emitterAngularDragStartMax(angularDragStartMax:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angularDragStartMax = angularDragStartMax; /** * Enable or disable the angular velocity range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterAngularVelocityActive(get,set):Bool; inline function get_emitterAngularVelocityActive():Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angularVelocityActive; inline function set_emitterAngularVelocityActive(angularVelocityActive:Bool):Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angularVelocityActive = angularVelocityActive; /** * The angular velocity range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterAngularVelocityStartMin(get,set):Float; inline function get_emitterAngularVelocityStartMin():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angularVelocityStartMin; inline function set_emitterAngularVelocityStartMin(angularVelocityStartMin:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angularVelocityStartMin = angularVelocityStartMin; /** * The angular velocity range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterAngularVelocityStartMax(get,set):Float; inline function get_emitterAngularVelocityStartMax():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angularVelocityStartMax; inline function set_emitterAngularVelocityStartMax(angularVelocityStartMax:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angularVelocityStartMax = angularVelocityStartMax; /** * The angular velocity range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterAngularVelocityEndMin(get,set):Float; inline function get_emitterAngularVelocityEndMin():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angularVelocityEndMin; inline function set_emitterAngularVelocityEndMin(angularVelocityEndMin:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angularVelocityEndMin = angularVelocityEndMin; /** * The angular velocity range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterAngularVelocityEndMax(get,set):Float; inline function get_emitterAngularVelocityEndMax():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angularVelocityEndMax; inline function set_emitterAngularVelocityEndMax(angularVelocityEndMax:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angularVelocityEndMax = angularVelocityEndMax; /** * Enable or disable the angle range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. * `angleEndMin` and `angleEndMax` are ignored unless `ignoreAngularVelocity` is set to `true`. */ public var emitterAngleActive(get,set):Bool; inline function get_emitterAngleActive():Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angleActive; inline function set_emitterAngleActive(angleActive:Bool):Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angleActive = angleActive; /** * The angle range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. * `angleEndMin` and `angleEndMax` are ignored unless `ignoreAngularVelocity` is set to `true`. */ public var emitterAngleStartMin(get,set):Float; inline function get_emitterAngleStartMin():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angleStartMin; inline function set_emitterAngleStartMin(angleStartMin:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angleStartMin = angleStartMin; /** * The angle range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. * `angleEndMin` and `angleEndMax` are ignored unless `ignoreAngularVelocity` is set to `true`. */ public var emitterAngleStartMax(get,set):Float; inline function get_emitterAngleStartMax():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angleStartMax; inline function set_emitterAngleStartMax(angleStartMax:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angleStartMax = angleStartMax; /** * The angle range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. * `angleEndMin` and `angleEndMax` are ignored unless `ignoreAngularVelocity` is set to `true`. */ public var emitterAngleEndMin(get,set):Float; inline function get_emitterAngleEndMin():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angleEndMin; inline function set_emitterAngleEndMin(angleEndMin:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angleEndMin = angleEndMin; /** * The angle range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. * `angleEndMin` and `angleEndMax` are ignored unless `ignoreAngularVelocity` is set to `true`. */ public var emitterAngleEndMax(get,set):Float; inline function get_emitterAngleEndMax():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angleEndMax; inline function set_emitterAngleEndMax(angleEndMax:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.angleEndMax = angleEndMax; /** * Set this if you want to specify the beginning and ending value of angle, * instead of using `angularVelocity` (or `angularAcceleration`). */ public var emitterIgnoreAngularVelocity(get,set):Bool; inline function get_emitterIgnoreAngularVelocity():Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.ignoreAngularVelocity; inline function set_emitterIgnoreAngularVelocity(ignoreAngularVelocity:Bool):Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.ignoreAngularVelocity = ignoreAngularVelocity; /** * Enable or disable the angle range at which particles will be launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. * Ignored unless `launchMode` is set to `CIRCLE`. */ public var emitterLaunchAngleActive(get,set):Bool; inline function get_emitterLaunchAngleActive():Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.launchAngleActive; inline function set_emitterLaunchAngleActive(launchAngleActive:Bool):Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.launchAngleActive = launchAngleActive; /** * The angle range at which particles will be launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. * Ignored unless `launchMode` is set to `CIRCLE`. */ public var emitterLaunchAngleMin(get,set):Float; inline function get_emitterLaunchAngleMin():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.launchAngleMin; inline function set_emitterLaunchAngleMin(launchAngleMin:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.launchAngleMin = launchAngleMin; /** * The angle range at which particles will be launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. * Ignored unless `launchMode` is set to `CIRCLE`. */ public var emitterLaunchAngleMax(get,set):Float; inline function get_emitterLaunchAngleMax():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.launchAngleMax; inline function set_emitterLaunchAngleMax(launchAngleMax:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.launchAngleMax = launchAngleMax; /** * Enable or disable the life, or duration, range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterLifespanActive(get,set):Bool; inline function get_emitterLifespanActive():Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.lifespanActive; inline function set_emitterLifespanActive(lifespanActive:Bool):Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.lifespanActive = lifespanActive; /** * The life, or duration, range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterLifespanMin(get,set):Float; inline function get_emitterLifespanMin():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.lifespanMin; inline function set_emitterLifespanMin(lifespanMin:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.lifespanMin = lifespanMin; /** * The life, or duration, range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterLifespanMax(get,set):Float; inline function get_emitterLifespanMax():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.lifespanMax; inline function set_emitterLifespanMax(lifespanMax:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.lifespanMax = lifespanMax; /** * Enable or disable `scale` range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterScaleActive(get,set):Bool; inline function get_emitterScaleActive():Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.scaleActive; inline function set_emitterScaleActive(scaleActive:Bool):Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.scaleActive = scaleActive; /** * Sets `scale` range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterScaleStartMinX(get,set):Float; inline function get_emitterScaleStartMinX():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.scaleStartMinX; inline function set_emitterScaleStartMinX(scaleStartMinX:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.scaleStartMinX = scaleStartMinX; /** * Sets `scale` range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterScaleStartMinY(get,set):Float; inline function get_emitterScaleStartMinY():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.scaleStartMinY; inline function set_emitterScaleStartMinY(scaleStartMinY:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.scaleStartMinY = scaleStartMinY; /** * Sets `scale` range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterScaleStartMaxX(get,set):Float; inline function get_emitterScaleStartMaxX():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.scaleStartMaxX; inline function set_emitterScaleStartMaxX(scaleStartMaxX:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.scaleStartMaxX = scaleStartMaxX; /** * Sets `scale` range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterScaleStartMaxY(get,set):Float; inline function get_emitterScaleStartMaxY():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.scaleStartMaxY; inline function set_emitterScaleStartMaxY(scaleStartMaxY:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.scaleStartMaxY = scaleStartMaxY; /** * Sets `scale` range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterScaleEndMinX(get,set):Float; inline function get_emitterScaleEndMinX():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.scaleEndMinX; inline function set_emitterScaleEndMinX(scaleEndMinX:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.scaleEndMinX = scaleEndMinX; /** * Sets `scale` range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterScaleEndMinY(get,set):Float; inline function get_emitterScaleEndMinY():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.scaleEndMinY; inline function set_emitterScaleEndMinY(scaleEndMinY:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.scaleEndMinY = scaleEndMinY; /** * Sets `scale` range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterScaleEndMaxX(get,set):Float; inline function get_emitterScaleEndMaxX():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.scaleEndMaxX; inline function set_emitterScaleEndMaxX(scaleEndMaxX:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.scaleEndMaxX = scaleEndMaxX; /** * Sets `scale` range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterScaleEndMaxY(get,set):Float; inline function get_emitterScaleEndMaxY():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.scaleEndMaxY; inline function set_emitterScaleEndMaxY(scaleEndMaxY:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.scaleEndMaxY = scaleEndMaxY; /** * Enable or disable `alpha` range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterAlphaActive(get,set):Bool; inline function get_emitterAlphaActive():Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.alphaActive; inline function set_emitterAlphaActive(alphaActive:Bool):Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.alphaActive = alphaActive; /** * Sets `alpha` range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterAlphaStartMin(get,set):Float; inline function get_emitterAlphaStartMin():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.alphaStartMin; inline function set_emitterAlphaStartMin(alphaStartMin:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.alphaStartMin = alphaStartMin; /** * Sets `alpha` range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterAlphaStartMax(get,set):Float; inline function get_emitterAlphaStartMax():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.alphaStartMax; inline function set_emitterAlphaStartMax(alphaStartMax:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.alphaStartMax = alphaStartMax; /** * Sets `alpha` range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterAlphaEndMin(get,set):Float; inline function get_emitterAlphaEndMin():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.alphaEndMin; inline function set_emitterAlphaEndMin(alphaEndMin:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.alphaEndMin = alphaEndMin; /** * Sets `alpha` range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterAlphaEndMax(get,set):Float; inline function get_emitterAlphaEndMax():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.alphaEndMax; inline function set_emitterAlphaEndMax(alphaEndMax:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.alphaEndMax = alphaEndMax; /** * Enable or disable `color` range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterColorActive(get,set):Bool; inline function get_emitterColorActive():Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.colorActive; inline function set_emitterColorActive(colorActive:Bool):Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.colorActive = colorActive; /** * Sets `color` range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterColorStartMin(get,set):Color; inline function get_emitterColorStartMin():Color return #if cs (cast emitter:ParticleEmitter) #else emitter #end.colorStartMin; inline function set_emitterColorStartMin(colorStartMin:Color):Color return #if cs (cast emitter:ParticleEmitter) #else emitter #end.colorStartMin = colorStartMin; /** * Sets `color` range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterColorStartMax(get,set):Color; inline function get_emitterColorStartMax():Color return #if cs (cast emitter:ParticleEmitter) #else emitter #end.colorStartMax; inline function set_emitterColorStartMax(colorStartMax:Color):Color return #if cs (cast emitter:ParticleEmitter) #else emitter #end.colorStartMax = colorStartMax; /** * Sets `color` range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterColorEndMin(get,set):Color; inline function get_emitterColorEndMin():Color return #if cs (cast emitter:ParticleEmitter) #else emitter #end.colorEndMin; inline function set_emitterColorEndMin(colorEndMin:Color):Color return #if cs (cast emitter:ParticleEmitter) #else emitter #end.colorEndMin = colorEndMin; /** * Sets `color` range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterColorEndMax(get,set):Color; inline function get_emitterColorEndMax():Color return #if cs (cast emitter:ParticleEmitter) #else emitter #end.colorEndMax; inline function set_emitterColorEndMax(colorEndMax:Color):Color return #if cs (cast emitter:ParticleEmitter) #else emitter #end.colorEndMax = colorEndMax; /** * Enable or disable X and Y drag component of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterDragActive(get,set):Bool; inline function get_emitterDragActive():Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.dragActive; inline function set_emitterDragActive(dragActive:Bool):Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.dragActive = dragActive; /** * Sets X and Y drag component of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterDragStartMinX(get,set):Float; inline function get_emitterDragStartMinX():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.dragStartMinX; inline function set_emitterDragStartMinX(dragStartMinX:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.dragStartMinX = dragStartMinX; /** * Sets X and Y drag component of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterDragStartMinY(get,set):Float; inline function get_emitterDragStartMinY():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.dragStartMinY; inline function set_emitterDragStartMinY(dragStartMinY:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.dragStartMinY = dragStartMinY; /** * Sets X and Y drag component of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterDragStartMaxX(get,set):Float; inline function get_emitterDragStartMaxX():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.dragStartMaxX; inline function set_emitterDragStartMaxX(dragStartMaxX:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.dragStartMaxX = dragStartMaxX; /** * Sets X and Y drag component of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterDragStartMaxY(get,set):Float; inline function get_emitterDragStartMaxY():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.dragStartMaxY; inline function set_emitterDragStartMaxY(dragStartMaxY:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.dragStartMaxY = dragStartMaxY; /** * Sets X and Y drag component of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterDragEndMinX(get,set):Float; inline function get_emitterDragEndMinX():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.dragEndMinX; inline function set_emitterDragEndMinX(dragEndMinX:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.dragEndMinX = dragEndMinX; /** * Sets X and Y drag component of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterDragEndMinY(get,set):Float; inline function get_emitterDragEndMinY():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.dragEndMinY; inline function set_emitterDragEndMinY(dragEndMinY:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.dragEndMinY = dragEndMinY; /** * Sets X and Y drag component of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterDragEndMaxX(get,set):Float; inline function get_emitterDragEndMaxX():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.dragEndMaxX; inline function set_emitterDragEndMaxX(dragEndMaxX:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.dragEndMaxX = dragEndMaxX; /** * Sets X and Y drag component of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ public var emitterDragEndMaxY(get,set):Float; inline function get_emitterDragEndMaxY():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.dragEndMaxY; inline function set_emitterDragEndMaxY(dragEndMaxY:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.dragEndMaxY = dragEndMaxY; /** * Enable or disable the `acceleration` range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. * Set acceleration y-values to give particles gravity. */ public var emitterAccelerationActive(get,set):Bool; inline function get_emitterAccelerationActive():Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.accelerationActive; inline function set_emitterAccelerationActive(accelerationActive:Bool):Bool return #if cs (cast emitter:ParticleEmitter) #else emitter #end.accelerationActive = accelerationActive; /** * Sets the `acceleration` range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. * Set acceleration y-values to give particles gravity. */ public var emitterAccelerationStartMinX(get,set):Float; inline function get_emitterAccelerationStartMinX():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.accelerationStartMinX; inline function set_emitterAccelerationStartMinX(accelerationStartMinX:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.accelerationStartMinX = accelerationStartMinX; /** * Sets the `acceleration` range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. * Set acceleration y-values to give particles gravity. */ public var emitterAccelerationStartMinY(get,set):Float; inline function get_emitterAccelerationStartMinY():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.accelerationStartMinY; inline function set_emitterAccelerationStartMinY(accelerationStartMinY:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.accelerationStartMinY = accelerationStartMinY; /** * Sets the `acceleration` range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. * Set acceleration y-values to give particles gravity. */ public var emitterAccelerationStartMaxX(get,set):Float; inline function get_emitterAccelerationStartMaxX():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.accelerationStartMaxX; inline function set_emitterAccelerationStartMaxX(accelerationStartMaxX:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.accelerationStartMaxX = accelerationStartMaxX; /** * Sets the `acceleration` range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. * Set acceleration y-values to give particles gravity. */ public var emitterAccelerationStartMaxY(get,set):Float; inline function get_emitterAccelerationStartMaxY():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.accelerationStartMaxY; inline function set_emitterAccelerationStartMaxY(accelerationStartMaxY:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.accelerationStartMaxY = accelerationStartMaxY; /** * Sets the `acceleration` range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. * Set acceleration y-values to give particles gravity. */ public var emitterAccelerationEndMinX(get,set):Float; inline function get_emitterAccelerationEndMinX():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.accelerationEndMinX; inline function set_emitterAccelerationEndMinX(accelerationEndMinX:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.accelerationEndMinX = accelerationEndMinX; /** * Sets the `acceleration` range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. * Set acceleration y-values to give particles gravity. */ public var emitterAccelerationEndMinY(get,set):Float; inline function get_emitterAccelerationEndMinY():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.accelerationEndMinY; inline function set_emitterAccelerationEndMinY(accelerationEndMinY:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.accelerationEndMinY = accelerationEndMinY; /** * Sets the `acceleration` range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. * Set acceleration y-values to give particles gravity. */ public var emitterAccelerationEndMaxX(get,set):Float; inline function get_emitterAccelerationEndMaxX():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.accelerationEndMaxX; inline function set_emitterAccelerationEndMaxX(accelerationEndMaxX:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.accelerationEndMaxX = accelerationEndMaxX; /** * Sets the `acceleration` range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. * Set acceleration y-values to give particles gravity. */ public var emitterAccelerationEndMaxY(get,set):Float; inline function get_emitterAccelerationEndMaxY():Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.accelerationEndMaxY; inline function set_emitterAccelerationEndMaxY(accelerationEndMaxY:Float):Float return #if cs (cast emitter:ParticleEmitter) #else emitter #end.accelerationEndMaxY = accelerationEndMaxY; /// Configuration shorthands /** * The width and height of the emission area. * If not defined (`-1`), will use visual's width and height bound to this `ParticleEmitter` object, if any */ inline public function emitterSize(width:Float, height:Float):Void { #if cs (cast emitter:ParticleEmitter) #else emitter #end.size(width, height); } /** * The x and y position of the emission, relative to particles parent (if any) */ inline public function emitterPos(x:Float, y:Float):Void { #if cs (cast emitter:ParticleEmitter) #else emitter #end.pos(x, y); } /** * If you are using `acceleration`, you can use `maxVelocity` with it * to cap the speed automatically (very useful!). */ inline public function emitterMaxVelocity(maxVelocityX:Float, maxVelocityY:Float):Void { #if cs (cast emitter:ParticleEmitter) #else emitter #end.maxVelocity(maxVelocityX, maxVelocityY); } /** * Sets the velocity starting range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. Only used with `SQUARE`. */ inline public function emitterVelocityStart(startMinX:Float, startMinY:Float, ?startMaxX:Float, ?startMaxY:Float):Void { #if cs (cast emitter:ParticleEmitter) #else emitter #end.velocityStart(startMinX, startMinY, startMaxX, startMaxY); } /** * Sets the velocity ending range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. Only used with `SQUARE`. */ inline public function emitterVelocityEnd(endMinX:Float, endMinY:Float, ?endMaxX:Float, ?endMaxY:Float):Void { #if cs (cast emitter:ParticleEmitter) #else emitter #end.velocityEnd(endMinX, endMinY, endMaxX, endMaxY); } /** * Set the speed starting range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. Only used with `CIRCLE`. */ inline public function emitterSpeedStart(startMin:Float, ?startMax:Float):Void { #if cs (cast emitter:ParticleEmitter) #else emitter #end.speedStart(startMin, startMax); } /** * Set the speed ending range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. Only used with `CIRCLE`. */ inline public function emitterSpeedEnd(endMin:Float, ?endMax:Float):Void { #if cs (cast emitter:ParticleEmitter) #else emitter #end.speedEnd(endMin, endMax); } /** * Set the angular acceleration range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ inline public function emitterAngularAcceleration(startMin:Float, startMax:Float):Void { #if cs (cast emitter:ParticleEmitter) #else emitter #end.angularAcceleration(startMin, startMax); } /** * Set the angular drag range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ inline public function emitterAngularDrag(startMin:Float, startMax:Float):Void { #if cs (cast emitter:ParticleEmitter) #else emitter #end.angularDrag(startMin, startMax); } /** * The angular velocity starting range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ inline public function emitterAngularVelocityStart(startMin:Float, ?startMax:Float):Void { #if cs (cast emitter:ParticleEmitter) #else emitter #end.angularVelocityStart(startMin, startMax); } /** * The angular velocity ending range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ inline public function emitterAngularVelocityEnd(endMin:Float, ?endMax:Float):Void { #if cs (cast emitter:ParticleEmitter) #else emitter #end.angularVelocityEnd(endMin, endMax); } /** * The angle starting range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. * `angleEndMin` and `angleEndMax` are ignored unless `ignoreAngularVelocity` is set to `true`. */ inline public function emitterAngleStart(startMin:Float, ?startMax:Float):Void { #if cs (cast emitter:ParticleEmitter) #else emitter #end.angleStart(startMin, startMax); } /** * The angle ending range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. * `angleEndMin` and `angleEndMax` are ignored unless `ignoreAngularVelocity` is set to `true`. */ inline public function emitterAngleEnd(endMin:Float, ?endMax:Float):Void { #if cs (cast emitter:ParticleEmitter) #else emitter #end.angleEnd(endMin, endMax); } /** * The angle range at which particles will be launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. * Ignored unless `launchMode` is set to `CIRCLE`. */ inline public function emitterLaunchAngle(min:Float, max:Float):Void { #if cs (cast emitter:ParticleEmitter) #else emitter #end.launchAngle(min, max); } /** * The life, or duration, range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ inline public function emitterLifespan(min:Float, max:Float):Void { #if cs (cast emitter:ParticleEmitter) #else emitter #end.lifespan(min, max); } /** * Sets `scale` starting range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ inline public function emitterScaleStart(startMinX:Float, startMinY:Float, ?startMaxX:Float, ?startMaxY:Float):Void { #if cs (cast emitter:ParticleEmitter) #else emitter #end.scaleStart(startMinX, startMinY, startMaxX, startMaxY); } /** * Sets `scale` ending range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ inline public function emitterScaleEnd(endMinX:Float, endMinY:Float, ?endMaxX:Float, ?endMaxY:Float):Void { #if cs (cast emitter:ParticleEmitter) #else emitter #end.scaleEnd(endMinX, endMinY, endMaxX, endMaxY); } /** * Sets `acceleration` starting range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ inline public function emitterAccelerationStart(startMinX:Float, startMinY:Float, ?startMaxX:Float, ?startMaxY:Float):Void { #if cs (cast emitter:ParticleEmitter) #else emitter #end.accelerationStart(startMinX, startMinY, startMaxX, startMaxY); } /** * Sets `acceleration` ending range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ inline public function emitterAccelerationEnd(endMinX:Float, endMinY:Float, ?endMaxX:Float, ?endMaxY:Float):Void { #if cs (cast emitter:ParticleEmitter) #else emitter #end.accelerationEnd(endMinX, endMinY, endMaxX, endMaxY); } /** * Sets `drag` starting range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ inline public function emitterDragStart(startMinX:Float, startMinY:Float, ?startMaxX:Float, ?startMaxY:Float):Void { #if cs (cast emitter:ParticleEmitter) #else emitter #end.dragStart(startMinX, startMinY, startMaxX, startMaxY); } /** * Sets `drag` ending range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ inline public function emitterdragEnd(endMinX:Float, endMinY:Float, ?endMaxX:Float, ?endMaxY:Float):Void { #if cs (cast emitter:ParticleEmitter) #else emitter #end.dragEnd(endMinX, endMinY, endMaxX, endMaxY); } /** * Sets `color` starting range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ inline public function emitterColorStart(startMin:Color, ?startMax:Color):Void { #if cs (cast emitter:ParticleEmitter) #else emitter #end.colorStart(startMin, startMax); } /** * Sets `color` ending range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ inline public function emitterColorEnd(endMin:Color, ?endMax:Color):Void { #if cs (cast emitter:ParticleEmitter) #else emitter #end.colorEnd(endMin, endMax); } /** * Sets `alpha` starting range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ inline public function emitterAlphaStart(startMin:Float, ?startMax:Float):Void { #if cs (cast emitter:ParticleEmitter) #else emitter #end.alphaStart(startMin, startMax); } /** * Sets `alpha` ending range of particles launched from this #if cs (cast emitter:ParticleEmitter) #else emitter #end. */ inline public function emitterAlphaEnd(endMin:Float, ?endMax:Float):Void { #if cs (cast emitter:ParticleEmitter) #else emitter #end.alphaEnd(endMin, endMax); } // Note: The emitter* properties and methods above provide convenient access to // the underlying ParticleEmitter configuration. They forward directly to the // emitter instance, allowing you to configure particles without accessing // the emitter property directly. For properties not exposed here, access // the emitter directly: particles.emitter.someProperty }
412
0.840746
1
0.840746
game-dev
MEDIA
0.820888
game-dev
0.814626
1
0.814626
xfw5/Fear-SDK-1.08
10,514
Game/ObjectDLL/AINavMeshGenCarver.cpp
// ----------------------------------------------------------------------- // // // MODULE : AINavMeshGenCarver.cpp // // PURPOSE : AI NavMesh generator Carver class implementation. // // CREATED : 11/02 // // (c) 2002 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #include "Stdafx.h" #include "AINavMeshGenCarver.h" #include "AINavMeshGenPoly.h" #include "AINavMeshGen.h" #include "AINavMeshGenMacros.h" //---------------------------------------------------------------------------- // // ROUTINE: CAINavMeshGenCarver::Con/destructor // // PURPOSE: Con/destructor // //---------------------------------------------------------------------------- CAINavMeshGenCarver::CAINavMeshGenCarver( IGameWorldPacker::PFNERRORCALLBACK pfnErrorCallback ) : m_pfnErrorCallback(pfnErrorCallback) { m_eNMGCarverID = kNMGCarver_Invalid; m_fNMGCarverHeight = 0.f; m_aabbNMGCarverBounds.InitAABB(); } CAINavMeshGenCarver::~CAINavMeshGenCarver() { m_lstNMGCarverVerts.resize( 0 ); m_aabbNMGCarverBounds.InitAABB(); } //---------------------------------------------------------------------------- // // ROUTINE: CAINavMeshGenCarver::InitNMGCarver // // PURPOSE: Initialize poly. // //---------------------------------------------------------------------------- void CAINavMeshGenCarver::InitNMGCarver() { // Calculate the axis-aligned bounding box. LTVector vVert; VECTOR_LIST::iterator itVert; for( itVert = m_lstNMGCarverVerts.begin(); itVert != m_lstNMGCarverVerts.end(); ++itVert ) { vVert = *itVert; m_aabbNMGCarverBounds.GrowAABB( vVert ); } m_aabbNMGCarverBounds.vMin.y = vVert.y - m_fNMGCarverHeight; } //---------------------------------------------------------------------------- // // ROUTINE: CAINavMeshGenCarver::AddNMGCarverVert // // PURPOSE: Add a vert to the Carver. // //---------------------------------------------------------------------------- void CAINavMeshGenCarver::AddNMGCarverVert( const LTVector& vVert ) { m_lstNMGCarverVerts.push_back( vVert ); } //---------------------------------------------------------------------------- // // ROUTINE: CAINavMeshGenCarver::CarveNMGPoly // // PURPOSE: Carve hole in poly where Carver lies. // //---------------------------------------------------------------------------- bool CAINavMeshGenCarver::CarveNMGPoly( CAINavMeshGenPoly* pPoly, AINAVMESHGEN_POLY_LIST* plstNewPolys, AINAVMESHGEN_POLY_LIST* plstDeletePolys, AINAVMESHGEN_POLY_LIST* plstCarvedPolys ) { // Sanity check. if( !pPoly ) { return false; } // PrintCarverVerts(); // pPoly->PrintActualVerts(); SAINAVMESHGEN_PLANE* plnNMGPoly = pPoly->GetNMGPlane(); VECTOR_LIST lstCarverIntersects; LTVector vCenter = LTVector( 0.f, 0.f, 0.f ); LTVector v0, v1, vIntersect; VECTOR_LIST::iterator itVert; for( itVert = m_lstNMGCarverVerts.begin(); itVert != m_lstNMGCarverVerts.end(); ++itVert ) { v0 = *itVert; v1 = v0; v1.y -= m_fNMGCarverHeight; if( plnNMGPoly->RayIntersectNMGPlane( v0, v1, &vIntersect ) ) { lstCarverIntersects.push_back( vIntersect ); vCenter += v0; } } if( lstCarverIntersects.size() < 3 ) { return false; } vCenter /= (float)lstCarverIntersects.size(); lstCarverIntersects.push_back( *( lstCarverIntersects.begin() ) ); // Find the optimal first carving plane. This is the plane // which leaves the polygon with the most uncut space. SelectFirstCarvingPlane( pPoly, &lstCarverIntersects ); // Get poly normal by pool ID. LTVector vNMGPolyN; CAINavMeshGen::GetAINavMeshGen()->GetActualNormalFromPool( pPoly->GetNMGNormalID(), &vNMGPolyN ); CAINavMeshGenPoly* pPolyA; CAINavMeshGenPoly* pPolyB; LTVector vEdge, vEdgeN, vPolyDir; SAINAVMESHGEN_POLY_INTERSECT pintersect; VECTOR_LIST::iterator itIntersect; // If the entire poly is on the outside of one of the edges of the // carver, then the carver does not carve the polygon. for( itIntersect = lstCarverIntersects.begin(); itIntersect != lstCarverIntersects.end() - 1; ++itIntersect ) { pintersect.v0 = *itIntersect; pintersect.v1 = *( itIntersect + 1 ); if( pPoly->IsPolyOnOutsideOfRay( &pintersect, vCenter ) ) { return false; } } // Attempt to carve the poly by each edge of the carver. uint32 cSplits = 0; uint32 cInsideEdge = 0; bool bDiscardCarvedPoly = true; for( itIntersect = lstCarverIntersects.begin(); itIntersect != lstCarverIntersects.end() - 1; ++itIntersect ) { bDiscardCarvedPoly = true; pintersect.v0 = *itIntersect; pintersect.v1 = *( itIntersect + 1 ); // Ignore polys that are entirely on one side of the carver's edge. if( pPoly->IsPolyOnOneSideOfRay( &pintersect ) ) { if( pPoly->IsPolyOnOutsideOfRay( &pintersect, vCenter ) ) { // Whole poly is outside of a cutting plane. We don't need to test others as // the carver is convex. bDiscardCarvedPoly = false; break; } else { ++cInsideEdge; } continue; } if( pPoly->CoplanarRayIntersectPoly( &pintersect ) ) { pPolyA = NULL; pPolyB = NULL; pPoly->SplitPoly( &pintersect, pPolyA, pPolyB ); // Bail if split created any degenerate polygons. // This can happen if the ray is coincident with one of // the original poly edges. if( ( pPolyA->GetNumNMGVerts() < 3 ) || ( pPolyB->GetNumNMGVerts() < 3 ) ) { continue; } ++cSplits; // pPoly->PrintActualVerts(); // pPolyA->PrintActualVerts(); // pPolyB->PrintActualVerts(); if( pPolyA && pPolyB ) { if( plstDeletePolys ) { plstDeletePolys->push_back( pPoly ); } vEdge = pintersect.v1 - pintersect.v0; vEdge.Normalize(); // Calculate the edge's normal. vEdgeN = vNMGPolyN.Cross( vEdge ); vPolyDir = pintersect.v1 - pPolyA->GetNMGPolyCenter(); vPolyDir.Normalize(); if( vPolyDir.Dot( vEdgeN ) < 0.f ) { if( plstNewPolys ) { plstNewPolys->push_back( pPolyA ); } pPoly = pPolyB; } else { if( plstNewPolys ) { plstNewPolys->push_back( pPolyB ); } pPoly = pPolyA; } } } } // Nothing was carved. if( ( cSplits == 0 ) && ( cInsideEdge != lstCarverIntersects.size() - 1 ) ) { return false; } // Add the poly that fits inside the carver. // The bCarve variable keeps track of whether // the last remaining polygon was inside of the carver, // or on the outside of the last carving plane. if( bDiscardCarvedPoly ) { if( plstCarvedPolys ) { plstCarvedPolys->push_back( pPoly ); } } else { if( plstNewPolys ) { if( pPoly->GetNMGPolyID() == kNMGPoly_Invalid ) { plstNewPolys->push_back( pPoly ); } } } return true; } //---------------------------------------------------------------------------- // // ROUTINE: CAINavMeshGenCarver::SelectFirstCarvingPlane // // PURPOSE: Find the carving plane which leaves the polygon with // most uncut space. Reorder the list of planes to start // with this optimal plane. // //---------------------------------------------------------------------------- void CAINavMeshGenCarver::SelectFirstCarvingPlane( CAINavMeshGenPoly* pPoly, VECTOR_LIST* plstCarverIntersects ) { float fDiff = 0.0f; float fDiffSqr = 0.0f; // Determine which side of the carver's AABB leaves the most // uncut space in the poly's AABB. float fMaxDiff = pPoly->GetAABB()->vMax.x - m_aabbNMGCarverBounds.vMax.x; ENUM_SIDE eSide = kRight; fDiff = m_aabbNMGCarverBounds.vMin.x - pPoly->GetAABB()->vMin.x; if( fDiff > fMaxDiff ) { fMaxDiff = fDiff; eSide = kLeft; } fDiff = pPoly->GetAABB()->vMax.z - m_aabbNMGCarverBounds.vMax.z; if( fDiff > fMaxDiff ) { fMaxDiff = fDiff; eSide = kBottom; } fDiff = m_aabbNMGCarverBounds.vMin.z - pPoly->GetAABB()->vMin.z; if( fDiff > fMaxDiff ) { fMaxDiff = fDiff; eSide = kTop; } // Find the carving plane that is closest to the optimal side // of the carver's AABB. LTVector v0, v1, vMin; float fMinDiffSqr = FLT_MAX; VECTOR_LIST::iterator itPlane = plstCarverIntersects->end(); VECTOR_LIST::iterator itMin = plstCarverIntersects->end(); for( itPlane = plstCarverIntersects->begin(); itPlane != plstCarverIntersects->end() - 1; ++itPlane ) { v0 = *itPlane; v1 = *( itPlane + 1 ); switch( eSide ) { case kRight: fDiff = ( v0.x - m_aabbNMGCarverBounds.vMax.x ) + ( v1.x - m_aabbNMGCarverBounds.vMax.x ); fDiffSqr = fDiff * fDiff; break; case kLeft: fDiff = ( m_aabbNMGCarverBounds.vMin.x - v0.x ) + ( m_aabbNMGCarverBounds.vMin.x - v1.x ); fDiffSqr = fDiff * fDiff; break; case kBottom: fDiff = ( v0.z - m_aabbNMGCarverBounds.vMax.z ) + ( v1.z - m_aabbNMGCarverBounds.vMax.z ); fDiffSqr = fDiff * fDiff; break; case kTop: fDiff = ( m_aabbNMGCarverBounds.vMin.z - v0.z ) + ( m_aabbNMGCarverBounds.vMin.z - v1.z ); fDiffSqr = fDiff * fDiff; break; } if( fDiffSqr < fMinDiffSqr ) { fMinDiffSqr = fDiffSqr; itMin = itPlane; } } // This shouldn't happen unless something went invalid. if (plstCarverIntersects->end() == itMin) { NAVMESH_ERROR("CAINavMeshGenCarver::SelectFirstCarvingPlane : No valid carving plane found."); return; } // Reorder the list of plane verts to start with the optimal plane. vMin = *itMin; plstCarverIntersects->pop_back(); itPlane = plstCarverIntersects->begin(); while( *itPlane != vMin ) { plstCarverIntersects->push_back( *itPlane ); itPlane = plstCarverIntersects->erase( itPlane ); } plstCarverIntersects->push_back( *( plstCarverIntersects->begin() ) ); } //---------------------------------------------------------------------------- // // ROUTINE: CAINavMeshGenCarver::PrintCarverVerts // // PURPOSE: Print vertex coordinates for debugging. // //---------------------------------------------------------------------------- void CAINavMeshGenCarver::PrintCarverVerts() { TRACE( "Carver: %d\n", m_eNMGCarverID ); LTVector vVert; VECTOR_LIST::iterator itVert; for( itVert = m_lstNMGCarverVerts.begin(); itVert != m_lstNMGCarverVerts.end(); ++itVert ) { vVert = *itVert; TRACE( " %.2f %.2f %.2f\n", vVert.x, vVert.y, vVert.z ); } } //----------------------------------------------------------------------------
412
0.701107
1
0.701107
game-dev
MEDIA
0.69638
game-dev
0.988197
1
0.988197
layabox/LayaAir
13,896
src/layaAir/laya/Physics3D/PhysX/Collider/pxCollider.ts
import { Sprite3D } from "../../../d3/core/Sprite3D"; import { Transform3D } from "../../../d3/core/Transform3D"; import { PhysicsColliderComponent, PhysicsCombineMode } from "../../../d3/physics/PhysicsColliderComponent"; import { Physics3DUtils } from "../../../d3/utils/Physics3DUtils"; import { Event } from "../../../events/Event"; import { Quaternion } from "../../../maths/Quaternion"; import { Vector3 } from "../../../maths/Vector3"; import { NotImplementedError } from "../../../utils/Error"; import { ICollider } from "../../interface/ICollider"; import { pxColliderShape } from "../Shape/pxColliderShape"; import { pxCompoundColliderShape } from "../Shape/pxCompoundColliderShape"; import type { pxPhysicsManager } from "../pxPhysicsManager"; import { partFlag } from "../pxStatics"; /** * @en Enumeration of collider types. * @zh 碰撞器类型枚举。 */ export enum pxColliderType { RigidbodyCollider, CharactorCollider, StaticCollider } /** * @en PhysX actor flags. * @zh PhysX 执行器标志。 */ export enum pxActorFlag { /** * @en Enable debug renderer for this actor. * @zh 为此执行器启用调试渲染器。 */ eVISUALIZATION = (1 << 0), /** * @en Disables scene gravity for this actor. * @zh 禁用此执行器的场景重力。 */ eDISABLE_GRAVITY = (1 << 1), /** * @en Enables the sending of PxSimulationEventCallback::onWake() and PxSimulationEventCallback::onSleep() notify events. * @zh 启用 PxSimulationEventCallback::onWake() 和 PxSimulationEventCallback::onSleep() 通知事件的发送。 */ eSEND_SLEEP_NOTIFIES = (1 << 2), /** * @en Disables simulation for the actor. * @zh 禁用执行器的模拟。 */ eDISABLE_SIMULATION = (1 << 3), } /** * @en The `pxCollider` class is used to handle physics colliders. * @zh `pxCollider` 类用于处理物理碰撞器。 */ export class pxCollider implements ICollider { /**@internal pool of Actor */ static _ActorPool: Map<number, pxCollider> = new Map(); /**@internal UUid of pxActor */ static _pxActorID: number = 0; /**temp tranform object */ private static _tempTransform: { translation: Vector3; rotation: Quaternion; } = { translation: new Vector3(), rotation: new Quaternion() }; /**@internal */ owner: Sprite3D; /**@internal */ componentEnable: boolean; /**@internal */ component: PhysicsColliderComponent; /**actor */ _pxActor: any; /**owner transform */ _transform: Transform3D; /**type data */ _type: pxColliderType = pxColliderType.StaticCollider; /**触发器 */ _isTrigger: boolean; /**@internal */ _isSimulate: boolean = false;//是否已经生效 /**can collision Group*/ _canCollisionWith: number; /**collision group */ _collisionGroup: number; /**pxshape */ _shape: pxColliderShape; /**manager */ _physicsManager: pxPhysicsManager; /**check destroy */ _destroyed: boolean = false; /** * @en The index of this collider in the physics update list. * @zh 此碰撞器在物理更新列表中的索引。 */ inPhysicUpdateListIndex: number = -1; /**@internal */ _enableProcessCollisions = false; /**id */ _id: number; /** @internal */ protected _transformFlag = 2147483647 /*int.MAX_VALUE*/; //material 这里material本身是shape行为,为了统一,暂时架构为colllider行为 private _bounciness: number = 0.1; /** @internal */ private _dynamicFriction: number = 0.1; /** @internal */ private _staticFriction: number = 0.1; /** @internal */ private _bounceCombine: PhysicsCombineMode = PhysicsCombineMode.Average; /** @internal */ private _frictionCombine: PhysicsCombineMode = PhysicsCombineMode.Average; /** * @en Creates a instance of pxCollider. * @param manager The physics manager responsible for this collider. * @zh 创建一个 pxCollider 实例。 * @param manager 负责管理此碰撞器的物理管理器。 */ constructor(manager: pxPhysicsManager) { this._collisionGroup = Physics3DUtils.PHYSXDEFAULTMASKVALUE; this._canCollisionWith = Physics3DUtils.PHYSXDEFAULTMASKVALUE; this._physicsManager = manager; this._id = pxCollider._pxActorID++; } /** * @en Indicates whether the collider is active. * @zh 表示碰撞器是否处于激活状态。 */ active: boolean; /** * @en Sets the friction value for the collider. * @param value The friction value to set. * @zh 设置碰撞器的摩擦力值。 * @param value 要设置的摩擦力值。 */ setfriction?(value: number): void { throw new NotImplementedError(); } /** * @en Sets the rolling friction value for the collider. * @param value The rolling friction value to set. * @zh 设置碰撞器的滚动摩擦力值。 * @param value 要设置的滚动摩擦力值。 */ setRollingFriction?(value: number): void { throw new NotImplementedError(); } protected setActorFlag(flag: pxActorFlag, value: boolean) { this._pxActor.setCustomFlag(flag, value); } /** * @en Gets the capability of the collider. * @param value The capability to check. * @zh 获取碰撞器的能力。 * @param value 要检查的能力。 */ getCapable(value: number): boolean { return null; } /** * @en Sets the collider shape for this collider. * @param shape The collider shape to set. * @zh 为此碰撞器设置碰撞形状。 * @param shape 要设置的碰撞形状。 */ setColliderShape(shape: pxColliderShape): void { if (shape == this._shape) return; if (shape instanceof pxCompoundColliderShape) { shape._pxCollider = this; shape.refreshShapes(); } var lastColliderShape: pxColliderShape = this._shape; this._shape = shape; //shape._pxCollider = this; if (shape) { if (this._pxActor) { if (lastColliderShape) lastColliderShape.removeFromActor(this); this._shape.addToActor(this); let simulate = this._isSimulate; simulate && this._physicsManager.removeCollider(this); this._initColliderShapeByCollider(); if ((simulate || !lastColliderShape || (lastColliderShape && lastColliderShape._destroyed)) && this.componentEnable) { this._physicsManager.addCollider(this); } } else { this._shape = null; } } else { if (this._isSimulate) { this._physicsManager.removeCollider(this); } } lastColliderShape && lastColliderShape.destroy(); } protected _initColliderShapeByCollider() { this.setBounceCombine(this._bounceCombine); this.setFrictionCombine(this._frictionCombine); this.setStaticFriction(this._staticFriction); this.setBounciness(this._bounciness); this.setDynamicFriction(this._dynamicFriction); this.setCollisionGroup(this._collisionGroup); this.setCanCollideWith(this._canCollisionWith); } /** * @en Destroys the collider and releases its resources. * @zh 销毁碰撞器并释放其资源。 */ destroy(): void { this._pxActor.release(); this._destroyed = true; } /** * @en Sets the collision group for this collider. * @param value The collision group value. * @zh 设置此碰撞器的碰撞组。 * @param value 碰撞组值。 */ setCollisionGroup(value: number): void { if (value == Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER) { value = Physics3DUtils.PHYSXDEFAULTMASKVALUE; } this._collisionGroup = value; this._shape.setSimulationFilterData(this._collisionGroup, this._canCollisionWith); } /** * @en Sets which groups this collider can collide with. * @param value The collision mask value. * @zh 设置此碰撞器可以与哪些组碰撞。 * @param value 碰撞掩码值。 */ setCanCollideWith(value: number): void { if (value == Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER) { value = Physics3DUtils.PHYSXDEFAULTMASKVALUE; } this._canCollisionWith = value; this._shape.setSimulationFilterData(this._collisionGroup, this._canCollisionWith); } /** * @en Sets the event filter for the collider. * @param events An array of events to filter. * @zh 设置碰撞器的事件过滤器。 * @param events 要过滤的事件数组。 */ setEventFilter(events: []): void { if (!this._shape) return; let flag = partFlag.eCONTACT_DEFAULT | partFlag.eTRIGGER_DEFAULT; for (let i = 0, j = events.length; i < j; i++) { let value = events[i]; if (value == Event.TRIGGER_ENTER) { flag = flag | partFlag.eTRIGGER_DEFAULT | partFlag.eNOTIFY_TOUCH_FOUND; } if (value == Event.TRIGGER_STAY) { // flag = partFlag.eNOTIFY_TOUCH_PERSISTS; } if (value == Event.TRIGGER_EXIT) { flag = flag | partFlag.eTRIGGER_DEFAULT | partFlag.eNOTIFY_TOUCH_LOST; } if (value == Event.COLLISION_ENTER) { flag = flag | partFlag.eNOTIFY_TOUCH_PERSISTS | partFlag.eNOTIFY_CONTACT_POINTS; } if (value == Event.COLLISION_STAY) { flag = flag | partFlag.eNOTIFY_TOUCH_PERSISTS; } if (value == Event.COLLISION_EXIT) { flag = flag | partFlag.eNOTIFY_TOUCH_PERSISTS | partFlag.eNOTIFY_TOUCH_LOST; } } this._shape && this._shape.setEventFilterData(flag); } allowSleep(value: boolean): void { } /** * @en Sets the owner node for this collider. * @param node The Sprite3D node that owns this collider. * @zh 设置此碰撞器的所有者节点。 * @param node 拥有此碰撞器的 Sprite3D 节点。 */ setOwner(node: Sprite3D): void { this.owner = node; this._transform = node.transform; this._initCollider(); pxCollider._ActorPool.set(this._id, this); this._pxActor.setUUID(this._id); this.setActorFlag(pxActorFlag.eSEND_SLEEP_NOTIFIES, true); } protected _initCollider() { //override it } /** * @en Notifies that the transform has changed. * @param flag The transform change flag. * @zh 通知变换已更改。 * @param flag 变换更改标志。 */ transformChanged(flag: number): void { this._transformFlag = flag; if (this.inPhysicUpdateListIndex == -1 && !this._enableProcessCollisions) { this._physicsManager._physicsUpdateList.add(this); } } /** * @en Sets the world transform of the collider. * @param focus Whether to force update even if no change is detected. * @zh 设置碰撞器的世界变换。 * @param focus 是否强制更新,即使未检测到变化。 */ setWorldTransform(focus: boolean): void { if (this.owner) { if (focus || this._getTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION) || this._getTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION)) { this._pxActor.setGlobalPose(this._transformTo(this.owner.transform.position, this.owner.transform.rotation), true); this._setTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION, false); this._setTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION, false); } if (focus || this._getTransformFlag(Transform3D.TRANSFORM_WORLDSCALE) && this._shape) { this._shape && this._shape.setOffset(this._shape._offset); this._setTransformFlag(Transform3D.TRANSFORM_WORLDSCALE, false); } } } /** * @en Sets the bounciness (restitution) of the collider. * @param value The bounciness value. * @zh 设置碰撞器的弹性(恢复)。 * @param value 弹性值。 */ setBounciness(value: number): void { this._bounciness = value; this._shape && this._shape._pxMaterials[0].setBounciness(value); } /** * @en Sets the dynamic friction of the collider. * @param value The dynamic friction value. * @zh 设置碰撞器的动态摩擦力。 * @param value 动态摩擦力值。 */ setDynamicFriction(value: number): void { this._dynamicFriction = value; this._shape && this._shape._pxMaterials[0].setDynamicFriction(value); } /** * @en Sets the static friction of the collider. * @param value The static friction value. * @zh 设置碰撞器的静态摩擦力。 * @param value 静态摩擦力值。 */ setStaticFriction(value: number): void { this._staticFriction = value; this._shape && this._shape._pxMaterials[0].setStaticFriction(value); } /** * @en Sets the friction combine mode of the collider. * @param value The friction combine mode. * @zh 设置碰撞器的摩擦力合并模式。 * @param value 摩擦力合并模式。 */ setFrictionCombine(value: PhysicsCombineMode): void { this._frictionCombine = value; this._shape && this._shape._pxMaterials[0].setFrictionCombine(value); } /** * @en Sets the bounce combine mode of the collider. * @param value The bounce combine mode. * @zh 设置碰撞器的弹性合并模式。 * @param value 弹性合并模式。 */ setBounceCombine(value: PhysicsCombineMode): void { this._bounceCombine = value; this._shape && this._shape._pxMaterials[0].setBounceCombine(value); } /** * @internal */ _getTransformFlag(type: number): boolean { return (this._transformFlag & type) != 0; } /** * @internal */ _setTransformFlag(type: number, value: boolean): void { if (value) this._transformFlag |= type; else this._transformFlag &= ~type; } /** * @internal */ _transformTo(pos: Vector3, rot: Quaternion): { translation: Vector3; rotation: Quaternion } { const transform = pxCollider._tempTransform; pos.cloneTo(transform.translation); rot.normalize(transform.rotation); return transform; } }
412
0.936326
1
0.936326
game-dev
MEDIA
0.939648
game-dev
0.963237
1
0.963237
ConsideredHamster/YetAnotherPixelDungeon
11,255
app/src/main/java/com/consideredhamster/yetanotherpixeldungeon/items/misc/OilLantern.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Yet Another Pixel Dungeon * Copyright (C) 2015-2016 Considered Hamster * * 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.consideredhamster.yetanotherpixeldungeon.items.misc; import com.consideredhamster.yetanotherpixeldungeon.Dungeon; import com.consideredhamster.yetanotherpixeldungeon.actors.Actor; import com.consideredhamster.yetanotherpixeldungeon.actors.blobs.Blob; import com.consideredhamster.yetanotherpixeldungeon.actors.blobs.Fire; import com.consideredhamster.yetanotherpixeldungeon.actors.buffs.Buff; import com.consideredhamster.yetanotherpixeldungeon.actors.buffs.bonuses.Invisibility; import com.consideredhamster.yetanotherpixeldungeon.actors.buffs.debuffs.Frozen; import com.consideredhamster.yetanotherpixeldungeon.actors.buffs.special.Light; import com.consideredhamster.yetanotherpixeldungeon.actors.hero.Hero; import com.consideredhamster.yetanotherpixeldungeon.items.Item; import com.consideredhamster.yetanotherpixeldungeon.levels.Level; import com.consideredhamster.yetanotherpixeldungeon.misc.mechanics.Ballistica; import com.consideredhamster.yetanotherpixeldungeon.misc.utils.GLog; import com.consideredhamster.yetanotherpixeldungeon.misc.utils.Utils; import com.consideredhamster.yetanotherpixeldungeon.scenes.CellSelector; import com.consideredhamster.yetanotherpixeldungeon.scenes.GameScene; import com.consideredhamster.yetanotherpixeldungeon.visuals.Assets; import com.consideredhamster.yetanotherpixeldungeon.visuals.effects.CellEmitter; import com.consideredhamster.yetanotherpixeldungeon.visuals.effects.particles.FlameParticle; import com.consideredhamster.yetanotherpixeldungeon.visuals.sprites.ItemSpriteSheet; import com.watabou.noosa.audio.Sample; import com.watabou.utils.Bundle; import java.util.ArrayList; public class OilLantern extends Item { public static final String AC_LIGHT = "LIGHT"; public static final String AC_SNUFF = "SNUFF"; public static final String AC_REFILL = "REFILL"; public static final String AC_BURN = "BURN"; private static final float TIME_TO_USE = 1f; private static final int MAX_CHARGE = 100; private static final String TXT_STATUS = "%d%%"; private static final String TXT_CANT_BURN = "You need a spare oil flask for this!"; private static final String TXT_NO_FLASKS = "You don't have oil to refill the lamp!"; private static final String TXT_DEACTIVATE = "Your lantern flickers faintly and goes out!"; private static final String TXT_REFILL = "You refill the lantern."; private static final String TXT_LIGHT = "You light the lantern."; private static final String TXT_SNUFF = "You snuff out the lantern."; private static final String TXT_BURN_SELF = "You pour the oil from an oil flask on yourself and ignite it. Just... Why?"; private static final String TXT_BURN_TILE = "You pour the oil from an oil flask on a nearby tile and ignite it."; private static final String TXT_BURN_FAIL = "You try to ignite a nearby tile, but it doesn't catch fire."; { name = "oil lantern"; image = ItemSpriteSheet.LANTERN; active = false; charge = MAX_CHARGE; flasks = 0; visible = false; unique = true; updateSprite(); } private boolean active; private int charge; private int flasks; private static final String ACTIVE = "active"; private static final String FLASKS = "flasks"; private static final String CHARGE = "charge"; public void updateSprite() { image = isActivated() ? ItemSpriteSheet.LANTERN_LIT : ItemSpriteSheet.LANTERN ; } public int getCharge() { return charge; } public int getFlasks() { return flasks; } public void spendCharge() { charge--; updateQuickslot(); } public boolean isActivated() { return active ; } @Override public String quickAction() { return charge > 0 ? ( isActivated() ? AC_SNUFF : AC_LIGHT ) : AC_REFILL ; } @Override public void storeInBundle( Bundle bundle ) { super.storeInBundle( bundle ); bundle.put( ACTIVE, active ); bundle.put( CHARGE, charge ); bundle.put( FLASKS, flasks ); } @Override public void restoreFromBundle( Bundle bundle ) { super.restoreFromBundle( bundle ); active = bundle.getBoolean( ACTIVE ); charge = bundle.getInt( CHARGE ); flasks = bundle.getInt( FLASKS ); updateSprite(); } @Override public ArrayList<String> actions( Hero hero ) { ArrayList<String> actions = super.actions( hero ); actions.add( isActivated() ? AC_SNUFF : AC_LIGHT ); actions.add( AC_REFILL ); actions.add( AC_BURN ); actions.remove( AC_THROW ); actions.remove( AC_DROP ); return actions; } @Override public void execute( final Hero hero, String action ) { if (action.equals( AC_LIGHT )) { if( charge > 0 ){ if( hero.buff( Frozen.class ) == null ){ activate( hero, true ); } else { GLog.n( Frozen.TXT_CANNOT_LIGHT ); } } } else if (action.equals( AC_SNUFF ) ) { if( isActivated() ){ deactivate( hero, true ); } } else if (action.equals( AC_REFILL ) ) { if ( flasks > 0 ) { refill( hero ); } else { GLog.w( TXT_NO_FLASKS ); } } else if (action.equals( AC_BURN ) ) { if ( flasks > 0 ) { curUser = hero; curItem = this; GameScene.selectCell( burner ); } else { GLog.w( TXT_CANT_BURN ); } } else { super.execute( hero, action ); } } public void refill( Hero hero ) { flasks--; charge = MAX_CHARGE; hero.spend( TIME_TO_USE ); hero.busy(); Sample.INSTANCE.play( Assets.SND_DRINK, 1.0f, 1.0f, 1.2f ); hero.sprite.operate( hero.pos ); GLog.i( TXT_REFILL ); updateQuickslot(); } public void activate( Hero hero, boolean voluntary ) { active = true; updateSprite(); Buff.affect( hero, Light.class ); // hero.updateSpriteState(); hero.search( false ); if( voluntary ){ hero.spend( TIME_TO_USE ); hero.busy(); GLog.i( TXT_LIGHT ); hero.sprite.operate( hero.pos ); } Sample.INSTANCE.play( Assets.SND_CLICK ); updateQuickslot(); Invisibility.dispel(); Dungeon.observe(); } public void deactivate( Hero hero, boolean voluntary ) { active = false; updateSprite(); Buff.detach( hero, Light.class ); // hero.updateSpriteState(); if( voluntary ){ hero.spend( TIME_TO_USE ); hero.busy(); hero.sprite.operate( hero.pos ); GLog.i( TXT_SNUFF ); } else { GLog.w( TXT_DEACTIVATE ); } Sample.INSTANCE.play( Assets.SND_PUFF ); updateQuickslot(); Dungeon.observe(); } public OilLantern collectFlask( OilFlask oil ) { flasks += oil.quantity; updateQuickslot(); return this; } @Override public int price() { return 0; } @Override public String status() { return Utils.format( TXT_STATUS, charge ); } @Override public String info() { return "This lamp from a hardened glass is an indispensable item in the dungeon, which is " + "notorious for its poor ambient lighting. Even in the darkest of dungeons, this simple " + "device can illuminate your way, provided that you've got oil flasks to keep it " + "alight.\n\n" + ( isActivated() ? "This small lantern shines vigorously, brighting your day. " : "This small lantern is snuffed out, waiting for its moment to shine. " ) + "You have " + ( charge / 10.0 ) + " oz of oil left and " + flasks + " spare flask" + ( flasks != 1 ? "s" : "" ) + " remaining."; } public static class OilFlask extends Item { { name = "oil flask"; image = ItemSpriteSheet.OIL_FLASK; visible = false; } @Override public boolean doPickUp( Hero hero ) { OilLantern lamp = hero.belongings.getItem( OilLantern.class ); if (lamp != null) { lamp.collectFlask( this ); GameScene.pickUp(this); Sample.INSTANCE.play(Assets.SND_ITEM); return true; } return super.doPickUp(hero); } @Override public int price() { return quantity * 30; } @Override public String info() { return "This container holds 10 oz of lantern oil. You can use it to " + "refill your lantern or pour on something to burn it."; } } protected static CellSelector.Listener burner = new CellSelector.Listener() { @Override public void onSelect( Integer target ) { if (target != null) { Ballistica.cast( curUser.pos, target, false, true ); int cell = Ballistica.trace[ 0 ]; if( Ballistica.distance > 0 ){ cell = Ballistica.trace[ 1 ]; } if( Level.flammable[ cell ] || !Level.solid[ cell ] && !Level.chasm[ cell ] ){ GameScene.add( Blob.seed( cell, 5, Fire.class ) ); } ((OilLantern)curItem).flasks--; Invisibility.dispel(); if( curUser.pos == cell ) { GLog.i( TXT_BURN_SELF ); } else if( Level.flammable[ cell ] || !Level.solid[ cell ] && !Level.chasm[ cell ] ){ GLog.i( TXT_BURN_TILE ); } else { GLog.i( TXT_BURN_FAIL ); } Sample.INSTANCE.play(Assets.SND_BURNING, 0.6f, 0.6f, 1.5f); CellEmitter.get( cell ).burst( FlameParticle.FACTORY, 5 ); curUser.sprite.operate(cell); curUser.busy(); curUser.spend( Actor.TICK ); } } @Override public String prompt() { return "Select nearby tile to burn"; } }; }
412
0.864017
1
0.864017
game-dev
MEDIA
0.951213
game-dev
0.980779
1
0.980779
mengtest/RPG_GameFramework
2,581
Client_GF/Assets/GameFramework/Scripts/Editor/Inspector/LocalizationComponentInspector.cs
//------------------------------------------------------------ // Game Framework // Copyright © 2013-2020 Jiang Yin. All rights reserved. // Homepage: https://gameframework.cn/ // Feedback: mailto:ellan@gameframework.cn //------------------------------------------------------------ using UnityEditor; using UnityGameFramework.Runtime; namespace UnityGameFramework.Editor { [CustomEditor(typeof(LocalizationComponent))] internal sealed class LocalizationComponentInspector : GameFrameworkInspector { private SerializedProperty m_EnableLoadDictionaryUpdateEvent = null; private SerializedProperty m_EnableLoadDictionaryDependencyAssetEvent = null; private HelperInfo<LocalizationHelperBase> m_LocalizationHelperInfo = new HelperInfo<LocalizationHelperBase>("Localization"); public override void OnInspectorGUI() { base.OnInspectorGUI(); serializedObject.Update(); LocalizationComponent t = (LocalizationComponent)target; EditorGUI.BeginDisabledGroup(EditorApplication.isPlayingOrWillChangePlaymode); { EditorGUILayout.PropertyField(m_EnableLoadDictionaryUpdateEvent); EditorGUILayout.PropertyField(m_EnableLoadDictionaryDependencyAssetEvent); m_LocalizationHelperInfo.Draw(); } EditorGUI.EndDisabledGroup(); if (EditorApplication.isPlaying && IsPrefabInHierarchy(t.gameObject)) { EditorGUILayout.LabelField("Language", t.Language.ToString()); EditorGUILayout.LabelField("System Language", t.SystemLanguage.ToString()); EditorGUILayout.LabelField("Dictionary Count", t.DictionaryCount.ToString()); } serializedObject.ApplyModifiedProperties(); Repaint(); } protected override void OnCompileComplete() { base.OnCompileComplete(); RefreshTypeNames(); } private void OnEnable() { m_EnableLoadDictionaryUpdateEvent = serializedObject.FindProperty("m_EnableLoadDictionaryUpdateEvent"); m_EnableLoadDictionaryDependencyAssetEvent = serializedObject.FindProperty("m_EnableLoadDictionaryDependencyAssetEvent"); m_LocalizationHelperInfo.Init(serializedObject); RefreshTypeNames(); } private void RefreshTypeNames() { m_LocalizationHelperInfo.Refresh(); serializedObject.ApplyModifiedProperties(); } } }
412
0.827733
1
0.827733
game-dev
MEDIA
0.80865
game-dev
0.933597
1
0.933597
StranikS-Scan/WorldOfTanks-Decompiled
1,787
source/res/scripts/client/gui/impl/gen/view_models/views/lobby/premacc/piggybank_model.py
# Python bytecode 2.7 (decompiled from Python 2.7) # Embedded file name: scripts/client/gui/impl/gen/view_models/views/lobby/premacc/piggybank_model.py from gui.impl.gen import R from gui.impl.gen.view_models.views.lobby.premacc.piggybank_base_model import PiggybankBaseModel class PiggybankModel(PiggybankBaseModel): __slots__ = ('onPremAccProlong', 'onGoToContentPage', 'onBackBtnClicked') def __init__(self, properties=11, commands=3): super(PiggybankModel, self).__init__(properties=properties, commands=commands) def getPeriodInDays(self): return self._getNumber(6) def setPeriodInDays(self, value): self._setNumber(6, value) def getPiggyIsFull(self): return self._getBool(7) def setPiggyIsFull(self, value): self._setBool(7, value) def getIsPremUsed(self): return self._getBool(8) def setIsPremUsed(self, value): self._setBool(8, value) def getBackBtnLabel(self): return self._getResource(9) def setBackBtnLabel(self, value): self._setResource(9, value) def getPercentDiscount(self): return self._getNumber(10) def setPercentDiscount(self, value): self._setNumber(10, value) def _initialize(self): super(PiggybankModel, self)._initialize() self._addNumberProperty('periodInDays', 0) self._addBoolProperty('piggyIsFull', False) self._addBoolProperty('isPremUsed', False) self._addResourceProperty('backBtnLabel', R.invalid()) self._addNumberProperty('percentDiscount', 0) self.onPremAccProlong = self._addCommand('onPremAccProlong') self.onGoToContentPage = self._addCommand('onGoToContentPage') self.onBackBtnClicked = self._addCommand('onBackBtnClicked')
412
0.536863
1
0.536863
game-dev
MEDIA
0.325412
game-dev
0.862041
1
0.862041
magefree/mage
1,471
Mage.Sets/src/mage/cards/m/MoltenMonstrosity.java
package mage.cards.m; import mage.MageInt; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.dynamicvalue.common.GreatestAmongPermanentsValue; import mage.abilities.effects.common.cost.SpellCostReductionSourceEffect; import mage.abilities.keyword.TrampleAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.Zone; import java.util.UUID; /** * @author TheElk801 */ public final class MoltenMonstrosity extends CardImpl { public MoltenMonstrosity(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{7}{R}"); this.subtype.add(SubType.HELLION); this.power = new MageInt(5); this.toughness = new MageInt(5); // This spell costs {X} less to cast, where X is the greatest power among creatures you control. this.addAbility(new SimpleStaticAbility( Zone.ALL, new SpellCostReductionSourceEffect(GreatestAmongPermanentsValue.POWER_CONTROLLED_CREATURES) ).setRuleAtTheTop(true).addHint(GreatestAmongPermanentsValue.POWER_CONTROLLED_CREATURES.getHint())); // Trample this.addAbility(TrampleAbility.getInstance()); } private MoltenMonstrosity(final MoltenMonstrosity card) { super(card); } @Override public MoltenMonstrosity copy() { return new MoltenMonstrosity(this); } }
412
0.943135
1
0.943135
game-dev
MEDIA
0.99
game-dev
0.985322
1
0.985322
sarkahn/dots-roguelike
4,622
Assets/DotsRogue/UI.cs
using Unity.Collections; using Unity.Entities; using Unity.Jobs; namespace DotsRogue { public struct UILogBuffer : IBufferElementData { public FixedString128 Value; public static implicit operator FixedString128(UILogBuffer b) => b.Value; public static implicit operator UILogBuffer(FixedString128 v) => new UILogBuffer { Value = v }; public static implicit operator UILogBuffer(string str) => new UILogBuffer { Value = str }; } public struct HitPointsUI : IComponentData { public int max; public int current; } public struct UI : IComponentData { public static void AddToEntity(EntityManager em, Entity e) { } } public struct UIJobContext { public BufferFromEntity<UILogBuffer> LogBuffer; public ComponentDataFromEntity<HitPointsUI> HitPointUI; public Entity Entity; public UIJobContext(SystemBase sys, Entity e, bool readOnly = false) { Entity = e; HitPointUI = sys.GetComponentDataFromEntity<HitPointsUI>(readOnly); LogBuffer = sys.GetBufferFromEntity<UILogBuffer>(readOnly); } public UIJobContext(SystemBase sys, bool readOnly = false) : this(sys, sys.GetSingletonEntity<UILogBuffer>(), readOnly) { } public void Log(FixedString128 str) { //Debug.Log($"Logging string len {str.Length}: {str}"); LogBuffer[Entity].Add(str); } public void SetHitPointsUI(int current, int max) { HitPointUI[Entity] = new HitPointsUI { current = current, max = max }; } } public class UpdateUIHealthSystem : SystemBase { protected override void OnCreate() { RequireSingletonForUpdate<UI>(); } protected override void OnUpdate() { var uiEntity = GetSingletonEntity<UI>(); var ui = new UIJobContext(this, uiEntity, false); Entities .WithChangeFilter<HitPoints>() .WithAll<Player>() .ForEach(( in MaxHitPoints max, in HitPoints hp) => { ui.SetHitPointsUI(hp, max); }).Schedule(); } } [UpdateInGroup(typeof(LateSimulationSystemGroup))] [UpdateAfter(typeof(ResolveCombatSystem))] public class CombatLogSystem : SystemBase { protected override void OnCreate() { RequireSingletonForUpdate<UI>(); } protected override void OnUpdate() { var uiEntity = GetSingletonEntity<UI>(); var ui = new UIJobContext(this, uiEntity, false); Entities .WithoutBurst() .ForEach((in Name name, in DynamicBuffer<CombatDefendBuffer> defendBuffer, in HitPoints hp) => { for(int i = 0; i < defendBuffer.Length; ++i) { var defend = defendBuffer[i]; var attackerName = GetComponent<Name>(defend.Attacker); int dmg = defend.Damage; FixedString128 str = $"{attackerName.Value} attacked {name.Value} for {dmg} damage"; //Debug.Log($"STRLen from CombatLogSystem {str.Length}: {str}"); ui.Log(str); } if(hp <= 0) { ui.Log($"{name.Value} was killed!"); } }).Run(); } } [UpdateInGroup(typeof(InitializationSystemGroup))] public class PickupItemLogSystem : SystemBase { protected override void OnUpdate() { var uiEntity = GetSingletonEntity<UI>(); var ui = new UIJobContext(this, uiEntity, false); Entities .WithoutBurst() .WithAll<Player>() .ForEach((in WantsToPickUpItem pickup) => { if(pickup.item == Entity.Null) { ui.Log($"There is nothing here to pick up."); } else { var itemName = GetComponent<Name>(pickup.item); ui.Log($"You picked up a {itemName}."); } }).Run(); } } }
412
0.722646
1
0.722646
game-dev
MEDIA
0.858744
game-dev
0.742516
1
0.742516
Patcher0/ThePitUltimate
1,820
core/src/main/java/net/mizukilab/pit/enchantment/type/normal/SniperEnchant.java
package net.mizukilab.pit.enchantment.type.normal; import com.google.common.util.concurrent.AtomicDouble; import net.mizukilab.pit.enchantment.AbstractEnchantment; import net.mizukilab.pit.enchantment.param.event.PlayerOnly; import net.mizukilab.pit.enchantment.param.item.BowOnly; import net.mizukilab.pit.enchantment.rarity.EnchantmentRarity; import net.mizukilab.pit.parm.listener.IPlayerShootEntity; import net.mizukilab.pit.util.PlayerUtil; import net.mizukilab.pit.util.cooldown.Cooldown; import nya.Skip; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import java.util.concurrent.atomic.AtomicBoolean; /** * @Author: Misoryan * @Created_In: 2021/2/7 17:48 */ @Skip @BowOnly public class SniperEnchant extends AbstractEnchantment implements IPlayerShootEntity { @Override public String getEnchantName() { return "锐箭"; } @Override public int getMaxEnchantLevel() { return 3; } @Override public String getNbtName() { return "sniper_enchant"; } @Override public EnchantmentRarity getRarity() { return EnchantmentRarity.NORMAL; } @Override public Cooldown getCooldown() { return null; } @Override public String getUsefulnessLore(int enchantLevel) { return "&7弓箭命中距离 &e24 &7格外的玩家时造成的伤害 &c+" + (10 + enchantLevel * 10) + "%"; } @Override @net.mizukilab.pit.parm.type.BowOnly @PlayerOnly public void handleShootEntity(int enchantLevel, Player attacker, Entity target, double damage, AtomicDouble finalDamage, AtomicDouble boostDamage, AtomicBoolean cancel) { Player targetPlayer = (Player) target; if (PlayerUtil.getDistance(attacker, targetPlayer) >= 24) { boostDamage.getAndAdd(0.1 + enchantLevel * 0.1); } } }
412
0.84756
1
0.84756
game-dev
MEDIA
0.943723
game-dev
0.928975
1
0.928975
cirosantilli/parsec-benchmark
1,461
pkgs/apps/facesim/src/Public_Library/Geometry/IMPLICIT_SURFACE_LIST.h
//##################################################################### // Copyright 2002-2004, Robert Bridson, Ron Fedkiw, Eran Guendelman, Geoffrey Irving. // This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt. //##################################################################### // Class IMPLICIT_SURFACE_LIST //##################################################################### #ifndef __IMPLICIT_SURFACE_LIST__ #define __IMPLICIT_SURFACE_LIST__ #include "../Data_Structures/DYNAMIC_LIST.h" namespace PhysBAM { template<class T> class IMPLICIT_SURFACE; template<class T> class IMPLICIT_SURFACE_LIST: public DYNAMIC_LIST<IMPLICIT_SURFACE<T>*> { private: using DYNAMIC_LIST<IMPLICIT_SURFACE<T>*>::array; using DYNAMIC_LIST<IMPLICIT_SURFACE<T>*>::id_to_index_map; using DYNAMIC_LIST<IMPLICIT_SURFACE<T>*>::last_unique_id; using DYNAMIC_LIST<IMPLICIT_SURFACE<T>*>::needs_write; mutable LIST_ARRAY<bool> levelset_data; // not quadtree data, indexed by id public: //##################################################################### template<class RW> void Read (const std::string& prefix, const int frame); template<class RW> void Write (const std::string& prefix, const int frame) const; virtual void Destroy_Element (IMPLICIT_SURFACE<T>*& segmented_surface, const int id); //##################################################################### }; } #endif
412
0.777698
1
0.777698
game-dev
MEDIA
0.68146
game-dev
0.579876
1
0.579876
LofizKittyCat/GradleMCPBase
5,798
src/main/java/net/minecraft/item/ItemFishFood.java
package net.minecraft.item; import com.google.common.collect.Maps; import java.util.List; import java.util.Map; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.potion.PotionHelper; import net.minecraft.world.World; public class ItemFishFood extends ItemFood { private final boolean cooked; public ItemFishFood(boolean cooked) { super(0, 0.0F, false); this.cooked = cooked; } public int getHealAmount(ItemStack stack) { ItemFishFood.FishType itemfishfood$fishtype = ItemFishFood.FishType.byItemStack(stack); return this.cooked && itemfishfood$fishtype.canCook() ? itemfishfood$fishtype.getCookedHealAmount() : itemfishfood$fishtype.getUncookedHealAmount(); } public float getSaturationModifier(ItemStack stack) { ItemFishFood.FishType itemfishfood$fishtype = ItemFishFood.FishType.byItemStack(stack); return this.cooked && itemfishfood$fishtype.canCook() ? itemfishfood$fishtype.getCookedSaturationModifier() : itemfishfood$fishtype.getUncookedSaturationModifier(); } public String getPotionEffect(ItemStack stack) { return ItemFishFood.FishType.byItemStack(stack) == ItemFishFood.FishType.PUFFERFISH ? PotionHelper.pufferfishEffect : null; } protected void onFoodEaten(ItemStack stack, World worldIn, EntityPlayer player) { ItemFishFood.FishType itemfishfood$fishtype = ItemFishFood.FishType.byItemStack(stack); if (itemfishfood$fishtype == ItemFishFood.FishType.PUFFERFISH) { player.addPotionEffect(new PotionEffect(Potion.poison.id, 1200, 3)); player.addPotionEffect(new PotionEffect(Potion.hunger.id, 300, 2)); player.addPotionEffect(new PotionEffect(Potion.confusion.id, 300, 1)); } super.onFoodEaten(stack, worldIn, player); } public void getSubItems(Item itemIn, CreativeTabs tab, List<ItemStack> subItems) { for (ItemFishFood.FishType itemfishfood$fishtype : ItemFishFood.FishType.values()) { if (!this.cooked || itemfishfood$fishtype.canCook()) { subItems.add(new ItemStack(this, 1, itemfishfood$fishtype.getMetadata())); } } } public String getUnlocalizedName(ItemStack stack) { ItemFishFood.FishType itemfishfood$fishtype = ItemFishFood.FishType.byItemStack(stack); return this.getUnlocalizedName() + "." + itemfishfood$fishtype.getUnlocalizedName() + "." + (this.cooked && itemfishfood$fishtype.canCook() ? "cooked" : "raw"); } public static enum FishType { COD(0, "cod", 2, 0.1F, 5, 0.6F), SALMON(1, "salmon", 2, 0.1F, 6, 0.8F), CLOWNFISH(2, "clownfish", 1, 0.1F), PUFFERFISH(3, "pufferfish", 1, 0.1F); private static final Map<Integer, ItemFishFood.FishType> META_LOOKUP = Maps.<Integer, ItemFishFood.FishType>newHashMap(); private final int meta; private final String unlocalizedName; private final int uncookedHealAmount; private final float uncookedSaturationModifier; private final int cookedHealAmount; private final float cookedSaturationModifier; private boolean cookable = false; private FishType(int meta, String unlocalizedName, int uncookedHeal, float uncookedSaturation, int cookedHeal, float cookedSaturation) { this.meta = meta; this.unlocalizedName = unlocalizedName; this.uncookedHealAmount = uncookedHeal; this.uncookedSaturationModifier = uncookedSaturation; this.cookedHealAmount = cookedHeal; this.cookedSaturationModifier = cookedSaturation; this.cookable = true; } private FishType(int meta, String unlocalizedName, int uncookedHeal, float uncookedSaturation) { this.meta = meta; this.unlocalizedName = unlocalizedName; this.uncookedHealAmount = uncookedHeal; this.uncookedSaturationModifier = uncookedSaturation; this.cookedHealAmount = 0; this.cookedSaturationModifier = 0.0F; this.cookable = false; } public int getMetadata() { return this.meta; } public String getUnlocalizedName() { return this.unlocalizedName; } public int getUncookedHealAmount() { return this.uncookedHealAmount; } public float getUncookedSaturationModifier() { return this.uncookedSaturationModifier; } public int getCookedHealAmount() { return this.cookedHealAmount; } public float getCookedSaturationModifier() { return this.cookedSaturationModifier; } public boolean canCook() { return this.cookable; } public static ItemFishFood.FishType byMetadata(int meta) { ItemFishFood.FishType itemfishfood$fishtype = (ItemFishFood.FishType)META_LOOKUP.get(Integer.valueOf(meta)); return itemfishfood$fishtype == null ? COD : itemfishfood$fishtype; } public static ItemFishFood.FishType byItemStack(ItemStack stack) { return stack.getItem() instanceof ItemFishFood ? byMetadata(stack.getMetadata()) : COD; } static { for (ItemFishFood.FishType itemfishfood$fishtype : values()) { META_LOOKUP.put(Integer.valueOf(itemfishfood$fishtype.getMetadata()), itemfishfood$fishtype); } } } }
412
0.69675
1
0.69675
game-dev
MEDIA
0.988288
game-dev
0.542571
1
0.542571
The-Final-Nights/The-Final-Nights
5,744
code/modules/mob/living/carbon/alien/special/alien_embryo.dm
// This is to replace the previous datum/disease/alien_embryo for slightly improved handling and maintainability // It functions almost identically (see code/datums/diseases/alien_embryo.dm) /obj/item/organ/body_egg/alien_embryo name = "alien embryo" icon = 'icons/mob/alien.dmi' icon_state = "larva0_dead" food_reagents = list(/datum/reagent/consumable/nutriment = 5, /datum/reagent/toxin/acid = 10) ///What stage of growth the embryo is at. Developed embryos give the host symptoms suggesting that an embryo is inside them. var/stage = 0 /// Are we bursting out of the poor sucker who's the xeno mom? var/bursting = FALSE /// How long does it take to advance one stage? Growth time * 5 = how long till we make a Larva! var/growth_time = 60 SECONDS /obj/item/organ/body_egg/alien_embryo/Initialize() . = ..() advance_embryo_stage() /obj/item/organ/body_egg/alien_embryo/on_find(mob/living/finder) ..() if(stage < 5) to_chat(finder, "<span class='notice'>It's small and weak, barely the size of a foetus.</span>") else to_chat(finder, "<span class='notice'>It's grown quite large, and writhes slightly as you look at it.</span>") if(prob(10)) AttemptGrow(0) /obj/item/organ/body_egg/alien_embryo/on_life() . = ..() switch(stage) if(3, 4) if(prob(2)) owner.emote("sneeze") if(prob(2)) owner.emote("cough") if(prob(2)) to_chat(owner, "<span class='danger'>Your throat feels sore.</span>") if(prob(2)) to_chat(owner, "<span class='danger'>Mucous runs down the back of your throat.</span>") if(5) if(prob(2)) owner.emote("sneeze") if(prob(2)) owner.emote("cough") if(prob(4)) to_chat(owner, "<span class='danger'>Your muscles ache.</span>") if(prob(20)) owner.take_bodypart_damage(1) if(prob(4)) to_chat(owner, "<span class='danger'>Your stomach hurts.</span>") if(prob(20)) owner.adjustToxLoss(1) if(5) to_chat(owner, "<span class='danger'>You feel something tearing its way out of your stomach...</span>") owner.adjustToxLoss(10) /// Controls Xenomorph Embryo growth. If embryo is fully grown (or overgrown), stop the proc. If not, increase the stage by one and if it's not fully grown (stage 6), add a timer to do this proc again after however long the growth time variable is. /obj/item/organ/body_egg/alien_embryo/proc/advance_embryo_stage() if(stage >= 6) return if(++stage < 6) INVOKE_ASYNC(src, PROC_REF(RefreshInfectionImage)) addtimer(CALLBACK(src, PROC_REF(advance_embryo_stage)), growth_time) /obj/item/organ/body_egg/alien_embryo/egg_process() if(stage == 6 && prob(50)) for(var/datum/surgery/S in owner.surgeries) if(S.location == BODY_ZONE_CHEST && istype(S.get_surgery_step(), /datum/surgery_step/manipulate_organs)) AttemptGrow(0) return AttemptGrow() /obj/item/organ/body_egg/alien_embryo/proc/AttemptGrow(gib_on_success=TRUE) if(!owner || bursting) return bursting = TRUE var/list/candidates = pollGhostCandidates("Do you want to play as an alien larva that will burst out of [owner.real_name]?", ROLE_ALIEN, null, ROLE_ALIEN, 100, POLL_IGNORE_ALIEN_LARVA) if(QDELETED(src) || QDELETED(owner)) return if(!candidates.len || !owner) bursting = FALSE stage = 5 // If no ghosts sign up for the Larva, let's regress our growth by one minute, we will try again! addtimer(CALLBACK(src, PROC_REF(advance_embryo_stage)), growth_time) return var/mob/dead/observer/ghost = pick(candidates) var/mutable_appearance/overlay = mutable_appearance('icons/mob/alien.dmi', "burst_lie") owner.add_overlay(overlay) var/atom/xeno_loc = get_turf(owner) var/mob/living/carbon/alien/larva/new_xeno = new(xeno_loc) new_xeno.key = ghost.key SEND_SOUND(new_xeno, sound('sound/voice/hiss5.ogg',0,0,0,100)) //To get the player's attention ADD_TRAIT(new_xeno, TRAIT_IMMOBILIZED, type) //so we don't move during the bursting animation ADD_TRAIT(new_xeno, TRAIT_HANDS_BLOCKED, type) new_xeno.notransform = 1 new_xeno.invisibility = INVISIBILITY_MAXIMUM sleep(6) if(QDELETED(src) || QDELETED(owner)) qdel(new_xeno) CRASH("AttemptGrow failed due to the early qdeletion of source or owner.") if(new_xeno) REMOVE_TRAIT(new_xeno, TRAIT_IMMOBILIZED, type) REMOVE_TRAIT(new_xeno, TRAIT_HANDS_BLOCKED, type) new_xeno.notransform = 0 new_xeno.invisibility = 0 if(gib_on_success) new_xeno.visible_message("<span class='danger'>[new_xeno] bursts out of [owner] in a shower of gore!</span>", "<span class='userdanger'>You exit [owner], your previous host.</span>", "<span class='hear'>You hear organic matter ripping and tearing!</span>") owner.gib(TRUE) else new_xeno.visible_message("<span class='danger'>[new_xeno] wriggles out of [owner]!</span>", "<span class='userdanger'>You exit [owner], your previous host.</span>") owner.adjustBruteLoss(40) owner.cut_overlay(overlay) qdel(src) /*---------------------------------------- Proc: AddInfectionImages(C) Des: Adds the infection image to all aliens for this embryo ----------------------------------------*/ /obj/item/organ/body_egg/alien_embryo/AddInfectionImages() for(var/mob/living/carbon/alien/alien in GLOB.player_list) var/I = image('icons/mob/alien.dmi', loc = owner, icon_state = "infected[stage]") alien.client.images += I /*---------------------------------------- Proc: RemoveInfectionImage(C) Des: Removes all images from the mob infected by this embryo ----------------------------------------*/ /obj/item/organ/body_egg/alien_embryo/RemoveInfectionImages() for(var/mob/living/carbon/alien/alien in GLOB.player_list) for(var/image/I in alien.client.images) var/searchfor = "infected" if(I.loc == owner && findtext(I.icon_state, searchfor, 1, length(searchfor) + 1)) qdel(I)
412
0.932048
1
0.932048
game-dev
MEDIA
0.953274
game-dev
0.839419
1
0.839419
ProjectIgnis/CardScripts
2,116
official/c6766208.lua
--DDD疾風大王エグゼクティブ・アレクサンダー --D/D/D Gust High King Alexander local s,id=GetID() function s.initial_effect(c) c:EnableReviveLimit() Synchro.AddProcedure(c,nil,1,1,Synchro.NonTuner(nil),1,99) --spsummon local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(id,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DELAY) e1:SetCode(EVENT_SUMMON_SUCCESS) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1,id) e1:SetCondition(s.spcon) e1:SetTarget(s.sptg) e1:SetOperation(s.spop) c:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e2) --atk local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_SINGLE) e3:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e3:SetCode(EFFECT_UPDATE_ATTACK) e3:SetRange(LOCATION_MZONE) e3:SetCondition(s.atkcon) e3:SetValue(3000) c:RegisterEffect(e3) end function s.cfilter(c,tp) return c:IsFaceup() and c:IsSetCard(SET_DD) and c:IsControler(tp) end function s.spcon(e,tp,eg,ep,ev,re,r,rp) return not eg:IsContains(e:GetHandler()) and eg:IsExists(s.cfilter,1,nil,tp) end function s.spfilter(c,e,tp) return c:IsSetCard(SET_DD) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function s.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and s.spfilter(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingTarget(s.spfilter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectTarget(tp,s.spfilter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0) end function s.spop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP) end end function s.atkfilter(c) return c:IsFaceup() and c:IsSetCard(SET_DDD) end function s.atkcon(e) return Duel.GetMatchingGroupCount(s.atkfilter,e:GetHandlerPlayer(),LOCATION_MZONE,LOCATION_MZONE,nil)>=3 end
412
0.933275
1
0.933275
game-dev
MEDIA
0.970376
game-dev
0.950057
1
0.950057
OpenRA/ra2
2,354
OpenRA.Mods.RA2/Traits/WeatherPaletteEffect.cs
#region Copyright & License Information /* * Copyright (c) The OpenRA Developers and Contributors * This file is part of OpenRA, which is free software. It is made * available to you under the terms of the GNU General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. For more * information, see COPYING. */ #endregion using System.Collections.Generic; using System.Linq; using OpenRA.Graphics; using OpenRA.Traits; using Color = OpenRA.Primitives.Color; namespace OpenRA.Mods.RA2.Traits { using Util = OpenRA.Graphics.Util; [Desc("Global palette effect with a fixed color.")] public class WeatherPaletteEffectInfo : TraitInfo { public readonly string[] ExcludePalette = { "cursor", "chrome", "colorpicker", "fog", "shroud", "effect" }; [Desc("Used to pre-multiply colors.")] public readonly float Ratio = 0.6f; [Desc("Measured in ticks.")] public readonly int Length = 40; public readonly Color Color = Color.LightGray; [Desc("Set this when using multiple independent flash effects.")] public readonly string Type = null; public override object Create(ActorInitializer init) { return new WeatherPaletteEffect(this); } } public class WeatherPaletteEffect : IPaletteModifier, ITick { public readonly WeatherPaletteEffectInfo Info; int remainingFrames; public WeatherPaletteEffect(WeatherPaletteEffectInfo info) { Info = info; } public void Enable(int ticks) { if (ticks == -1) remainingFrames = Info.Length; else remainingFrames = ticks; } void ITick.Tick(Actor self) { if (remainingFrames > 0) remainingFrames--; } void IPaletteModifier.AdjustPalette(IReadOnlyDictionary<string, MutablePalette> palettes) { if (remainingFrames == 0) return; foreach (var palette in palettes) { if (Info.ExcludePalette.Contains(palette.Key)) continue; for (var x = 0; x < Palette.Size; x++) { var orig = palette.Value.GetColor(x); var c = Info.Color; var color = Color.FromArgb(orig.A, ((int)c.R).Clamp(0, 255), ((int)c.G).Clamp(0, 255), ((int)c.B).Clamp(0, 255)); var final = Util.PremultipliedColorLerp(Info.Ratio, orig, Util.PremultiplyAlpha(Color.FromArgb(orig.A, color))); palette.Value.SetColor(x, final); } } } } }
412
0.899203
1
0.899203
game-dev
MEDIA
0.353649
game-dev
0.968529
1
0.968529
castle-engine/castle-engine
2,276
src/ui/castlecontrols_clipboard.inc
{%MainUnit castlecontrols.pas} { Copyright 2017-2018 Michalis Kamburelis. This file is part of "Castle Game Engine". "Castle Game Engine" is free software; see the file COPYING.txt, included in this distribution, for details about the copyright. "Castle Game Engine" 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. ---------------------------------------------------------------------------- } {$ifdef read_interface} type { Clipboard to cut / copy / paste the text. You usually use this through the single global instance @link(Clipboard). The trivial interface is mostly compatible with LCL clipboard. } TCastleClipboard = class private FContents: String; protected function GetAsText: String; virtual; procedure SetAsText(const Value: String); virtual; public property AsText: String read GetAsText write SetAsText; end; { Single global instance of TCastleClipboard. Automatically created / destroyed by this unit. } function Clipboard: TCastleClipboard; { Register custom TCastleClipboard implementation, that replaces the global @link(Clipboard). The instance given here becomes owned by this unit (we will free it automatically). } procedure RegisterClipboard(const AClipboard: TCastleClipboard); {$endif read_interface} {$ifdef read_implementation} var FClipboard: TCastleClipboard; function Clipboard: TCastleClipboard; begin if FClipboard = nil then FClipboard := TCastleClipboard.Create; Result := FClipboard; end; procedure RegisterClipboard(const AClipboard: TCastleClipboard); begin FreeAndNil(FClipboard); FClipboard := AClipboard; end; procedure FinalizationClipboard; begin FreeAndNil(FClipboard); end; { TCastleClipboard ----------------------------------------------------------- } { The default clipboard does not communicate with other processes, it's just a trivial container to copy-paste strings between Castle Game Engine edit boxes. } function TCastleClipboard.GetAsText: String; begin Result := FContents; end; procedure TCastleClipboard.SetAsText(const Value: String); begin FContents := Value; end; {$endif read_implementation}
412
0.743385
1
0.743385
game-dev
MEDIA
0.747197
game-dev
0.691849
1
0.691849
hal-uw/cpelide-micro24-artifact
4,547
gem5_multigpu/src/cpu/activity.cc
/* * Copyright (c) 2006 The Regents of The University of Michigan * 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 the copyright holders 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. */ #include "cpu/activity.hh" #include <string> #include "cpu/timebuf.hh" #include "debug/Activity.hh" ActivityRecorder::ActivityRecorder(const std::string &name, int num_stages, int longest_latency, int activity) : _name(name), activityBuffer(longest_latency, 0), longestLatency(longest_latency), activityCount(activity), numStages(num_stages) { stageActive = new bool[numStages]; std::memset(stageActive, 0, numStages); } ActivityRecorder::~ActivityRecorder() { delete[] stageActive; } void ActivityRecorder::activity() { // If we've already recorded activity for this cycle, we don't // want to increment the count any more. if (activityBuffer[0]) { return; } activityBuffer[0] = true; ++activityCount; DPRINTF(Activity, "Activity: %i\n", activityCount); } void ActivityRecorder::advance() { // If there's a 1 in the slot that is about to be erased once the // time buffer advances, then decrement the activityCount. if (activityBuffer[-longestLatency]) { --activityCount; assert(activityCount >= 0); DPRINTF(Activity, "Activity: %i\n", activityCount); if (activityCount == 0) { DPRINTF(Activity, "No activity left!\n"); } } activityBuffer.advance(); } void ActivityRecorder::activateStage(const int idx) { // Increment the activity count if this stage wasn't already active. if (!stageActive[idx]) { ++activityCount; stageActive[idx] = true; DPRINTF(Activity, "Activity: %i\n", activityCount); } else { DPRINTF(Activity, "Stage %i already active.\n", idx); } // assert(activityCount < longestLatency + numStages + 1); } void ActivityRecorder::deactivateStage(const int idx) { // Decrement the activity count if this stage was active. if (stageActive[idx]) { --activityCount; stageActive[idx] = false; DPRINTF(Activity, "Activity: %i\n", activityCount); } else { DPRINTF(Activity, "Stage %i already inactive.\n", idx); } assert(activityCount >= 0); } void ActivityRecorder::reset() { activityCount = 0; std::memset(stageActive, 0, numStages); for (int i = 0; i < longestLatency + 1; ++i) activityBuffer.advance(); } void ActivityRecorder::dump() { for (int i = 0; i <= longestLatency; ++i) { cprintf("[Idx:%i %i] ", i, activityBuffer[-i]); } cprintf("\n"); for (int i = 0; i < numStages; ++i) { cprintf("[Stage:%i %i]\n", i, stageActive[i]); } cprintf("\n"); cprintf("Activity count: %i\n", activityCount); } void ActivityRecorder::validate() { int count = 0; for (int i = 0; i <= longestLatency; ++i) { if (activityBuffer[-i]) { count++; } } for (int i = 0; i < numStages; ++i) { if (stageActive[i]) { count++; } } assert(count == activityCount); }
412
0.838277
1
0.838277
game-dev
MEDIA
0.17056
game-dev
0.855265
1
0.855265
michaelmalaska/aarpg-tutorial
2,524
GUI/pause_menu/inventory/scripts/inventory_ui.gd
class_name InventoryUI extends Control const INVENTORY_SLOT = preload("res://GUI/pause_menu/inventory/inventory_slot.tscn") var focus_index : int = 0 var hovered_item : InventorySlotUI @export var data : InventoryData @onready var inventory_slot_armor: InventorySlotUI = %InventorySlot_Armor @onready var inventory_slot_amulet: InventorySlotUI = %InventorySlot_Amulet @onready var inventory_slot_weapon: InventorySlotUI = %InventorySlot_Weapon @onready var inventory_slot_ring: InventorySlotUI = %InventorySlot_Ring func _ready() -> void: PauseMenu.shown.connect( update_inventory ) PauseMenu.hidden.connect( clear_inventory ) clear_inventory() data.changed.connect( on_inventory_changed ) data.equipment_changed.connect( on_inventory_changed ) pass func clear_inventory() -> void: for c in get_children(): c.set_slot_data( null ) func update_inventory( apply_focus : bool = true ) -> void: clear_inventory() var inventory_slots : Array[ SlotData ] = data.inventory_slots() for i in inventory_slots.size(): var slot : InventorySlotUI = get_child( i ) slot.set_slot_data( inventory_slots[ i ] ) connect_item_signals( slot ) # Update equipment slots var e_slots : Array[ SlotData ] = data.equipment_slots() inventory_slot_armor.set_slot_data( e_slots[ 0 ] ) inventory_slot_weapon.set_slot_data( e_slots[ 1 ] ) inventory_slot_amulet.set_slot_data( e_slots[ 2 ] ) inventory_slot_ring.set_slot_data( e_slots[ 3 ] ) if apply_focus: get_child( 0 ).grab_focus() func item_focused() -> void: for i in get_child_count(): if get_child( i ).has_focus(): focus_index = i return pass func on_inventory_changed() -> void: update_inventory( false ) func connect_item_signals( item : InventorySlotUI ) -> void: if not item.button_up.is_connected( _on_item_drop ): item.button_up.connect( _on_item_drop.bind( item ) ) if not item.mouse_entered.is_connected( _on_item_mouse_entered ): item.mouse_entered.connect( _on_item_mouse_entered.bind( item ) ) if not item.mouse_exited.is_connected( _on_item_mouse_exited ): item.mouse_exited.connect( _on_item_mouse_exited ) pass func _on_item_drop( item : InventorySlotUI ) -> void: if item == null or item == hovered_item or hovered_item == null: return data.swap_items_by_index( item.get_index(), hovered_item.get_index() ) update_inventory( false ) pass func _on_item_mouse_entered( item : InventorySlotUI ) -> void: hovered_item = item pass func _on_item_mouse_exited() -> void: hovered_item = null pass
412
0.864753
1
0.864753
game-dev
MEDIA
0.992825
game-dev
0.905005
1
0.905005
PacktPublishing/Mastering-Cpp-Game-Development
4,474
Chapter07/Include/bullet/BulletSoftBody/btSoftBodySolvers.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_SOFT_BODY_SOLVERS_H #define BT_SOFT_BODY_SOLVERS_H #include "BulletCollision/CollisionShapes/btTriangleIndexVertexArray.h" class btSoftBodyTriangleData; class btSoftBodyLinkData; class btSoftBodyVertexData; class btVertexBufferDescriptor; class btCollisionObject; class btSoftBody; class btSoftBodySolver { public: enum SolverTypes { DEFAULT_SOLVER, CPU_SOLVER, CL_SOLVER, CL_SIMD_SOLVER, DX_SOLVER, DX_SIMD_SOLVER }; protected: int m_numberOfPositionIterations; int m_numberOfVelocityIterations; // Simulation timescale float m_timeScale; public: btSoftBodySolver() : m_numberOfPositionIterations( 10 ), m_timeScale( 1 ) { m_numberOfVelocityIterations = 0; m_numberOfPositionIterations = 5; } virtual ~btSoftBodySolver() { } /** * Return the type of the solver. */ virtual SolverTypes getSolverType() const = 0; /** Ensure that this solver is initialized. */ virtual bool checkInitialized() = 0; /** Optimize soft bodies in this solver. */ virtual void optimize( btAlignedObjectArray< btSoftBody * > &softBodies , bool forceUpdate=false) = 0; /** Copy necessary data back to the original soft body source objects. */ virtual void copyBackToSoftBodies(bool bMove = true) = 0; /** Predict motion of soft bodies into next timestep */ virtual void predictMotion( float solverdt ) = 0; /** Solve constraints for a set of soft bodies */ virtual void solveConstraints( float solverdt ) = 0; /** Perform necessary per-step updates of soft bodies such as recomputing normals and bounding boxes */ virtual void updateSoftBodies() = 0; /** Process a collision between one of the world's soft bodies and another collision object */ virtual void processCollision( btSoftBody *, const struct btCollisionObjectWrapper* ) = 0; /** Process a collision between two soft bodies */ virtual void processCollision( btSoftBody*, btSoftBody* ) = 0; /** Set the number of velocity constraint solver iterations this solver uses. */ virtual void setNumberOfPositionIterations( int iterations ) { m_numberOfPositionIterations = iterations; } /** Get the number of velocity constraint solver iterations this solver uses. */ virtual int getNumberOfPositionIterations() { return m_numberOfPositionIterations; } /** Set the number of velocity constraint solver iterations this solver uses. */ virtual void setNumberOfVelocityIterations( int iterations ) { m_numberOfVelocityIterations = iterations; } /** Get the number of velocity constraint solver iterations this solver uses. */ virtual int getNumberOfVelocityIterations() { return m_numberOfVelocityIterations; } /** Return the timescale that the simulation is using */ float getTimeScale() { return m_timeScale; } #if 0 /** * Add a collision object to be used by the indicated softbody. */ virtual void addCollisionObjectForSoftBody( int clothIdentifier, btCollisionObject *collisionObject ) = 0; #endif }; /** * Class to manage movement of data from a solver to a given target. * This version is abstract. Subclasses will have custom pairings for different combinations. */ class btSoftBodySolverOutput { protected: public: btSoftBodySolverOutput() { } virtual ~btSoftBodySolverOutput() { } /** Output current computed vertex data to the vertex buffers for all cloths in the solver. */ virtual void copySoftBodyToVertexBuffer( const btSoftBody * const softBody, btVertexBufferDescriptor *vertexBuffer ) = 0; }; #endif // #ifndef BT_SOFT_BODY_SOLVERS_H
412
0.873468
1
0.873468
game-dev
MEDIA
0.968518
game-dev
0.861325
1
0.861325
ParadiseSS13/Paradise
5,773
code/modules/mob/living/simple_animal/bot/syndicate_bots.dm
/mob/living/simple_animal/bot/ed209/syndicate name = "Syndicate Sentry Bot" desc = "A syndicate security bot." model = "Guardian" icon = 'icons/mecha/mecha.dmi' icon_state = "darkgygax" radio_channel = "Syndicate" health = 300 maxHealth = 300 declare_arrests = FALSE idcheck = TRUE no_handcuffs = TRUE auto_patrol = TRUE emagged = TRUE faction = list("syndicate") shoot_sound = 'sound/weapons/wave.ogg' anchored = TRUE window_id = "syndiebot" window_name = "Syndicate Bot Interface" var/turf/saved_turf var/stepsound = 'sound/mecha/mechstep.ogg' var/area/syndicate_depot/core/depotarea var/raised_alert = FALSE var/pathing_failed = FALSE var/turf/spawn_turf /mob/living/simple_animal/bot/ed209/syndicate/Initialize(mapload) . = ..() set_weapon() update_icon() spawn_turf = get_turf(src) /mob/living/simple_animal/bot/ed209/syndicate/setup_access() if(access_card) access_card.access = list(ACCESS_SYNDICATE, ACCESS_SYNDICATE_LEADER) prev_access = access_card.access /mob/living/simple_animal/bot/ed209/syndicate/update_icon_state() icon_state = initial(icon_state) /mob/living/simple_animal/bot/ed209/syndicate/turn_on() . = ..() update_icon() /mob/living/simple_animal/bot/ed209/syndicate/turn_off() ..() update_icon() /mob/living/simple_animal/bot/ed209/syndicate/ui_state(mob/user) return GLOB.default_state /mob/living/simple_animal/bot/ed209/syndicate/ui_interact(mob/user, datum/tgui/ui = null) to_chat(user, "<span class='warning'>[src] has no accessible control panel!</span>") return /mob/living/simple_animal/bot/ed209/syndicate/ui_data(mob/user) return /mob/living/simple_animal/bot/ed209/syndicate/ui_act(action, params) return /mob/living/simple_animal/bot/ed209/syndicate/Topic(href, href_list) return /mob/living/simple_animal/bot/ed209/syndicate/retaliate(mob/living/carbon/human/H) if(!H) return target = H set_mode(BOT_HUNT) /mob/living/simple_animal/bot/ed209/syndicate/emag_act(mob/user) to_chat(user, "<span class='warning'>[src] has no card reader slot!</span>") /mob/living/simple_animal/bot/ed209/syndicate/try_chasing_target() . = ..() if(!lost_target) shootAt(target) /mob/living/simple_animal/bot/ed209/syndicate/ed209_ai() var/turf/current_turf = get_turf(src) if(saved_turf && current_turf != saved_turf) playsound(loc, stepsound, 40, 1) if(spawn_turf && !atoms_share_level(src, spawn_turf)) raise_alert("[src] lost in space.") raised_alert = FALSE raise_alert("[src] activated self-destruct.") qdel(src) saved_turf = current_turf switch(mode) if(BOT_IDLE) GLOB.move_manager.stop_looping(src) set_path(null) if(find_new_target()) return if(!mode && auto_patrol) set_mode(BOT_START_PATROL) if(BOT_HUNT) if(frustration >= 8) GLOB.move_manager.stop_looping(src) set_path(null) back_to_idle() return if(!target) back_to_idle() return if(isliving(target) && target.stat == DEAD) back_to_idle() return try_chasing_target(target) if(BOT_START_PATROL) if(find_new_target()) return start_patrol() if(BOT_PATROL) if(find_new_target()) return bot_patrol() else back_to_idle() return /mob/living/simple_animal/bot/ed209/syndicate/find_new_target() if(disabled) return for(var/mob/M in view(7, src)) if(M.invisibility > see_invisible) continue if("syndicate" in M.faction) continue if(M.stat == DEAD) continue if((M.name == oldtarget_name) && (world.time < last_found + 100)) continue target = M oldtarget_name = M.name set_mode(BOT_HUNT) INVOKE_ASYNC(src, PROC_REF(handle_automated_action)) return TRUE return FALSE /mob/living/simple_animal/bot/ed209/syndicate/shootAt(atom/target) if(lastfired && world.time - lastfired < shot_delay) return lastfired = world.time var/obj/item/projectile/P = new projectile(loc) playsound(loc, shoot_sound, 100, 1) P.current = loc P.starting = loc P.firer = src P.firer_source_atom = src P.yo = target.y - loc.y P.xo = target.x - loc.x P.original = target P.fire() /mob/living/simple_animal/bot/ed209/syndicate/explode() if(!QDELETED(src)) if(depotarea) depotarea.list_remove(src, depotarea.guard_list) GLOB.move_manager.stop_looping(src) visible_message("<span class='userdanger'>[src] blows apart!</span>") do_sparks(3, 1, src) new /obj/effect/decal/cleanable/blood/oil(loc) var/obj/structure/mecha_wreckage/gygax/dark/wreck = new /obj/structure/mecha_wreckage/gygax/dark(loc) wreck.name = "sentry bot wreckage" raise_alert("[src] destroyed.") qdel(src) /mob/living/simple_animal/bot/ed209/syndicate/set_weapon() projectile = /obj/item/projectile/bullet/a40mm /mob/living/simple_animal/bot/ed209/syndicate/emp_act(severity) return /mob/living/simple_animal/bot/ed209/syndicate/UnarmedAttack(atom/A) if(!on) return shootAt(A) /mob/living/simple_animal/bot/ed209/syndicate/cuff(mob/living/carbon/C) shootAt(C) /mob/living/simple_animal/bot/ed209/syndicate/stun_attack(mob/living/carbon/C) shootAt(C) /mob/living/simple_animal/bot/ed209/syndicate/speak() return /mob/living/simple_animal/bot/ed209/syndicate/Process_Spacemove(movement_dir = 0, continuous_move = FALSE) return 1 /mob/living/simple_animal/bot/ed209/syndicate/start_patrol() if(tries >= BOT_STEP_MAX_RETRIES) if(!pathing_failed) pathing_failed = TRUE var/failmsg = "Depot: [src] at [loc.x],[loc.y],[loc.z] lacks patrol target." if(istype(patrol_target)) failmsg = "Depot: [src] at [loc.x],[loc.y],[loc.z] cannot reach [patrol_target.x],[patrol_target.y]" log_debug(failmsg) return ..() /mob/living/simple_animal/bot/ed209/syndicate/proc/raise_alert(reason) if(raised_alert) return raised_alert = TRUE if(depotarea) depotarea.increase_alert(reason)
412
0.95505
1
0.95505
game-dev
MEDIA
0.996332
game-dev
0.97542
1
0.97542
ColumbusUtrigas/ColumbusEngine
29,062
Lib/STB/tests/caveview/cave_mesher.c
// This file takes minecraft chunks (decoded by cave_parse) and // uses stb_voxel_render to turn them into vertex buffers. #define STB_GLEXT_DECLARE "glext_list.h" #include "stb_gl.h" #include "stb_image.h" #include "stb_glprog.h" #include "caveview.h" #include "cave_parse.h" #include "stb.h" #include "sdl.h" #include "sdl_thread.h" #include <math.h> //#define VHEIGHT_TEST //#define STBVOX_OPTIMIZED_VHEIGHT #define STBVOX_CONFIG_MODE 1 #define STBVOX_CONFIG_OPENGL_MODELVIEW #define STBVOX_CONFIG_PREFER_TEXBUFFER //#define STBVOX_CONFIG_LIGHTING_SIMPLE #define STBVOX_CONFIG_FOG_SMOOTHSTEP //#define STBVOX_CONFIG_PREMULTIPLIED_ALPHA // this doesn't work properly alpha test without next #define //#define STBVOX_CONFIG_UNPREMULTIPLY // slower, fixes alpha test makes windows & fancy leaves look better //#define STBVOX_CONFIG_TEX1_EDGE_CLAMP #define STBVOX_CONFIG_DISABLE_TEX2 //#define STBVOX_CONFIG_DOWN_TEXLERP_PACKED #define STBVOX_CONFIG_ROTATION_IN_LIGHTING #define STB_VOXEL_RENDER_IMPLEMENTATION #include "stb_voxel_render.h" extern void ods(char *fmt, ...); //#define FANCY_LEAVES // nearly 2x the triangles when enabled (if underground is filled) #define FAST_CHUNK #define IN_PLACE #define SKIP_TERRAIN 0 //#define SKIP_TERRAIN 48 // use to avoid building underground stuff // allows you to see what perf would be like if underground was efficiently culled, // or if you were making a game without underground enum { C_empty, C_solid, C_trans, C_cross, C_water, C_slab, C_stair, C_force, }; unsigned char geom_map[] = { STBVOX_GEOM_empty, STBVOX_GEOM_solid, STBVOX_GEOM_transp, STBVOX_GEOM_crossed_pair, STBVOX_GEOM_solid, STBVOX_GEOM_slab_lower, STBVOX_GEOM_floor_slope_north_is_top, STBVOX_GEOM_force, }; unsigned char minecraft_info[256][7] = { { C_empty, 0,0,0,0,0,0 }, { C_solid, 1,1,1,1,1,1 }, { C_solid, 3,3,3,3,40,2 }, { C_solid, 2,2,2,2,2,2 }, { C_solid, 16,16,16,16,16,16 }, { C_solid, 4,4,4,4,4,4 }, { C_cross, 15,15,15,15 }, { C_solid, 17,17,17,17,17,17 }, // 8 { C_water, 223,223,223,223,223,223 }, { C_water, 223,223,223,223,223,223 }, { C_solid, 255,255,255,255,255,255 }, { C_solid, 255,255,255,255,255,255 }, { C_solid, 18,18,18,18,18,18 }, { C_solid, 19,19,19,19,19,19 }, { C_solid, 32,32,32,32,32,32 }, { C_solid, 33,33,33,33,33,33 }, // 16 { C_solid, 34,34,34,34,34,34 }, { C_solid, 20,20,20,20,21,21 }, #ifdef FANCY_LEAVES { C_force, 52,52,52,52,52,52 }, // leaves #else { C_solid, 53,53,53,53,53,53 }, // leaves #endif { C_solid, 24,24,24,24,24,24 }, { C_trans, 49,49,49,49,49,49 }, // glass { C_solid, 160,160,160,160,160,160 }, { C_solid, 144,144,144,144,144,144 }, { C_solid, 46,45,45,45,62,62 }, // 24 { C_solid, 192,192,192,192, 176,176 }, { C_solid, 74,74,74,74,74,74 }, { C_empty }, // bed { C_empty }, // powered rail { C_empty }, // detector rail { C_solid, 106,108,109,108,108,108 }, { C_empty }, // cobweb=11 { C_cross, 39,39,39,39 }, // 32 { C_cross, 55,55,55,55,0,0 }, { C_solid, 107,108,109,108,108,108 }, { C_empty }, // piston head { C_solid, 64,64,64,64,64,64 }, // various colors { C_empty }, // unused { C_cross, 13,13,13,13,0,0 }, { C_cross, 12,12,12,12,0,0 }, { C_cross, 29,29,29,29,0,0 }, // 40 { C_cross, 28,28,28,28,0,0 }, { C_solid, 23,23,23,23,23,23 }, { C_solid, 22,22,22,22,22,22 }, { C_solid, 5,5,5,5,6,6, }, { C_slab , 5,5,5,5,6,6, }, { C_solid, 7,7,7,7,7,7, }, { C_solid, 8,8,8,8,9,10 }, { C_solid, 35,35,35,35,4,4, }, // 48 //{ C_solid, 36,36,36,36,36,36 }, { C_force, 36,36,36,36,36,36 }, { C_solid, 37,37,37,37,37,37 }, { C_cross, 80,80,80,80,80,80 }, // torch { C_empty }, // fire { C_trans, 65,65,65,65,65,65 }, { C_stair, 4,4,4,4,4,4 }, { C_solid, 26,26,26,27,25,25 }, { C_empty }, // redstone // 56 { C_solid, 50,50,50,50,50,50 }, //{ C_force, 50,50,50,50,50,50 }, { C_solid, 26,26,26,26,26,26 }, { C_solid, 60,59,59,59,43,43 }, { C_cross, 95,95,95,95 }, { C_solid, 2,2,2,2,86,2 }, { C_solid, 44,45,45,45,62,62 }, { C_solid, 61,45,45,45,62,62 }, { C_empty }, // sign // 64 { C_empty }, // door { C_empty }, // ladder { C_empty }, // rail { C_stair, 16,16,16,16,16,16 }, // cobblestone stairs { C_empty }, // sign { C_empty }, // lever { C_empty }, // stone pressure plate { C_empty }, // iron door // 72 { C_empty }, // wooden pressure { C_solid, 51,51,51,51,51,51 }, { C_solid, 51,51,51,51,51,51 }, { C_empty }, { C_empty }, { C_empty }, { C_empty }, // snow on block below, do as half slab? { C_solid, 67,67,67,67,67,67 }, // 80 { C_solid, 66,66,66,66,66,66 }, { C_solid, 70,70,70,70,69,71 }, { C_solid, 72,72,72,72,72,72 }, { C_cross, 73,73,73,73,73,73 }, { C_solid, 74,74,74,74,75,74 }, { C_empty }, // fence { C_solid,119,118,118,118,102,102 }, { C_solid,103,103,103,103,103,103 }, // 88 { C_solid, 104,104,104,104,104,104 }, { C_solid, 105,105,105,105,105,105 }, { C_solid, 167,167,167,167,167,167 }, { C_solid, 120,118,118,118,102,102 }, { C_empty }, // cake { C_empty }, // repeater { C_empty }, // repeater { C_solid, 49,49,49,49,49,49 }, // colored glass // 96 { C_empty }, { C_empty }, { C_solid, 54,54,54,54,54,54 }, { C_solid, 125,125,125,125,125,125 }, { C_solid, 126,126,126,126,126,126 }, { C_empty }, // bars { C_trans, 49,49,49,49,49,49 }, // glass pane { C_solid, 136,136,136,136,137,137 }, // melon // 104 { C_empty }, // pumpkin stem { C_empty }, // melon stem { C_empty }, // vines { C_empty }, // gate { C_stair, 7,7,7,7,7,7, }, // brick stairs { C_stair, 54,54,54,54,54,54 }, // stone brick stairs { C_empty }, // mycelium { C_empty }, // lily pad // 112 { C_solid, 224,224,224,224,224,224 }, { C_empty }, // nether brick fence { C_stair, 224,224,224,224,224,224 }, // nether brick stairs { C_empty }, // nether wart { C_solid, 182,182,182,182,166,183 }, { C_empty }, // brewing stand { C_empty }, // cauldron { C_empty }, // end portal // 120 { C_solid, 159,159,159,159,158,158 }, { C_solid, 175,175,175,175,175,175 }, { C_empty }, // dragon egg { C_solid, 211,211,211,211,211,211 }, { C_solid, 212,212,212,212,212,212 }, { C_solid, 4,4,4,4,4,4, }, // wood double-slab { C_slab , 4,4,4,4,4,4, }, // wood slab { C_empty }, // cocoa // 128 { C_solid, 192,192,192,192,176,176 }, // sandstone stairs { C_solid, 32,32,32,32,32,32 }, // emerald ore { C_solid, 26,26,26,27,25,25 }, // ender chest { C_empty }, { C_empty }, { C_solid, 23,23,23,23,23,23 }, // emerald block { C_solid, 198,198,198,198,198,198 }, // spruce stairs { C_solid, 214,214,214,214,214,214 }, // birch stairs // 136 { C_stair, 199,199,199,199,199,199 }, // jungle stairs { C_empty }, // command block { C_empty }, // beacon { C_slab, 16,16,16,16,16,16 }, // cobblestone wall { C_empty }, // flower pot { C_empty }, // carrot { C_empty }, // potatoes { C_empty }, // wooden button // 144 { C_empty }, // mob head { C_empty }, // anvil { C_solid, 26,26,26,27,25,25 }, // trapped chest { C_empty }, // weighted pressure plate light { C_empty }, // weighted pressure plat eheavy { C_empty }, // comparator inactive { C_empty }, // comparator active { C_empty }, // daylight sensor // 152 { C_solid, 135,135,135,135,135,135 }, // redstone block { C_solid, 0,0,0,0,0,0, }, // nether quartz ore { C_empty }, // hopper { C_solid, 22,22,22,22,22,22 }, // quartz block { C_stair, 22,22,22,22,22,22 }, // quartz stairs { C_empty }, // activator rail { C_solid, 46,45,45,45,62,62 }, // dropper { C_solid, 72,72,72,72,72,72 }, // stained clay // 160 { C_trans, 49,49,49,49,49,49 }, // stained glass pane #ifdef FANCY_LEAVES { C_force, 52,52,52,52,52,52 }, // leaves #else { C_solid, 53,53,53,53,53,53 }, // acacia leaves #endif { C_solid, 20,20,20,20,21,21 }, // acacia tree { C_solid, 199,199,199,199,199,199 }, // acacia wood stairs { C_solid, 198,198,198,198,198,198 }, // dark oak stairs { C_solid, 146,146,146,146,146,146 }, // slime block { C_solid, 176,176,176,176,176,176 }, // red sandstone { C_solid, 176,176,176,176,176,176 }, // red sandstone // 168 { C_empty }, { C_empty }, { C_empty }, { C_empty }, { C_solid, 72,72,72,72,72,72 }, // hardened clay { C_empty }, { C_empty }, { C_empty }, // 176 { C_empty }, { C_empty }, { C_solid, 176,176,176,176,176,176 }, // red sandstone }; unsigned char minecraft_tex1_for_blocktype[256][6]; unsigned char effective_blocktype[256]; unsigned char minecraft_color_for_blocktype[256][6]; unsigned char minecraft_geom_for_blocktype[256]; uint8 build_buffer[BUILD_BUFFER_SIZE]; uint8 face_buffer[FACE_BUFFER_SIZE]; //GLuint vbuf, fbuf, fbuf_tex; //unsigned char tex1_for_blocktype[256][6]; //unsigned char blocktype[34][34][257]; //unsigned char lighting[34][34][257]; // a superchunk is 64x64x256, with the border blocks computed as well, // which means we need 4x4 chunks plus 16 border chunks plus 4 corner chunks #define SUPERCHUNK_X 4 #define SUPERCHUNK_Y 4 unsigned char remap_data[16][16]; unsigned char remap[256]; unsigned char rotate_data[4] = { 1,3,2,0 }; void convert_fastchunk_inplace(fast_chunk *fc) { int i; int num_blocks=0, step=0; unsigned char rot[4096]; #ifndef IN_PLACE unsigned char *storage; #endif memset(rot, 0, 4096); for (i=0; i < 16; ++i) num_blocks += fc->blockdata[i] != NULL; #ifndef IN_PLACE storage = malloc(16*16*16*2 * num_blocks); #endif for (i=0; i < 16; ++i) { if (fc->blockdata[i]) { int o=0; unsigned char *bd,*dd,*lt,*sky; unsigned char *out, *outb; // this ordering allows us to determine which data we can safely overwrite for in-place processing bd = fc->blockdata[i]; dd = fc->data[i]; lt = fc->light[i]; sky = fc->skylight[i]; #ifdef IN_PLACE out = bd; #else out = storage + 16*16*16*2*step; #endif // bd is written in place, but also reads from dd for (o=0; o < 16*16*16/2; o += 1) { unsigned char v1,v2; unsigned char d = dd[o]; v1 = bd[o*2+0]; v2 = bd[o*2+1]; if (remap[v1]) { //unsigned char d = bd[o] & 15; v1 = remap_data[remap[v1]][d&15]; rot[o*2+0] = rotate_data[d&3]; } else v1 = effective_blocktype[v1]; if (remap[v2]) { //unsigned char d = bd[o] >> 4; v2 = remap_data[remap[v2]][d>>4]; rot[o*2+1] = rotate_data[(d>>4)&3]; } else v2 = effective_blocktype[v2]; out[o*2+0] = v1; out[o*2+1] = v2; } // this reads from lt & sky #ifndef IN_PLACE outb = out + 16*16*16; ++step; #endif // MC used to write in this order and it makes it possible to compute in-place if (dd < sky && sky < lt) { // @TODO go this path always if !IN_PLACE #ifdef IN_PLACE outb = dd; #endif for (o=0; o < 16*16*16/2; ++o) { int bright; bright = (lt[o]&15)*12 + 15 + (sky[o]&15)*16; if (bright > 255) bright = 255; if (bright < 32) bright = 32; outb[o*2+0] = STBVOX_MAKE_LIGHTING_EXT((unsigned char) bright, (rot[o*2+0]&3)); bright = (lt[o]>>4)*12 + 15 + (sky[o]>>4)*16; if (bright > 255) bright = 255; if (bright < 32) bright = 32; outb[o*2+1] = STBVOX_MAKE_LIGHTING_EXT((unsigned char) bright, (rot[o*2+1]&3)); } } else { // @TODO: if blocktype is in between others, this breaks; need to find which side has two pointers, and use that // overwrite rot[] array, then copy out #ifdef IN_PLACE outb = (dd < sky) ? dd : sky; if (lt < outb) lt = outb; #endif for (o=0; o < 16*16*16/2; ++o) { int bright; bright = (lt[o]&15)*12 + 15 + (sky[o]&15)*16; if (bright > 255) bright = 255; if (bright < 32) bright = 32; rot[o*2+0] = STBVOX_MAKE_LIGHTING_EXT((unsigned char) bright, (rot[o*2+0]&3)); bright = (lt[o]>>4)*12 + 15 + (sky[o]>>4)*16; if (bright > 255) bright = 255; if (bright < 32) bright = 32; rot[o*2+1] = STBVOX_MAKE_LIGHTING_EXT((unsigned char) bright, (rot[o*2+1]&3)); } memcpy(outb, rot, 4096); fc->data[i] = outb; } #ifndef IN_PLACE fc->blockdata[i] = out; fc->data[i] = outb; #endif } } #ifndef IN_PLACE free(fc->pointer_to_free); fc->pointer_to_free = storage; #endif } void make_converted_fastchunk(fast_chunk *fc, int x, int y, int segment, uint8 *sv_blocktype, uint8 *sv_lighting) { int z; assert(fc == NULL || (fc->refcount > 0 && fc->refcount < 64)); if (fc == NULL || fc->blockdata[segment] == NULL) { for (z=0; z < 16; ++z) { sv_blocktype[z] = C_empty; sv_lighting[z] = 255; } } else { unsigned char *block = fc->blockdata[segment]; unsigned char *data = fc->data[segment]; y = 15-y; for (z=0; z < 16; ++z) { sv_blocktype[z] = block[z*256 + y*16 + x]; sv_lighting [z] = data [z*256 + y*16 + x]; } } } #define CHUNK_CACHE 64 typedef struct { int valid; int chunk_x, chunk_y; fast_chunk *fc; } cached_converted_chunk; cached_converted_chunk chunk_cache[CHUNK_CACHE][CHUNK_CACHE]; int cache_size = CHUNK_CACHE; void reset_cache_size(int size) { int i,j; for (j=size; j < cache_size; ++j) { for (i=size; i < cache_size; ++i) { cached_converted_chunk *ccc = &chunk_cache[j][i]; if (ccc->valid) { if (ccc->fc) { free(ccc->fc->pointer_to_free); free(ccc->fc); ccc->fc = NULL; } ccc->valid = 0; } } } cache_size = size; } // this must be called inside mutex void deref_fastchunk(fast_chunk *fc) { if (fc) { assert(fc->refcount > 0); --fc->refcount; if (fc->refcount == 0) { free(fc->pointer_to_free); free(fc); } } } SDL_mutex * chunk_cache_mutex; SDL_mutex * chunk_get_mutex; void lock_chunk_get_mutex(void) { SDL_LockMutex(chunk_get_mutex); } void unlock_chunk_get_mutex(void) { SDL_UnlockMutex(chunk_get_mutex); } fast_chunk *get_converted_fastchunk(int chunk_x, int chunk_y) { int slot_x = (chunk_x & (cache_size-1)); int slot_y = (chunk_y & (cache_size-1)); fast_chunk *fc; cached_converted_chunk *ccc; SDL_LockMutex(chunk_cache_mutex); ccc = &chunk_cache[slot_y][slot_x]; if (ccc->valid) { if (ccc->chunk_x == chunk_x && ccc->chunk_y == chunk_y) { fast_chunk *fc = ccc->fc; if (fc) ++fc->refcount; SDL_UnlockMutex(chunk_cache_mutex); return fc; } if (ccc->fc) { deref_fastchunk(ccc->fc); ccc->fc = NULL; ccc->valid = 0; } } SDL_UnlockMutex(chunk_cache_mutex); fc = get_decoded_fastchunk_uncached(chunk_x, -chunk_y); if (fc) convert_fastchunk_inplace(fc); SDL_LockMutex(chunk_cache_mutex); // another thread might have updated it, so before we overwrite it... if (ccc->fc) { deref_fastchunk(ccc->fc); ccc->fc = NULL; } if (fc) fc->refcount = 1; // 1 in the cache ccc->chunk_x = chunk_x; ccc->chunk_y = chunk_y; ccc->valid = 1; if (fc) ++fc->refcount; ccc->fc = fc; SDL_UnlockMutex(chunk_cache_mutex); return fc; } void make_map_segment_for_superchunk_preconvert(int chunk_x, int chunk_y, int segment, fast_chunk *fc_table[4][4], uint8 sv_blocktype[34][34][18], uint8 sv_lighting[34][34][18]) { int a,b; assert((chunk_x & 1) == 0); assert((chunk_y & 1) == 0); for (b=-1; b < 3; ++b) { for (a=-1; a < 3; ++a) { int xo = a*16+1; int yo = b*16+1; int x,y; fast_chunk *fc = fc_table[b+1][a+1]; for (y=0; y < 16; ++y) for (x=0; x < 16; ++x) if (xo+x >= 0 && xo+x < 34 && yo+y >= 0 && yo+y < 34) make_converted_fastchunk(fc,x,y, segment, sv_blocktype[xo+x][yo+y], sv_lighting[xo+x][yo+y]); } } } // build 1 mesh covering 2x2 chunks void build_chunk(int chunk_x, int chunk_y, fast_chunk *fc_table[4][4], raw_mesh *rm) { int a,b,z; stbvox_input_description *map; #ifdef VHEIGHT_TEST unsigned char vheight[34][34][18]; #endif #ifndef STBVOX_CONFIG_DISABLE_TEX2 unsigned char tex2_choice[34][34][18]; #endif assert((chunk_x & 1) == 0); assert((chunk_y & 1) == 0); rm->cx = chunk_x; rm->cy = chunk_y; stbvox_set_input_stride(&rm->mm, 34*18, 18); assert(rm->mm.input.geometry == NULL); map = stbvox_get_input_description(&rm->mm); map->block_tex1_face = minecraft_tex1_for_blocktype; map->block_color_face = minecraft_color_for_blocktype; map->block_geometry = minecraft_geom_for_blocktype; stbvox_reset_buffers(&rm->mm); stbvox_set_buffer(&rm->mm, 0, 0, rm->build_buffer, BUILD_BUFFER_SIZE); stbvox_set_buffer(&rm->mm, 0, 1, rm->face_buffer , FACE_BUFFER_SIZE); map->blocktype = &rm->sv_blocktype[1][1][1]; // this is (0,0,0), but we need to be able to query off the edges map->lighting = &rm->sv_lighting[1][1][1]; // fill in the top two rows of the buffer for (a=0; a < 34; ++a) { for (b=0; b < 34; ++b) { rm->sv_blocktype[a][b][16] = 0; rm->sv_lighting [a][b][16] = 255; rm->sv_blocktype[a][b][17] = 0; rm->sv_lighting [a][b][17] = 255; } } #ifndef STBVOX_CONFIG_DISABLE_TEX2 for (a=0; a < 34; ++a) { for (b=0; b < 34; ++b) { int px = chunk_x*16 + a - 1; int py = chunk_y*16 + b - 1; float dist = (float) sqrt(px*px + py*py); float s1 = (float) sin(dist / 16), s2, s3; dist = (float) sqrt((px-80)*(px-80) + (py-50)*(py-50)); s2 = (float) sin(dist / 11); for (z=0; z < 18; ++z) { s3 = (float) sin(z * 3.141592 / 8); s3 = s1*s2*s3; tex2_choice[a][b][z] = 63 & (int) stb_linear_remap(s3,-1,1, -20,83); } } } #endif for (z=256-16; z >= SKIP_TERRAIN; z -= 16) { int z0 = z; int z1 = z+16; if (z1 == 256) z1 = 255; make_map_segment_for_superchunk_preconvert(chunk_x, chunk_y, z >> 4, fc_table, rm->sv_blocktype, rm->sv_lighting); map->blocktype = &rm->sv_blocktype[1][1][1-z]; // specify location of 0,0,0 so that accessing z0..z1 gets right data map->lighting = &rm->sv_lighting[1][1][1-z]; #ifndef STBVOX_CONFIG_DISABLE_TEX2 map->tex2 = &tex2_choice[1][1][1-z]; #endif #ifdef VHEIGHT_TEST // hacky test of vheight for (a=0; a < 34; ++a) { for (b=0; b < 34; ++b) { int c; for (c=0; c < 17; ++c) { if (rm->sv_blocktype[a][b][c] != 0 && rm->sv_blocktype[a][b][c+1] == 0) { // topmost block vheight[a][b][c] = rand() & 255; rm->sv_blocktype[a][b][c] = 168; } else if (c > 0 && rm->sv_blocktype[a][b][c] != 0 && rm->sv_blocktype[a][b][c-1] == 0) { // bottommost block vheight[a][b][c] = ((rand() % 3) << 6) + ((rand() % 3) << 4) + ((rand() % 3) << 2) + (rand() % 3); rm->sv_blocktype[a][b][c] = 169; } } vheight[a][b][c] = STBVOX_MAKE_VHEIGHT(2,2,2,2); // flat top } } map->vheight = &vheight[1][1][1-z]; #endif { stbvox_set_input_range(&rm->mm, 0,0,z0, 32,32,z1); stbvox_set_default_mesh(&rm->mm, 0); stbvox_make_mesh(&rm->mm); } // copy the bottom two rows of data up to the top for (a=0; a < 34; ++a) { for (b=0; b < 34; ++b) { rm->sv_blocktype[a][b][16] = rm->sv_blocktype[a][b][0]; rm->sv_blocktype[a][b][17] = rm->sv_blocktype[a][b][1]; rm->sv_lighting [a][b][16] = rm->sv_lighting [a][b][0]; rm->sv_lighting [a][b][17] = rm->sv_lighting [a][b][1]; } } } stbvox_set_mesh_coordinates(&rm->mm, chunk_x*16, chunk_y*16, 0); stbvox_get_transform(&rm->mm, rm->transform); stbvox_set_input_range(&rm->mm, 0,0,0, 32,32,255); stbvox_get_bounds(&rm->mm, rm->bounds); rm->num_quads = stbvox_get_quad_count(&rm->mm, 0); } int next_blocktype = 255; unsigned char mc_rot[4] = { 1,3,2,0 }; // create blocktypes with rotation baked into type... // @TODO we no longer need this now that we store rotations // in lighting void build_stair_rotations(int blocktype, unsigned char *map) { int i; // use the existing block type for floor stairs; allocate a new type for ceil stairs for (i=0; i < 6; ++i) { minecraft_color_for_blocktype[next_blocktype][i] = minecraft_color_for_blocktype[blocktype][i]; minecraft_tex1_for_blocktype [next_blocktype][i] = minecraft_tex1_for_blocktype [blocktype][i]; } minecraft_geom_for_blocktype[next_blocktype] = (unsigned char) STBVOX_MAKE_GEOMETRY(STBVOX_GEOM_ceil_slope_north_is_bottom, 0, 0); minecraft_geom_for_blocktype[ blocktype] = (unsigned char) STBVOX_MAKE_GEOMETRY(STBVOX_GEOM_floor_slope_north_is_top, 0, 0); for (i=0; i < 4; ++i) { map[0+i+8] = map[0+i] = blocktype; map[4+i+8] = map[4+i] = next_blocktype; } --next_blocktype; } void build_wool_variations(int bt, unsigned char *map) { int i,k; unsigned char tex[16] = { 64, 210, 194, 178, 162, 146, 130, 114, 225, 209, 193, 177, 161, 145, 129, 113 }; for (i=0; i < 16; ++i) { if (i == 0) map[i] = bt; else { map[i] = next_blocktype; for (k=0; k < 6; ++k) { minecraft_tex1_for_blocktype[next_blocktype][k] = tex[i]; } minecraft_geom_for_blocktype[next_blocktype] = minecraft_geom_for_blocktype[bt]; --next_blocktype; } } } void build_wood_variations(int bt, unsigned char *map) { int i,k; unsigned char tex[4] = { 5, 198, 214, 199 }; for (i=0; i < 4; ++i) { if (i == 0) map[i] = bt; else { map[i] = next_blocktype; for (k=0; k < 6; ++k) { minecraft_tex1_for_blocktype[next_blocktype][k] = tex[i]; } minecraft_geom_for_blocktype[next_blocktype] = minecraft_geom_for_blocktype[bt]; --next_blocktype; } } map[i] = map[i-1]; ++i; for (; i < 16; ++i) map[i] = bt; } void remap_in_place(int bt, int rm) { int i; remap[bt] = rm; for (i=0; i < 16; ++i) remap_data[rm][i] = bt; } void mesh_init(void) { int i; chunk_cache_mutex = SDL_CreateMutex(); chunk_get_mutex = SDL_CreateMutex(); for (i=0; i < 256; ++i) { memcpy(minecraft_tex1_for_blocktype[i], minecraft_info[i]+1, 6); effective_blocktype[i] = (minecraft_info[i][0] == C_empty ? 0 : i); minecraft_geom_for_blocktype[i] = geom_map[minecraft_info[i][0]]; } //effective_blocktype[50] = 0; // delete torches for (i=0; i < 6*256; ++i) { if (minecraft_tex1_for_blocktype[0][i] == 40) minecraft_color_for_blocktype[0][i] = 38 | 64; // apply to tex1 if (minecraft_tex1_for_blocktype[0][i] == 39) minecraft_color_for_blocktype[0][i] = 39 | 64; // apply to tex1 if (minecraft_tex1_for_blocktype[0][i] == 105) minecraft_color_for_blocktype[0][i] = 63; // emissive if (minecraft_tex1_for_blocktype[0][i] == 212) minecraft_color_for_blocktype[0][i] = 63; // emissive if (minecraft_tex1_for_blocktype[0][i] == 80) minecraft_color_for_blocktype[0][i] = 63; // emissive } for (i=0; i < 6; ++i) { minecraft_color_for_blocktype[172][i] = 47 | 64; // apply to tex1 minecraft_color_for_blocktype[178][i] = 47 | 64; // apply to tex1 minecraft_color_for_blocktype[18][i] = 39 | 64; // green minecraft_color_for_blocktype[161][i] = 37 | 64; // green minecraft_color_for_blocktype[10][i] = 63; // emissive lava minecraft_color_for_blocktype[11][i] = 63; // emissive //minecraft_color_for_blocktype[56][i] = 63; // emissive diamond minecraft_color_for_blocktype[48][i] = 63; // emissive dungeon } #ifdef VHEIGHT_TEST effective_blocktype[168] = 168; minecraft_tex1_for_blocktype[168][0] = 1; minecraft_tex1_for_blocktype[168][1] = 1; minecraft_tex1_for_blocktype[168][2] = 1; minecraft_tex1_for_blocktype[168][3] = 1; minecraft_tex1_for_blocktype[168][4] = 1; minecraft_tex1_for_blocktype[168][5] = 1; minecraft_geom_for_blocktype[168] = STBVOX_GEOM_floor_vheight_12; effective_blocktype[169] = 169; minecraft_tex1_for_blocktype[169][0] = 1; minecraft_tex1_for_blocktype[169][1] = 1; minecraft_tex1_for_blocktype[169][2] = 1; minecraft_tex1_for_blocktype[169][3] = 1; minecraft_tex1_for_blocktype[169][4] = 1; minecraft_tex1_for_blocktype[169][5] = 1; minecraft_geom_for_blocktype[169] = STBVOX_GEOM_ceil_vheight_03; #endif remap[53] = 1; remap[67] = 2; remap[108] = 3; remap[109] = 4; remap[114] = 5; remap[136] = 6; remap[156] = 7; for (i=0; i < 256; ++i) if (remap[i]) build_stair_rotations(i, remap_data[remap[i]]); remap[35] = 8; build_wool_variations(35, remap_data[remap[35]]); remap[5] = 11; build_wood_variations(5, remap_data[remap[5]]); // set the remap flags for these so they write the rotation values remap_in_place(54, 9); remap_in_place(146, 10); } // Timing stats while optimizing the single-threaded builder // 32..-32, 32..-32, SKIP_TERRAIN=0, !FANCY_LEAVES on 'mcrealm' data set // 6.27s - reblocked to do 16 z at a time instead of 256 (still using 66x66x258), 4 meshes in parallel // 5.96s - reblocked to use FAST_CHUNK (no intermediate data structure) // 5.45s - unknown change, or previous measurement was wrong // 6.12s - use preconverted data, not in-place // 5.91s - use preconverted, in-place // 5.34s - preconvert, in-place, avoid dependency chain (suggested by ryg) // 5.34s - preconvert, in-place, avoid dependency chain, use bit-table instead of byte-table // 5.50s - preconvert, in-place, branchless // 6.42s - non-preconvert, avoid dependency chain (not an error) // 5.40s - non-preconvert, w/dependency chain (same as earlier) // 5.50s - non-FAST_CHUNK, reblocked outer loop for better cache reuse // 4.73s - FAST_CHUNK non-preconvert, reblocked outer loop // 4.25s - preconvert, in-place, reblocked outer loop // 4.18s - preconvert, in-place, unrolled again // 4.10s - 34x34 1 mesh instead of 66x66 and 4 meshes (will make it easier to do multiple threads) // 4.83s - building bitmasks but not using them (2 bits per block, one if empty, one if solid) // 5.16s - using empty bitmasks to early out // 5.01s - using solid & empty bitmasks to early out - "foo" // 4.64s - empty bitmask only, test 8 at a time, then test geom // 4.72s - empty bitmask only, 8 at a time, then test bits // 4.46s - split bitmask building into three loops (each byte is separate) // 4.42s - further optimize computing bitmask // 4.58s - using solid & empty bitmasks to early out, same as "foo" but faster bitmask building // 4.12s - using solid & empty bitmasks to efficiently test neighbors // 4.04s - using 16-bit fetches (not endian-independent) // - note this is first place that beats previous best '4.10s - 34x34 1 mesh' // 4.30s - current time with bitmasks disabled again (note was 4.10s earlier) // 3.95s - bitmasks enabled again, no other changes // 4.00s - current time with bitmasks disabled again, no other changes -- wide variation that is time dependent? // (note that most of the numbers listed here are median of 3 values already) // 3.98s - bitmasks enabled // Bitmasks removed from the code as not worth the complexity increase // Raw data for Q&A: // // 26% parsing & loading minecraft files (4/5ths of which is zlib decode) // 39% building mesh from stb input format // 18% converting from minecraft blocks to stb blocks // 9% reordering from minecraft axis order to stb axis order // 7% uploading vertex buffer to OpenGL
412
0.940527
1
0.940527
game-dev
MEDIA
0.25466
game-dev
0.537166
1
0.537166
kailaix/ADCME.jl
11,989
src/gan.jl
export GAN, jsgan, klgan, wgan, rklgan, lsgan, sample, predict, dcgan_generator, dcgan_discriminator, wgan_stable mutable struct GAN latent_dim::Int64 batch_size::Int64 dim::Int64 dat::PyObject generator::Union{Missing, Function} discriminator::Union{Missing, Function} loss::Function d_vars::Union{Missing,Array{PyObject}} g_vars::Union{Missing,Array{PyObject}} d_loss::Union{Missing,PyObject} g_loss::Union{Missing,PyObject} is_training::Union{Missing,PyObject, Bool} update::Union{Missing,Array{PyObject}} fake_data::Union{Missing,PyObject} true_data::Union{Missing,PyObject} ganid::String noise::Union{Missing,PyObject} ids::Union{Missing,PyObject} STORAGE::Dict{String, Any} end """ build!(gan::GAN) Builds the GAN instances. This function returns `gan` for convenience. """ function build!(gan::GAN) gan.noise = placeholder(get_dtype(gan.dat), shape=(gan.batch_size, gan.latent_dim)) gan.ids = placeholder(Int32, shape=(gan.batch_size,)) variable_scope("generator_$(gan.ganid)") do gan.fake_data = gan.generator(gan.noise, gan) end gan.true_data = tf.gather(gan.dat,gan.ids-1) variable_scope("discriminator_$(gan.ganid)") do gan.d_loss, gan.g_loss = gan.loss(gan) end gan.d_vars = Array{PyObject}(get_collection("discriminator_$(gan.ganid)")) gan.d_vars = length(gan.d_vars)>0 ? gan.d_vars : missing gan.g_vars = Array{PyObject}(get_collection("generator_$(gan.ganid)")) gan.g_vars = length(gan.g_vars)>0 ? gan.g_vars : missing gan.update = Array{PyCall.PyObject}(get_collection(UPDATE_OPS)) gan.update = length(gan.update)>0 ? gan.update : missing # gan.STORAGE["d_grad_magnitude"] = gradient_magnitude(gan.d_loss, gan.d_vars) # gan.STORAGE["g_grad_magnitude"] = gradient_magnitude(gan.g_loss, gan.g_vars) gan end @doc raw""" GAN(dat::Union{Array,PyObject}, generator::Function, discriminator::Function, loss::Union{Missing, Function}=missing; latent_dim::Union{Missing, Int64}=missing, batch_size::Int64=32) Creates a GAN instance. - `dat` ``\in \mathbb{R}^{n\times d}`` is the training data for the GAN, where ``n`` is the number of training data, and ``d`` is the dimension per training data. - `generator```:\mathbb{R}^{d'} \rightarrow \mathbb{R}^d`` is the generator function, ``d'`` is the hidden dimension. - `discriminator```:\mathbb{R}^{d} \rightarrow \mathbb{R}`` is the discriminator function. - `loss` is the loss function. See [`klgan`](@ref), [`rklgan`](@ref), [`wgan`](@ref), [`lsgan`](@ref) for examples. - `latent_dim` (default=``d``, the same as output dimension) is the latent dimension. - `batch_size` (default=32) is the batch size in training. # Example: Constructing a GAN ```julia dat = rand(10000,10) generator = (z, gan)->10*z discriminator = (x, gan)->sum(x) gan = GAN(dat, generator, discriminator, "wgan_stable") ``` # Example: Learning a Gaussian random variable ```julia using ADCME using PyPlot using Distributions dat = randn(10000, 1) * 0.5 .+ 3.0 function gen(z, gan) ae(z, [20,20,20,1], "generator_$(gan.ganid)", activation = "relu") end function disc(x, gan) squeeze(ae(x, [20,20,20,1], "discriminator_$(gan.ganid)", activation = "relu")) end gan = GAN(dat, gen, disc, g->wgan_stable(g, 0.001); latent_dim = 10) dopt = AdamOptimizer(0.0002, beta1=0.5, beta2=0.9).minimize(gan.d_loss, var_list=gan.d_vars) gopt = AdamOptimizer(0.0002, beta1=0.5, beta2=0.9).minimize(gan.g_loss, var_list=gan.g_vars) sess = Session(); init(sess) for i = 1:5000 batch_x = rand(1:10000, 32) batch_z = randn(32, 10) for n_critic = 1:1 global _, dl = run(sess, [dopt, gan.d_loss], feed_dict=Dict(gan.ids=>batch_x, gan.noise=>batch_z)) end _, gl, gm, dm, gp = run(sess, [gopt, gan.g_loss, gan.STORAGE["g_grad_magnitude"], gan.STORAGE["d_grad_magnitude"], gan.STORAGE["gradient_penalty"]], feed_dict=Dict(gan.ids=>batch_x, gan.noise=>batch_z)) mod(i, 100)==0 && (@info i, dl, gl, gm, dm, gp) end hist(run(sess, squeeze(rand(gan,10000))), bins=50, density = true) nm = Normal(3.0,0.5) x0 = 1.0:0.01:5.0 y0 = pdf.(nm, x0) plot(x0, y0, "g") ``` """ function GAN(dat::Union{Array,PyObject}, generator::Function, discriminator::Function, loss::Union{Missing, Function, String}=missing; latent_dim::Union{Missing, Int64}=missing, batch_size::Int64=32) dim = size(dat, 2) dat = convert_to_tensor(dat) if ismissing(latent_dim) latent_dim=dim end if ismissing(loss) loss = "jsgan" end if isa(loss, String) if loss=="jsgan" loss = jsgan elseif loss=="klgan" loss = klgan elseif loss=="wgan" loss = wgan elseif loss=="wgan_stable" loss = wgan_stable elseif loss=="rklgan" loss = rklgan elseif loss=="lsgan" loss = lsgan else error("loss function $loss not found!") end end gan = GAN(latent_dim, batch_size, dim, dat, generator, discriminator, loss, missing, missing, missing, missing, ADCME.options.training.training, missing, missing, missing, randstring(), missing, missing, Dict()) build!(gan) gan end GAN(dat::Array{T}) where T<:Real = GAN(constant(dat)) function Base.:show(io::IO, gan::GAN) yes_or_no = x->ismissing(x) ? "✘" : "✔️" print( """ ( Generative Adversarial Network -- $(gan.ganid) ) ================================================== $(gan.latent_dim) D $(gan.dim) D (Latent Space)---->(Data Space) batch_size = $(gan.batch_size) loss function: $(gan.loss) generator: $(gan.generator) discriminator: $(gan.discriminator) d_vars ... $(yes_or_no(gan.d_vars)) g_vars ... $(yes_or_no(gan.g_vars)) d_loss ... $(yes_or_no(gan.d_loss)) g_loss ... $(yes_or_no(gan.g_loss)) update ... $(yes_or_no(gan.update)) true_data ... $(size(gan.true_data)) fake_data ... $(size(gan.fake_data)) is_training... Placeholder (Bool), $(gan.is_training) noise ... Placeholder (Float64) of size $(size(gan.noise)) ids ... Placeholder (Int32) of size $(size(gan.ids)) """ ) end ##################### GAN Library ##################### """ klgan(gan::GAN) Computes the KL-divergence GAN loss function. """ function klgan(gan::GAN) P, Q = gan.true_data, gan.fake_data D_real = gan.discriminator(P, gan) D_fake = gan.discriminator(Q, gan) D_loss = -mean(log(D_real) + log(1-D_fake)) G_loss = mean(log((1-D_fake)/D_fake)) D_loss, G_loss end """ jsgan(gan::GAN) Computes the vanilla GAN loss function. """ function jsgan(gan::GAN) P, Q = gan.true_data, gan.fake_data D_real = gan.discriminator(P, gan) D_fake = gan.discriminator(Q, gan) D_loss = -mean(log(D_real) + log(1-D_fake)) G_loss = -mean(log(D_fake)) D_loss, G_loss end """ wgan(gan::GAN) Computes the Wasserstein GAN loss function. """ function wgan(gan::GAN) P, Q = gan.true_data, gan.fake_data D_real = gan.discriminator(P, gan) D_fake = gan.discriminator(Q, gan) D_loss = mean(D_fake)-mean(D_real) G_loss = -mean(D_fake) D_loss, G_loss end @doc raw""" wgan_stable(gan::GAN, λ::Float64) Returns the discriminator and generator loss for the Wasserstein GAN loss with penalty parameter $\lambda$ The objective function is ```math L = E_{\tilde x\sim P_g} [D(\tilde x)] - E_{x\sim P_r} [D(x)] + \lambda E_{\hat x\sim P_{\hat x}}[(||\nabla_{\hat x}D(\hat x)||^2-1)^2] ``` """ function wgan_stable(gan::GAN, λ::Float64=1.0) real_data, fake_data = gan.true_data, gan.fake_data @assert length(size(real_data))==2 @assert length(size(fake_data))==2 D_logits = gan.discriminator(real_data, gan) D_logits_ = gan.discriminator(fake_data, gan) g_loss = -mean(D_logits_) d_loss_real = -mean(D_logits) d_loss_fake = tf.reduce_mean(D_logits_) α = tf.random_uniform( shape=(gan.batch_size, 1), minval=0., maxval=1., dtype=tf.float64 ) differences = fake_data - real_data interpolates = real_data + α .* differences # nb x dim d_inter = gan.discriminator(interpolates, gan) @assert length(size(d_inter))==1 gradients = tf.gradients(d_inter, interpolates)[1] # ∇D(xt), nb x dim slopes = sqrt(sum(gradients^2, dims=2)) # ||∇D(xt)||, (nb,) gradient_penalty = mean((slopes-1.)^2) d_loss = d_loss_fake + d_loss_real + λ * gradient_penalty gan.STORAGE["gradient_penalty"] = mean(slopes) return d_loss, g_loss end """ rklgan(gan::GAN) Computes the reverse KL-divergence GAN loss function. """ function rklgan(gan::GAN) P, Q = gan.true_data, gan.fake_data D_real = gan.discriminator(P, gan) D_fake = gan.discriminator(Q, gan) G_loss = mean(log((1-D_fake)/D_fake)) D_loss = -mean(log(D_fake)+log(1-D_real)) D_loss, G_loss end """ lsgan(gan::GAN) Computes the least square GAN loss function. """ function lsgan(gan::GAN) P, Q = gan.true_data, gan.fake_data D_real = gan.discriminator(P, gan) D_fake = gan.discriminator(Q, gan) D_loss = mean((D_real-1)^2+D_fake^2) G_loss = mean((D_fake-1)^2) D_loss, G_loss end ####################################################### """ sample(gan::GAN, n::Int64) rand(gan::GAN, n::Int64) Samples `n` instances from `gan`. """ function sample(gan::GAN, n::Int64) local out @info "Using a normal latent vector" noise = constant(randn(n, gan.latent_dim)) variable_scope("generator_$(gan.ganid)") do out = gan.generator(noise, gan) end out end Base.:rand(gan::GAN) = squeeze(sample(gan, 1), dims=1) Base.:rand(gan::GAN, n::Int64) = sample(gan, n) """ predict(gan::GAN, input::Union{PyObject, Array}) Predicts the GAN `gan` output given input `input`. """ function predict(gan::GAN, input::Union{PyObject, Array}) local out flag = false if length(size(input))==1 flag = true input = reshape(input, 1, length(input)) end input = convert_to_tensor(input) variable_scope("generator_$(gan.ganid)", initializer=random_uniform_initializer(0.0,1e-3)) do out = gan.generator(input, gan) end if flag; out = squeeze(out); end out end # adapted from https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3_NeuralNetworks/dcgan.py function dcgan_generator(x::PyObject, n::Int64=1) if length(size(x))!=2 error("ADCME: input must have rank 2, rank $(length(size(x))) received") end variable_scope("generator", reuse=AUTO_REUSE) do # TensorFlow Layers automatically create variables and calculate their # shape, based on the input. x = tf.layers.dense(x, units=6n * 6n * 128) x = tf.nn.tanh(x) # Reshape to a 4-D array of images: (batch, height, width, channels) # New shape: (batch, 6, 6, 128) x = tf.reshape(x, shape=[-1, 6n, 6n, 128]) # Deconvolution, image shape: (batch, 14, 14, 64) x = tf.layers.conv2d_transpose(x, 64, 4, strides=2) # Deconvolution, image shape: (batch, 28, 28, 1) x = tf.layers.conv2d_transpose(x, 1, 2, strides=2) # Apply sigmoid to clip values between 0 and 1 x = tf.nn.sigmoid(x) end return squeeze(x) end function dcgan_discriminator(x) variable_scope("Discriminator", reuse=AUTO_REUSE) do # Typical convolutional neural network to classify images. x = tf.layers.conv2d(x, 64, 5) x = tf.nn.tanh(x) x = tf.layers.average_pooling2d(x, 2, 2) x = tf.layers.conv2d(x, 128, 5) x = tf.nn.tanh(x) x = tf.layers.average_pooling2d(x, 2, 2) x = tf.contrib.layers.flatten(x) x = tf.layers.dense(x, 1024) x = tf.nn.tanh(x) # Output 2 classes: Real and Fake images x = tf.layers.dense(x, 2) end return x end
412
0.807486
1
0.807486
game-dev
MEDIA
0.460701
game-dev
0.933212
1
0.933212
tukui-org/ElvUI
5,620
ElvUI_Libraries/Core/oUF/events.lua
local _, ns = ... local oUF = ns.oUF local Private = oUF.Private local argcheck = Private.argcheck local validateEvent = Private.validateEvent local validateUnit = Private.validateUnit local isUnitEvent = Private.isUnitEvent local frame_metatable = Private.frame_metatable -- Original event methods local registerEvent = frame_metatable.__index.RegisterEvent local registerUnitEvent = frame_metatable.__index.RegisterUnitEvent local unregisterEvent = frame_metatable.__index.UnregisterEvent local isEventRegistered = frame_metatable.__index.IsEventRegistered local next, type, assert = next, type, assert local format, tinsert = format, tinsert local setmetatable = setmetatable -- to update unit frames correctly, some events need to be registered for -- a specific combination of primary and secondary units local secondaryUnits = { UNIT_ENTERED_VEHICLE = { pet = 'player', }, UNIT_EXITED_VEHICLE = { pet = 'player', }, UNIT_PET = { pet = 'player', }, } function Private.UpdateUnits(frame, unit, realUnit) if(unit == realUnit) then realUnit = nil end if(frame.unit ~= unit or frame.realUnit ~= realUnit) then -- don't let invalid units in, otherwise unit events will end up being -- registered as unitless if(frame.unitEvents and validateUnit(unit)) then local resetRealUnit = false for event in next, frame.unitEvents do if(not realUnit and secondaryUnits[event]) then realUnit = secondaryUnits[event][unit] resetRealUnit = true end local registered, unit1, unit2 = isEventRegistered(frame, event) -- we don't want to re-register unitless/shared events in case -- someone added them by hand to the unitEvents table if(not registered or unit1 and (unit1 ~= unit or unit2 ~= realUnit)) then registerUnitEvent(frame, event, unit, realUnit) end if(resetRealUnit) then realUnit = nil resetRealUnit = false end end end frame.unit = unit frame.realUnit = realUnit frame.id = unit:match('^.-(%d+)') return true end end local function OnEvent(self, event, ...) if(self:IsVisible()) then return self[event](self, event, ...) end end local event_metatable = { __call = function(funcs, self, ...) for _, func in next, funcs do func(self, ...) end end, } --[[ Events: frame:RegisterEvent(event, func, unitless) Used to register a frame for a game event and add an event handler. OnUpdate polled frames are prevented from registering events. * self - frame that will be registered for the given event. * event - name of the event to register (string) * func - a function that will be executed when the event fires. Multiple functions can be added for the same frame and event (function) * unitless - indicates that the event does not fire for a specific unit, so the event arguments won't be matched to the frame unit(s). Obligatory for unitless event (boolean) --]] function frame_metatable.__index:RegisterEvent(event, func, unitless) -- Block OnUpdate polled frames from registering events except for -- UNIT_PORTRAIT_UPDATE and UNIT_MODEL_CHANGED which are used for -- portrait updates. if(self.__eventless and event ~= 'UNIT_PORTRAIT_UPDATE' and event ~= 'UNIT_MODEL_CHANGED') then return end argcheck(event, 2, 'string') argcheck(func, 3, 'function') local curev = self[event] if(curev) then local kind = type(curev) if(kind == 'function' and curev ~= func) then self[event] = setmetatable({curev, func}, event_metatable) elseif(kind == 'table') then for _, infunc in next, curev do if(infunc == func) then return end end tinsert(curev, func) end if(unitless or self.__eventless) then -- re-register the event in case we have mixed registration registerEvent(self, event) if(self.unitEvents) then self.unitEvents[event] = nil end end elseif(validateEvent(event)) then self[event] = func if(not self:GetScript('OnEvent')) then self:SetScript('OnEvent', OnEvent) end if(unitless or self.__eventless) then registerEvent(self, event) else self.unitEvents = self.unitEvents or {} self.unitEvents[event] = true -- UpdateUnits will take care of unit event registration for header -- units in case we don't have a valid unit yet local unit1, unit2 = self.unit if(unit1 and validateUnit(unit1)) then if(secondaryUnits[event]) then unit2 = secondaryUnits[event][unit1] end -- be helpful and throw a custom error when attempting to register -- an event that is unitless assert(isUnitEvent(event, unit1), format('Event "%s" is not an unit event', event)) registerUnitEvent(self, event, unit1, unit2 or '') end end end end --[[ Events: frame:UnregisterEvent(event, func) Used to remove a function from the event handler list for a game event. * self - the frame registered for the event * event - name of the registered event (string) * func - function to be removed from the list of event handlers. If this is the only handler for the given event, then the frame will be unregistered for the event (function) --]] function frame_metatable.__index:UnregisterEvent(event, func) argcheck(event, 2, 'string') local cleanUp = false local curev = self[event] if(type(curev) == 'table' and func) then for k, infunc in next, curev do if(infunc == func) then curev[k] = nil break end end if(not next(curev)) then cleanUp = true end end if(cleanUp or curev == func) then self[event] = nil if(self.unitEvents) then self.unitEvents[event] = nil end unregisterEvent(self, event) end end
412
0.824463
1
0.824463
game-dev
MEDIA
0.950308
game-dev
0.933044
1
0.933044
tge-was-taken/GFD-Studio
1,670
GFDStudio/GUI/DataViewNodes/ChunkType000100F9Entry3ViewNode.cs
using GFDLibrary.Misc; using System.ComponentModel; namespace GFDStudio.GUI.DataViewNodes { public class ChunkType000100F9Entry3ViewNode : DataViewNode<ChunkType000100F9Entry3> { public override DataViewNodeMenuFlags ContextMenuFlags => DataViewNodeMenuFlags.Move | DataViewNodeMenuFlags.Delete; public override DataViewNodeFlags NodeFlags => DataViewNodeFlags.Leaf; [Browsable( true )] [DisplayName( "Length (Squared)" )] public float LengthSq { get => Data.LengthSq; set => SetDataProperty( value ); } [Browsable( true )] [DisplayName( "Angular Limit" )] public float AngularLimit { get => Data.AngularLimit; set => SetDataProperty( value ); } [Browsable( true )] [DisplayName( "Chain thickness" )] public float ChainThickness { get => Data.ChainThickness; set => SetDataProperty( value ); } [Browsable( true )] [DisplayName( "Parent bone" )] public short ParentBoneIndex { get => Data.ParentBoneIndex; set => SetDataProperty( value ); } [Browsable( true )] [DisplayName( "Child bone" )] public short ChildBoneIndex { get => Data.ChildBoneIndex; set => SetDataProperty( value ); } public ChunkType000100F9Entry3ViewNode( string text, ChunkType000100F9Entry3 data ) : base( text, data ) { } protected override void InitializeCore() { } } }
412
0.900643
1
0.900643
game-dev
MEDIA
0.410604
game-dev,desktop-app
0.871553
1
0.871553
exteraSquad/exteraGram
1,029
TMessagesProj/src/main/java/org/telegram/ui/Components/SimpleFloatPropertyCompat.java
package org.telegram.ui.Components; import androidx.dynamicanimation.animation.FloatPropertyCompat; public class SimpleFloatPropertyCompat<T> extends FloatPropertyCompat<T> { private Getter<T> getter; private Setter<T> setter; private float multiplier = 1f; public SimpleFloatPropertyCompat(String name, Getter<T> getter, Setter<T> setter) { super(name); this.getter = getter; this.setter = setter; } public SimpleFloatPropertyCompat<T> setMultiplier(float multiplier) { this.multiplier = multiplier; return this; } public float getMultiplier() { return multiplier; } @Override public float getValue(T object) { return getter.get(object) * multiplier; } @Override public void setValue(T object, float value) { setter.set(object, value / multiplier); } public interface Getter<T> { float get(T obj); } public interface Setter<T> { void set(T obj, float value); } }
412
0.57209
1
0.57209
game-dev
MEDIA
0.904468
game-dev
0.87433
1
0.87433
awgil/ffxiv_bossmod
6,064
BossMod/Modules/Dawntrail/Foray/ForkedTower/FT01DemonTablet/FT01DemonTabletStates.cs
namespace BossMod.Dawntrail.Foray.ForkedTower.FT01DemonTablet; class FT01DemonTabletStates : StateMachineBuilder { public FT01DemonTabletStates(BossModule module) : base(module) { DeathPhase(0, Phase1) .ActivateOnEnter<BossCollision>(); } private void Phase1(uint id) { Cast(id, AID.DemonicDarkIICast, 4.2f, 5, "Raidwide") .ActivateOnEnter<DemonicDarkII>(); RayOfIgnorance(id + 0x100, 6.2f, "Safe side 1"); RayOfIgnorance(id + 0x200, 2.7f, "Safe side 2"); Cast(id + 0x300, AID.OccultChiselCast, 5.7f, 8.5f, "Tankbusters") .ActivateOnEnter<OccultChisel>() .DeactivateOnExit<OccultChisel>(); Towers1(id + 0x10000, 6.2f); Rotate(id + 0x20000, 5.1f); Meteors(id + 0x30000, 9.3f); Rotate(id + 0x40000, 5.7f); Adds(id + 0x50000, 9.3f); GravityTowers(id + 0x60000, 41.3f); Rotate(id + 0x70000, 6.1f); Timeout(id + 0xFF0000, 9999, "???"); } private State CloseFar(uint id, float delay) { return CastStartMulti(id, [AID.RayOfDangersNear, AID.RayOfExpulsionAfar, AID.DemonographOfDangersNear, AID.DemonographOfExpulsionAfar], delay) .ActivateOnEnter<LandingBoss>() .ActivateOnEnter<LandingNear>() .ActivateOnEnter<LandingKnockback>(); } private void RayOfIgnorance(uint id, float delay, string title) { CloseFar(id, delay) .ActivateOnEnter<RayOfIgnorance>(); ComponentCondition<RayOfIgnorance>(id + 0x10, 10.5f, r => r.NumCasts > 0, title) .DeactivateOnExit<LandingBoss>() .DeactivateOnExit<LandingNear>() .DeactivateOnExit<LandingKnockback>() .DeactivateOnExit<RayOfIgnorance>(); } private void Towers1(uint id, float delay) { CloseFar(id, delay).ActivateOnEnter<Explosion>(); ComponentCondition<LandingBoss>(id + 0x10, 10.5f, l => l.NumCasts > 0, "In/out") .ExecOnExit<Explosion>(e => e.EnableHints = true) .DeactivateOnExit<LandingBoss>() .DeactivateOnExit<LandingNear>() .DeactivateOnExit<LandingKnockback>(); ComponentCondition<Explosion>(id + 0x20, 4.5f, e => e.NumCasts > 0, "Towers") .DeactivateOnExit<Explosion>(); } private void Rotate(uint id, float delay) { CastStartMulti(id, [AID.RotateLeft, AID.RotateRight], delay) .ActivateOnEnter<Rotation>() .ActivateOnEnter<Rotation1>(); ComponentCondition<Rotation>(id + 0x10, 8.8f, r => r.NumCasts > 0, "Rotation 1") .DeactivateOnExit<Rotation>() .DeactivateOnExit<Rotation1>(); CastStartMulti(id + 0x100, [AID.RotateLeft, AID.RotateRight], 3.3f) .ActivateOnEnter<Rotation>() .ActivateOnEnter<Rotation1>() .ActivateOnEnter<LacunateStream>(); ComponentCondition<Rotation>(id + 0x110, 8.8f, r => r.NumCasts > 1, "Rotation 2") .DeactivateOnExit<Rotation>() .DeactivateOnExit<Rotation1>(); ComponentCondition<LacunateStream>(id + 0x120, 4.2f, l => l.NumCasts > 0, "Safe side") .DeactivateOnExit<LacunateStream>(); } private void Meteors(uint id, float delay) { ComponentCondition<PortentousComet>(id, delay, c => c.ActiveSpreads.Any(), "Meteors appear") .ActivateOnEnter<PortentousComet>() .ActivateOnEnter<PortentousCometeor>() .ActivateOnEnter<PortentousCometKB>() .ActivateOnEnter<LandingBoss>() .ActivateOnEnter<LandingNear>() .ActivateOnEnter<LandingKnockback>(); ComponentCondition<LandingBoss>(id + 1, 10.4f, l => l.NumCasts > 0, "In/out") .DeactivateOnExit<LandingBoss>() .DeactivateOnExit<LandingNear>() .DeactivateOnExit<LandingKnockback>(); ComponentCondition<PortentousComet>(id + 0x10, 1.6f, c => !c.ActiveSpreads.Any(), "Meteor target resolve") .ExecOnExit<PortentousComet>(e => e.EnableHints = true); ComponentCondition<PortentousCometKB>(id + 0x20, 5.1f, c => c.NumCasts > 0, "Stacks") .ExecOnExit<PortentousCometeor>(c => c.Risky = true) .DeactivateOnExit<PortentousComet>() .DeactivateOnExit<PortentousCometKB>(); ComponentCondition<PortentousCometeor>(id + 0x30, 7, c => c.NumCasts > 0, "Meteor AOEs") .DeactivateOnExit<PortentousCometeor>(); } private void Adds(uint id, float delay) { Cast(id, AID.SummonRect, delay, 10) .ActivateOnEnter<Summon>() .ActivateOnEnter<Summons>(); ComponentCondition<Summons>(id + 0x10, 0.9f, s => s.ActiveActors.Any(), "Adds appear") .ActivateOnEnter<DarkDefenses>(); } private void GravityTowers(uint id, float delay) { Cast(id, AID.Summon, delay, 4, "Statues appear"); Cast(id + 0x10, AID.Demonography, 2.1f, 4) .ActivateOnEnter<GravityExplosion>() .ActivateOnEnter<LandingNear>() .ActivateOnEnter<LandingKnockback>() .ActivateOnEnter<LandingBoss>() .ActivateOnEnter<EraseGravity>(); ComponentCondition<LandingBoss>(id + 0x20, 12.6f, b => b.NumCasts > 0, "In/out") .DeactivateOnExit<LandingNear>() .DeactivateOnExit<LandingKnockback>() .DeactivateOnExit<LandingBoss>() .ExecOnExit<EraseGravity>(e => e.Risky = true); ComponentCondition<EraseGravity>(id + 0x30, 3.5f, e => e.NumCasts > 0, "Statues activate") .DeactivateOnExit<EraseGravity>() .ExecOnExit<GravityExplosion>(g => g.EnableHints = true); ComponentCondition<GravityExplosion>(id + 0x40, 5.7f, g => g.NumCasts > 0, "Towers") .DeactivateOnExit<GravityExplosion>(); ComponentCondition<LandingStatue>(id + 0x50, 6.3f, l => l.NumCasts > 0, "Statue AOEs") .ActivateOnEnter<LandingStatue>(); } }
412
0.919718
1
0.919718
game-dev
MEDIA
0.489723
game-dev
0.790376
1
0.790376
MatthewHallberg/MapboxGPSHeading
1,310
Assets/GameSparks/Editor/GameSparksPopUp.cs
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; public class GameSparksPopUp : EditorWindow { private static Texture2D logo; static public void Init() { GameSparksPopUp window = (GameSparksPopUp)EditorWindow.GetWindowWithRect(typeof(GameSparksPopUp), new Rect((Screen.width - 350) / 2, (Screen.height - 265) / 2, 350, 265), false, "GameSparksSDK"); window.Focus(); } void OnEnable() { logo = (Texture2D)Resources.Load("GameSparksLogo", typeof(Texture2D)); } void OnGUI() { GUIStyle style = new GUIStyle(EditorStyles.wordWrappedLabel); style.alignment = TextAnchor.MiddleCenter; GUILayout.Label(logo); EditorGUILayout.LabelField("Welcome to GameSparks!", style); GUILayout.Space(20); EditorGUILayout.LabelField("To take advantage of this plugin, you must first register", style); EditorGUILayout.LabelField("on the GameSparks platform. Here you will be able to build", style); EditorGUILayout.LabelField("and configure your game.", style); GUILayout.Space(30); if (GUILayout.Button("Register Now")) { Close(); Application.OpenURL("https://auth.gamesparks.net/register.htm?utm_source=Unity%20SDK&utm_medium=Unity%20Editor&utm_campaign=Unity%20Asset%20Store"); } GUILayout.Space(10); } }
412
0.648066
1
0.648066
game-dev
MEDIA
0.857946
game-dev
0.579402
1
0.579402
realms-mud/core-lib
6,785
guilds/bard/melee-attacks.c
//***************************************************************************** // Copyright (c) 2025 - Allen Cummings, RealmsMUD, All rights reserved. See // the accompanying LICENSE file for details. //***************************************************************************** inherit "/lib/modules/research/researchTree.c"; ///////////////////////////////////////////////////////////////////////////// private void FirstLevel() { addResearchElement("/guilds/bard/melee/melees-melody.c"); addChild("/guilds/bard/melee/melees-melody.c", "/guilds/bard/melee/root.c"); } ///////////////////////////////////////////////////////////////////////////// private void SecondLevel() { addResearchElement("/guilds/bard/melee/anthem-of-attack.c"); addChild("/guilds/bard/melee/anthem-of-attack.c", "/guilds/bard/melee/root.c"); } ///////////////////////////////////////////////////////////////////////////// private void ThirdLevel() { addResearchElement("/guilds/bard/melee/melee-tune.c"); addChild("/guilds/bard/melee/melee-tune.c", "/guilds/bard/melee/root.c"); } ///////////////////////////////////////////////////////////////////////////// private void FifthLevel() { addResearchElement("/guilds/bard/melee/defenders-lament.c"); addChild("/guilds/bard/melee/defenders-lament.c", "/guilds/bard/melee/root.c"); } ///////////////////////////////////////////////////////////////////////////// private void SeventhLevel() { addResearchElement("/guilds/bard/melee/footmans-tune.c"); addChild("/guilds/bard/melee/footmans-tune.c", "/guilds/bard/melee/melees-melody.c"); } ///////////////////////////////////////////////////////////////////////////// private void NinthLevel() { addResearchElement("/guilds/bard/melee/melee-march.c"); addChild("/guilds/bard/melee/melee-march.c", "/guilds/bard/melee/melees-melody.c"); } ///////////////////////////////////////////////////////////////////////////// private void TenthLevel() { addResearchElement("/guilds/bard/melee/rhythmic-riposte.c"); addChild("/guilds/bard/melee/rhythmic-riposte.c", "/guilds/bard/melee/melees-melody.c"); } ///////////////////////////////////////////////////////////////////////////// private void EleventhLevel() { addResearchElement("/guilds/bard/melee/song-of-the-strong.c"); addChild("/guilds/bard/melee/song-of-the-strong.c", "/guilds/bard/melee/footmans-tune.c"); } ///////////////////////////////////////////////////////////////////////////// private void ThirteenthLevel() { addResearchElement("/guilds/bard/melee/sangine-song.c"); addChild("/guilds/bard/melee/sangine-song.c", "/guilds/bard/melee/melees-melody.c"); } ///////////////////////////////////////////////////////////////////////////// private void FifteenthLevel() { addResearchElement("/guilds/bard/melee/soldiers-song.c"); addChild("/guilds/bard/melee/soldiers-song.c", "/guilds/bard/melee/melee-march.c"); } ///////////////////////////////////////////////////////////////////////////// private void SixteenthLevel() { addResearchElement("/guilds/bard/melee/armsmans-form.c"); addChild("/guilds/bard/melee/armsmans-form.c", "/guilds/bard/melee/rhythmic-riposte.c"); } ///////////////////////////////////////////////////////////////////////////// private void NineteenthLevel() { addResearchElement("/guilds/bard/melee/requiem-of-attack.c"); addChild("/guilds/bard/melee/requiem-of-attack.c", "/guilds/bard/melee/song-of-the-strong.c"); } ///////////////////////////////////////////////////////////////////////////// private void TwentyFirstLevel() { addResearchElement("/guilds/bard/melee/serenade-of-the-soldier.c"); addChild("/guilds/bard/melee/serenade-of-the-soldier.c", "/guilds/bard/melee/soldiers-song.c"); } ///////////////////////////////////////////////////////////////////////////// private void TwentyThirdLevel() { addResearchElement("/guilds/bard/melee/armsmans-breath.c"); addChild("/guilds/bard/melee/armsmans-breath.c", "/guilds/bard/melee/armsmans-form.c"); } ///////////////////////////////////////////////////////////////////////////// private void TwentyFifthLevel() { addResearchElement("/guilds/bard/melee/arms-lament.c"); addChild("/guilds/bard/melee/arms-lament.c", "/guilds/bard/melee/serenade-of-the-soldier.c"); } ///////////////////////////////////////////////////////////////////////////// private void TwentySeventhLevel() { addResearchElement("/guilds/bard/melee/armsmasters-tale.c"); addChild("/guilds/bard/melee/armsmasters-tale.c", "/guilds/bard/melee/requiem-of-attack.c"); } ///////////////////////////////////////////////////////////////////////////// private void TwentyNinthLevel() { addResearchElement("/guilds/bard/melee/footmans-ballad.c"); addResearchElement("/guilds/bard/melee/dirge-of-destruction.c"); addChild("/guilds/bard/melee/footmans-ballad.c", "/guilds/bard/melee/arms-lament.c"); addChild("/guilds/bard/melee/dirge-of-destruction.c", "/guilds/bard/melee/sangine-song.c"); } ///////////////////////////////////////////////////////////////////////////// private void ThirtyFirstLevel() { addResearchElement("/guilds/bard/melee/minstrels-melee.c"); addChild("/guilds/bard/melee/minstrels-melee.c", "/guilds/bard/melee/armsmans-breath.c"); } ///////////////////////////////////////////////////////////////////////////// private void ThirtyThirdLevel() { addResearchElement("/guilds/bard/melee/weapon-masters-tale.c"); addChild("/guilds/bard/melee/weapon-masters-tale.c", "/guilds/bard/melee/footmans-ballad.c"); } ///////////////////////////////////////////////////////////////////////////// private void ThirtySeventhLevel() { addResearchElement("/guilds/bard/melee/lay-of-the-armsmaster.c"); addChild("/guilds/bard/melee/lay-of-the-armsmaster.c", "/guilds/bard/melee/weapon-masters-tale.c"); } ///////////////////////////////////////////////////////////////////////////// protected void Setup() { Name("Melee Weapons"); Description(""); Source("bard"); addResearchElement("/guilds/bard/melee/root.c"); TreeRoot("/guilds/bard/melee/root.c"); FirstLevel(); SecondLevel(); ThirdLevel(); FifthLevel(); SeventhLevel(); NinthLevel(); TenthLevel(); EleventhLevel(); ThirteenthLevel(); FifteenthLevel(); SixteenthLevel(); NineteenthLevel(); TwentyFirstLevel(); TwentyThirdLevel(); TwentyFifthLevel(); TwentySeventhLevel(); TwentyNinthLevel(); ThirtyFirstLevel(); ThirtyThirdLevel(); ThirtySeventhLevel(); }
412
0.657509
1
0.657509
game-dev
MEDIA
0.961175
game-dev
0.529577
1
0.529577
pathea-games/planetexplorers
2,188
Assets/Scripts/ZhouXun/Voxel Creation/Scripts/Components/Parts/Functions/VCPShipRudderFunc.cs
using UnityEngine; using System.Collections; //public class VCPShipRudderFunc : VCPartFunc //{ // public VCPShipRudderProperty m_Property; //// public BoatController m_Controller; // public Transform m_RudderSteering; // public Transform m_RudderFace; // public float m_CurrSteering; // public float m_SteeringTarget; // public float m_CurrTurningAngle; // /* // void Start () // { // if ( m_Controller != null ) // { // m_CurrSteering = 0; // m_SteeringTarget = 0; // } // } // void FixedUpdate () // { // if ( m_Controller != null ) // { // if ( m_Controller.m_NetChar == ENetCharacter.nrOwner ) // { // if ( m_Controller.m_Rigidbody != null && m_Controller.m_Active ) // { // // steering // if ( Mathf.Abs(m_CurrSteering - m_SteeringTarget) < 0.001f ) // m_CurrSteering = m_SteeringTarget; // else // m_CurrSteering = Mathf.Lerp(m_CurrSteering, m_SteeringTarget, Time.fixedDeltaTime * 3f); // m_CurrTurningAngle = m_CurrSteering * m_Property.m_MaxTurningAngle; // m_RudderSteering.localEulerAngles = new Vector3 (0, -m_CurrTurningAngle, 0); // float dot = -Vector3.Dot(m_Controller.GetComponent<Rigidbody>().velocity, m_Controller.transform.forward); // float scale = m_Controller.m_Rigidbody.mass / 1000; // scale = Mathf.Clamp(scale, 40, 100); // float force = Mathf.Pow(Mathf.Abs(dot), 0.7f) * Mathf.Sign(dot) * scale // * m_Property.m_YawingCoef * transform.localScale.y * transform.localScale.z // * Mathf.Sin(m_CurrTurningAngle*Mathf.Deg2Rad); // Vector3 point = m_RudderFace.position; // Vector3 thrust = m_RudderFace.right * force; // point.y = m_Controller.m_Rigidbody.worldCenterOfMass.y; // m_Controller.m_Rigidbody.AddForceAtPosition(thrust, point); // } // } // else // { // m_CurrTurningAngle = m_CurrSteering * m_Property.m_MaxTurningAngle; // m_RudderSteering.localEulerAngles = new Vector3 (0, m_CurrTurningAngle, 0); // } // } // } // public void TurnLeft () // { // m_SteeringTarget = -1; // } // public void TurnRight () // { // m_SteeringTarget = 1; // } // public void NotTurning () // { // m_SteeringTarget = 0; // } // * */ //}
412
0.684042
1
0.684042
game-dev
MEDIA
0.967713
game-dev
0.809535
1
0.809535
IppClub/Dora-SSR
5,765
Source/Platformer/Data.cpp
/* Copyright (c) 2016-2025 Li Jin <dragon-fly@qq.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Const/Header.h" #include "Platformer/Define.h" #include "Platformer/Data.h" #include "Basic/Application.h" #include "Physics/Body.h" #include "Physics/PhysicsWorld.h" #include "Platformer/Unit.h" #include "Platformer/UnitAction.h" #include "Support/Dictionary.h" NS_DORA_PLATFORMER_BEGIN Data::Data() : _store(Dictionary::create()) { SharedApplication.quitHandler += [this]() { clear(); UnitAction::clear(); }; } Data::~Data() { clear(); } #define Hide 0 #define FP 1 #define LP PhysicsWorld::TotalGroups - 4 #define PSensor PhysicsWorld::TotalGroups - 3 #define Terrain PhysicsWorld::TotalGroups - 2 #define SenseAll PhysicsWorld::TotalGroups - 1 void Data::apply(PhysicsWorld* world) { for (int p = FP; p <= LP; p++) { world->setShouldContact(PSensor, p, true); world->setShouldContact(Terrain, p, true); world->setShouldContact(SenseAll, p, true); world->setShouldContact(Hide, p, false); world->setShouldContact(p, p, false); } world->setShouldContact(Hide, Hide, false); world->setShouldContact(Hide, PSensor, false); world->setShouldContact(Hide, SenseAll, false); world->setShouldContact(Hide, Terrain, true); world->setShouldContact(PSensor, Terrain, true); world->setShouldContact(Terrain, Terrain, true); world->setShouldContact(SenseAll, Terrain, true); for (auto it : _contactMap) { uint8_t groupA = it.first >> 8; uint8_t groupB = it.first & 0xff; world->setShouldContact(groupA, groupB, it.second); } } void Data::setRelation(uint8_t groupA, uint8_t groupB, Relation relation) { uint16_t key = groupA << 8 | groupB; _relationMap[key] = relation; key = groupA | groupB << 8; _relationMap[key] = relation; } Relation Data::getRelation(uint8_t groupA, uint8_t groupB) const { if (groupA == groupB) return Relation::Friend; uint16_t key = groupA << 8 | groupB; auto it = _relationMap.find(key); return it != _relationMap.end() ? it->second : Relation::Unknown; } Relation Data::getRelation(Body* bodyA, Body* bodyB) const { if (!bodyA || !bodyB) return Relation::Unknown; return Data::getRelation(bodyA->getGroup(), bodyB->getGroup()); } bool Data::isEnemy(uint8_t groupA, uint8_t groupB) const { return getRelation(groupA, groupB) == Relation::Enemy; } bool Data::isEnemy(Body* bodyA, Body* bodyB) const { return getRelation(bodyA, bodyB) == Relation::Enemy; } bool Data::isFriend(uint8_t groupA, uint8_t groupB) const { return getRelation(groupA, groupB) == Relation::Enemy; } bool Data::isFriend(Body* bodyA, Body* bodyB) const { return getRelation(bodyA, bodyB) == Relation::Friend; } bool Data::isNeutral(uint8_t groupA, uint8_t groupB) const { return getRelation(groupA, groupB) == Relation::Neutral; } bool Data::isNeutral(Body* bodyA, Body* bodyB) const { return getRelation(bodyA, bodyB) == Relation::Neutral; } void Data::setShouldContact(uint8_t groupA, uint8_t groupB, bool contact) { uint16_t key = groupA << 8 | groupB; _contactMap[key] = contact; key = groupA | groupB << 8; _contactMap[key] = contact; } bool Data::getShouldContact(uint8_t groupA, uint8_t groupB) const { uint16_t key = groupA << 8 | groupB; auto it = _contactMap.find(key); return it != _contactMap.end() ? it->second : false; } uint8_t Data::getGroupFirstPlayer() const noexcept { return FP; } uint8_t Data::getGroupLastPlayer() const noexcept { return LP; } uint8_t Data::getGroupDetectPlayer() const noexcept { return PSensor; } uint8_t Data::getGroupTerrain() const noexcept { return Terrain; } uint8_t Data::getGroupDetection() const noexcept { return SenseAll; } uint8_t Data::getGroupHide() const noexcept { return Hide; } void Data::setDamageFactor(uint16_t damageType, uint16_t defenceType, float bounus) { uint32_t key = damageType | defenceType << 16; _damageBounusMap[key] = bounus; } float Data::getDamageFactor(uint16_t damageType, uint16_t defenceType) const { uint32_t key = damageType | defenceType << 16; std::unordered_map<uint32_t, float>::const_iterator it = _damageBounusMap.find(key); if (it != _damageBounusMap.end()) { return it->second; } return 0.0f; } bool Data::isPlayer(Body* body) { if (!body) return false; int16_t index = body->getGroup(); return FP <= index && index <= LP; } bool Data::isTerrain(Body* body) { if (!body) return false; return body->getGroup() == Data::getGroupTerrain(); } Dictionary* Data::getStore() const noexcept { return _store; } void Data::clear() { _contactMap.clear(); _relationMap.clear(); _damageBounusMap.clear(); _store->each([](Value* value, const std::string& key) { if (auto dict = value->as<Dictionary>()) { dict->clear(); } return false; }); _store->clear(); } NS_DORA_PLATFORMER_END
412
0.923874
1
0.923874
game-dev
MEDIA
0.928343
game-dev
0.945168
1
0.945168
realms-mud/core-lib
3,388
lib/tests/secure/usersTest.c
//***************************************************************************** // Copyright (c) 2025 - Allen Cummings, RealmsMUD, All rights reserved. See // the accompanying LICENSE file for details. //***************************************************************************** inherit "/lib/tests/framework/testFixture.c"; #include <functionlist.h> object Users; ///////////////////////////////////////////////////////////////////////////// void Init() { string *functions = filter( functionlist(this_object(), RETURN_FUNCTION_NAME), (: sizeof(regexp(({ $1 }), "__inline")) :)); ignoreList += functions; } ///////////////////////////////////////////////////////////////////////////// void Setup() { Users = clone_object("/secure/simul_efun.c"); } ///////////////////////////////////////////////////////////////////////////// void CleanUp() { destruct(Users); } ///////////////////////////////////////////////////////////////////////////// void LivingObjectsPlacedInList() { ExpectEq(0, Users.findLiving("bob")); object critter = clone_object("/lib/realizations/monster.c"); critter.Name("bob"); Users.addLiving(critter); ExpectEq(critter, Users.findLiving("bob")); destruct(critter); ExpectEq(0, Users.findLiving("bob")); } ///////////////////////////////////////////////////////////////////////////// void FindLivingCanFindPlayers() { ExpectEq(0, Users.findLiving("bob")); object critter = clone_object("/lib/realizations/player.c"); critter.Name("bob"); setUsers(({ critter })); Users.addLiving(critter); ExpectEq(critter, Users.findLiving("bob")); destruct(critter); ExpectEq(0, Users.findLiving("bob")); } ///////////////////////////////////////////////////////////////////////////// void FindLivingCanFindWizards() { ExpectEq(0, Users.findLiving("bob")); object critter = clone_object("/lib/realizations/wizard.c"); critter.Name("bob"); setUsers(({ critter })); Users.addLiving(critter); ExpectEq(critter, Users.findLiving("bob")); destruct(critter); ExpectEq(0, Users.findLiving("bob")); } ///////////////////////////////////////////////////////////////////////////// void PlayersPlacedInUsersList() { ExpectEq(({}), users()); object player = clone_object("/lib/realizations/player.c"); player.Name("earl"); object wizard = clone_object("/lib/realizations/wizard.c"); wizard.Name("fred"); setUsers(({ player, wizard })); addLiving(player); addLiving(wizard); ExpectEq(({ player, wizard }), users()); destruct(player); ExpectEq(({ wizard }), users()); } ///////////////////////////////////////////////////////////////////////////// void CanGetGuestNameReturnsNextAvailableName() { object player = clone_object("/lib/realizations/player.c"); player.Name("guest"); object player1 = clone_object("/lib/realizations/player.c"); player1.Name("guest"); ExpectEq("guest01", getGuestName(player)); ExpectEq("guest02", getGuestName(player1)); ExpectEq("guest03", getGuestName(player)); ExpectEq("guest04", getGuestName(player1)); destruct(player1); player1 = clone_object("/lib/realizations/player.c"); player1.Name("guest"); ExpectEq("guest02", getGuestName(player1)); destruct(player); destruct(player1); }
412
0.702387
1
0.702387
game-dev
MEDIA
0.864405
game-dev
0.706606
1
0.706606
masqu3rad3/tik_manager4
1,596
tik_manager4/dcc/blender/validate/ngons.py
"""Ensure meshes do not contain ngons""" import bpy from tik_manager4.dcc.validate_core import ValidateCore class Ngons(ValidateCore): """Example validation for Blender""" nice_name = "Ngons" def __init__(self): super(Ngons, self).__init__() self.autofixable = False self.ignorable = True self.selectable = True self.bad_meshes = [] def collect(self): """Collect all mesh objects in the scene.""" self.collection = [ obj for obj in bpy.context.scene.objects if obj.type == "MESH" ] def validate(self): """Identify ngons in the scene.""" self.bad_meshes = [] self.collect() for mesh in self.collection: ngon_count = self.get_ngon_count(mesh) if ngon_count: self.bad_meshes.append(mesh.name) if self.bad_meshes: self.failed( msg=f"Ngons found in the following meshes: {self.bad_meshes}" ) else: self.passed() def select(self): """Select the bad meshes with ngons.""" bpy.ops.object.select_all(action="DESELECT") for mesh_name in self.bad_meshes: obj = bpy.data.objects.get(mesh_name) if obj: obj.select_set(True) def get_ngon_count(self, obj): """Check the mesh for ngons and return the count. Returns 0 if none found.""" if obj.type != "MESH": return 0 mesh = obj.data return sum(1 for poly in mesh.polygons if len(poly.vertices) > 4)
412
0.709148
1
0.709148
game-dev
MEDIA
0.426764
game-dev
0.520176
1
0.520176
sobolevn/python-code-disasters
10,476
python/AI-battlship_game.py
import random from models import Player, Field, Ship from restrictions import CheckSurround, BorderRestriction class AI(Player): def __init__(self, turn): super(AI, self).__init__(turn) self.name = 'A.I.' def placing_ships_on_the_field(self, size): """ With this method computer places ships on the game field :param size: size of the ship """ old_field = list(self.field) upd_field = list(self.field) def place_ship(fld, cur_fld, trn): current_ship_position = set([place for place in range( len(fld)) if fld[place] == '&']) forb_places = CheckSurround(fld).forbid_placement() forb_places_upd = [place for place in forb_places if cur_fld[place] == trn] if len(forb_places_upd) == 0: for position in current_ship_position: cur_fld[position] = trn self.ships_alive.append(list(current_ship_position)) return True commands = {'w': Ship(size).move_up, 'd': Ship(size).move_right, 's': Ship(size).move_down, 'a': Ship(size).move_left, 'r': Ship(size).rotate_ship, 'p': place_ship} while True: Ship(size).place_ship(old_field, upd_field) upd_field, old_field = list(self.field), upd_field attempts = 0 randoms = random.randint(1, 50) try: while attempts != randoms: commands[random.choice(('w', 'd', 's', 'a', 'r'))](old_field, upd_field) if BorderRestriction(upd_field).forbid_of_cross_border(): upd_field = list(self.field) continue upd_field, old_field = list(self.field), upd_field attempts += 1 if commands['p'](old_field, self.field, self.turn): break else: continue except IndexError: upd_field = list(self.field) continue def shooting(self): """ Method marks the field: 'o' - miss 'x' - hit the target """ wounded_ships = [deck for deck in range(len( self.opponent.field)) if self.opponent.field[deck] == 'x' and self.opponent.field[deck] not in self.ships_hit] if len(wounded_ships) == 1: while True: shot = random.choice(list( AI.shooting_area(wounded_ships))) if self.opponent.field[shot] == self.opponent.turn: self.opponent.field[shot] = 'x' break elif self.opponent.field[shot] is None: self.opponent.field[shot] = 'o' break else: continue elif len(wounded_ships) > 1: if self.opponent.field[wounded_ships[-1] - 1] == 'x': while True: shot = random.choice(list( AI.horizontal_shooting_area(wounded_ships))) if self.opponent.field[shot] == self.opponent.turn: self.opponent.field[shot] = 'x' break elif self.opponent.field[shot] is None: self.opponent.field[shot] = 'o' break else: continue else: while True: shot = random.choice(list( AI.upright_shooting_area(wounded_ships))) if self.opponent.field[shot] == self.opponent.turn: self.opponent.field[shot] = 'x' break elif self.opponent.field[shot] is None: self.opponent.field[shot] = 'o' break else: continue else: available_to_shoot = random.choice([pos for pos in range( len(self.opponent.field)) if self.opponent.field[pos] != 'o']) if self.opponent.field[available_to_shoot] == self.opponent.turn: self.opponent.field[available_to_shoot] = 'x' else: self.opponent.field[available_to_shoot] = 'o' @staticmethod def shooting_area(ship_position): """ If computer hit the target this method defies the area there it will tries to hit the next target :param ship_position: current hit ship position in the list """ set_of_pos = set() for place in ship_position: if place in Field.r_upper_corner: set_of_pos.update({place - 1}, {place + Field.num_of_lines} ) elif place in Field.r_bottom_corner: set_of_pos.update({place - 1}, {place - Field.num_of_lines} ) elif place in Field.l_upper_corner: set_of_pos.update({place + 1}, {place + Field.num_of_lines} ) elif place in Field.l_bottom_corner: set_of_pos.update({place + 1}, {place - Field.num_of_lines} ) elif place in Field.right_border: set_of_pos.update({place - 1}, {place - Field.num_of_lines}, {place + Field.num_of_lines} ) elif place in Field.left_border: set_of_pos.update({place + 1}, {place - Field.num_of_lines}, {place + Field.num_of_lines} ) elif place in Field.upper_border: set_of_pos.update({place + 1}, {place - 1}, {place + Field.num_of_lines} ) elif place in Field.bottom_border: set_of_pos.update({place + 1}, {place - 1}, {place - Field.num_of_lines} ) else: set_of_pos.update({place + 1}, {place - 1}, {place - Field.num_of_lines}, {place + Field.num_of_lines} ) return set_of_pos @staticmethod def horizontal_shooting_area(ship_position): """ If computer hit the target this method defies the area there it will tries to hit the next target (horizontally) :param ship_position: current hit ship position in the list """ set_of_pos = set() for place in ship_position: if place in Field.r_upper_corner: set_of_pos.update({place - 1}) elif place in Field.r_bottom_corner: set_of_pos.update({place - 1}) elif place in Field.l_upper_corner: set_of_pos.update({place + 1}) elif place in Field.l_bottom_corner: set_of_pos.update({place + 1}) elif place in Field.right_border: set_of_pos.update({place - 1}) elif place in Field.left_border: set_of_pos.update({place + 1}) elif place in Field.upper_border: set_of_pos.update({place + 1}, {place - 1}) elif place in Field.bottom_border: set_of_pos.update({place + 1}, {place - 1}) else: set_of_pos.update({place + 1}, {place - 1}) return set_of_pos @staticmethod def upright_shooting_area(ship_position): """ If computer hit the target this method defies the area there it will tries to hit the next target (upright) :param ship_position: current hit ship position in the list """ set_of_pos = set() for place in ship_position: if place in Field.r_upper_corner: set_of_pos.update( {place + Field.num_of_lines} ) elif place in Field.r_bottom_corner: set_of_pos.update( {place - Field.num_of_lines} ) elif place in Field.l_upper_corner: set_of_pos.update( {place + Field.num_of_lines} ) elif place in Field.l_bottom_corner: set_of_pos.update( {place - Field.num_of_lines} ) elif place in Field.right_border: set_of_pos.update( {place - Field.num_of_lines}, {place + Field.num_of_lines} ) elif place in Field.left_border: set_of_pos.update( {place + Field.num_of_lines}, {place - Field.num_of_lines} ) elif place in Field.upper_border: set_of_pos.update( {place + Field.num_of_lines} ) elif place in Field.bottom_border: set_of_pos.update( {place - Field.num_of_lines} ) else: set_of_pos.update( {place - Field.num_of_lines}, {place + Field.num_of_lines} ) return set_of_pos
412
0.815186
1
0.815186
game-dev
MEDIA
0.746232
game-dev
0.91489
1
0.91489
Kromtec/LegendsViewer
5,086
LegendsViewer/Legends/Events/FieldBattle.cs
using System; using System.Collections.Generic; using LegendsViewer.Legends.Parser; using LegendsViewer.Legends.WorldObjects; namespace LegendsViewer.Legends.Events { public class FieldBattle : WorldEvent { public Entity Attacker { get; set; } public Entity Defender { get; set; } public Entity AttackerMercenaries { get; set; } public Entity DefenderMercenaries { get; set; } public Entity AttackerSupportMercenaries { get; set; } public Entity DefenderSupportMercenaries { get; set; } public WorldRegion Region { get; set; } public HistoricalFigure AttackerGeneral { get; set; } public HistoricalFigure DefenderGeneral { get; set; } public UndergroundRegion UndergroundRegion { get; set; } public Location Coordinates { get; set; } public FieldBattle(List<Property> properties, World world) : base(properties, world) { foreach (Property property in properties) { switch (property.Name) { case "coords": Coordinates = Formatting.ConvertToLocation(property.Value); break; case "attacker_civ_id": Attacker = world.GetEntity(Convert.ToInt32(property.Value)); break; case "defender_civ_id": Defender = world.GetEntity(Convert.ToInt32(property.Value)); break; case "subregion_id": Region = world.GetRegion(Convert.ToInt32(property.Value)); break; case "attacker_general_hfid": AttackerGeneral = world.GetHistoricalFigure(Convert.ToInt32(property.Value)); break; case "defender_general_hfid": DefenderGeneral = world.GetHistoricalFigure(Convert.ToInt32(property.Value)); break; case "feature_layer_id": UndergroundRegion = world.GetUndergroundRegion(Convert.ToInt32(property.Value)); break; case "attacker_merc_enid": AttackerMercenaries = world.GetEntity(Convert.ToInt32(property.Value)); break; case "defender_merc_enid": DefenderMercenaries = world.GetEntity(Convert.ToInt32(property.Value)); break; case "a_support_merc_enid": AttackerSupportMercenaries = world.GetEntity(Convert.ToInt32(property.Value)); break; case "d_support_merc_enid": DefenderSupportMercenaries = world.GetEntity(Convert.ToInt32(property.Value)); break; } } Attacker.AddEvent(this); Defender.AddEvent(this); AttackerGeneral.AddEvent(this); DefenderGeneral.AddEvent(this); Region.AddEvent(this); UndergroundRegion.AddEvent(this); if (AttackerMercenaries != Defender && AttackerMercenaries != Attacker) { AttackerMercenaries.AddEvent(this); } if (DefenderMercenaries != Defender && DefenderMercenaries != Attacker) { DefenderMercenaries.AddEvent(this); } AttackerSupportMercenaries.AddEvent(this); DefenderSupportMercenaries.AddEvent(this); } public override string Print(bool link = true, DwarfObject pov = null) { string eventString = GetYearTime(); eventString += Attacker.ToLink(true, pov); eventString += " attacked "; eventString += Defender.ToLink(true, pov); eventString += " in " + Region.ToLink(link, pov, this) + ". "; if (AttackerGeneral != null) { eventString += "Leader of the attack was "; eventString += AttackerGeneral.ToLink(link, pov, this); } if (DefenderGeneral != null) { eventString += ", and the defenders were led by "; eventString += DefenderGeneral.ToLink(link, pov, this); } eventString += PrintParentCollection(link, pov); eventString += "."; if (AttackerMercenaries != null) { eventString += " "; eventString += AttackerMercenaries.ToLink(true, pov); eventString += " were hired by the attackers."; } if (DefenderMercenaries != null) { eventString += " "; eventString += DefenderMercenaries.ToLink(true, pov); eventString += " were hired by the defenders."; } if (AttackerSupportMercenaries != null) { eventString += " "; eventString += AttackerSupportMercenaries.ToLink(true, pov); eventString += " were hired as scouts by the attackers."; } if (DefenderSupportMercenaries != null) { eventString += " "; eventString += DefenderSupportMercenaries.ToLink(true, pov); eventString += " were hired as scouts by the defenders."; } return eventString; } } }
412
0.925909
1
0.925909
game-dev
MEDIA
0.834406
game-dev
0.74836
1
0.74836
hc-tcg/hc-tcg
2,555
common/cards/bed-update/single-use/coward's-bed.ts
import { CardComponent, ObserverComponent, SlotComponent, } from '../../../components' import query from '../../../components/query' import {GameModel} from '../../../models/game-model' import {singleUse} from '../../defaults' import {SingleUse} from '../../types' const hasSwitchable = query.every( query.slot.hermit, query.not(query.slot.active), query.not(query.slot.empty), query.slot.canBecomeActive, ) const CowardsBed: SingleUse = { ...singleUse, id: "coward's_bed", numericId: 264, name: "Coward's Bed", expansion: 'beds', rarity: 'ultra_rare', tokens: 1, description: 'Both players must choose an AFK Hermit to set as their active Hermit, unless they have no AFK Hermits.\nYour opponent chooses their active Hermit first.', showConfirmationModal: true, attachCondition: query.every( singleUse.attachCondition, query.exists(SlotComponent, hasSwitchable), ), onAttach( game: GameModel, component: CardComponent, observer: ObserverComponent, ) { const {player, opponentPlayer} = component observer.subscribe(player.hooks.onApply, () => { //Copied from Tango Rare, slightly modified. const playerInactiveRowsPickCondition = query.every( query.slot.currentPlayer, query.slot.hermit, query.not(query.slot.active), query.not(query.slot.empty), query.slot.canBecomeActive, ) // Check if we are blocked from changing by anything other than the game const canChange = !game.isActionBlocked('CHANGE_ACTIVE_HERMIT', ['game']) // If opponent has hermit they can switch to, add a pick request for them to switch let knockbackPickRequest = opponentPlayer.getKnockbackPickRequest(component) if (knockbackPickRequest) game.addPickRequest(knockbackPickRequest) // If we have an afk hermit and are not bound in place, add a pick for us to switch if ( game.components.exists( SlotComponent, playerInactiveRowsPickCondition, ) && canChange ) { game.addPickRequest({ player: player.entity, id: component.entity, message: 'Pick a new active Hermit from your afk hermits', canPick: playerInactiveRowsPickCondition, onResult(pickedSlot) { if (!pickedSlot.inRow()) return player.changeActiveRow(pickedSlot.row) }, onTimeout() { let newActiveHermit = game.components.find( SlotComponent, playerInactiveRowsPickCondition, ) if (!newActiveHermit?.inRow()) return player.changeActiveRow(newActiveHermit.row) }, }) } }) }, } export default CowardsBed
412
0.966953
1
0.966953
game-dev
MEDIA
0.656901
game-dev
0.988193
1
0.988193
BLACKujira/SekaiTools
14,491
SekaiTools/Assets/Spine/spine-unity/Modules/Ragdoll/SkeletonRagdoll.cs
/****************************************************************************** * Spine Runtimes Software License v2.5 * * Copyright (c) 2013-2016, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable, and * non-transferable license to use, install, execute, and perform the Spine * Runtimes software and derivative works solely for personal or internal * use. Without the written permission of Esoteric Software (see Section 2 of * the Spine Software License Agreement), you may not (a) modify, translate, * adapt, or develop new applications using the Spine Runtimes or otherwise * create derivative works or improvements of the Spine Runtimes or (b) remove, * delete, alter, or obscure any trademarks or any copyright, trademark, patent, * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF * USE, DATA, OR PROFITS) 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. *****************************************************************************/ // Contributed by: Mitch Thompson using UnityEngine; using System.Collections; using System.Collections.Generic; namespace Spine.Unity.Modules { [RequireComponent(typeof(SkeletonRenderer))] public class SkeletonRagdoll : MonoBehaviour { static Transform parentSpaceHelper; #region Inspector [Header("Hierarchy")] [SpineBone] public string startingBoneName = ""; [SpineBone] public List<string> stopBoneNames = new List<string>(); [Header("Parameters")] public bool applyOnStart; [Tooltip("Warning! You will have to re-enable and tune mix values manually if attempting to remove the ragdoll system.")] public bool disableIK = true; public bool disableOtherConstraints = false; [Space(18)] [Tooltip("Set RootRigidbody IsKinematic to true when Apply is called.")] public bool pinStartBone; [Tooltip("Enable Collision between adjacent ragdoll elements (IE: Neck and Head)")] public bool enableJointCollision; public bool useGravity = true; [Tooltip("If no BoundingBox Attachment is attached to a bone, this becomes the default Width or Radius of a Bone's ragdoll Rigidbody")] public float thickness = 0.125f; [Tooltip("Default rotational limit value. Min is negative this value, Max is this value.")] public float rotationLimit = 20; public float rootMass = 20; [Tooltip("If your ragdoll seems unstable or uneffected by limits, try lowering this value.")] [Range(0.01f, 1f)] public float massFalloffFactor = 0.4f; [Tooltip("The layer assigned to all of the rigidbody parts.")] public int colliderLayer = 0; [Range(0, 1)] public float mix = 1; #endregion ISkeletonAnimation targetSkeletonComponent; Skeleton skeleton; Dictionary<Bone, Transform> boneTable = new Dictionary<Bone, Transform>(); Transform ragdollRoot; public Rigidbody RootRigidbody { get; private set; } public Bone StartingBone { get; private set; } Vector3 rootOffset; public Vector3 RootOffset { get { return this.rootOffset; } } bool isActive; public bool IsActive { get { return this.isActive; } } IEnumerator Start () { if (parentSpaceHelper == null) { parentSpaceHelper = (new GameObject("Parent Space Helper")).transform; parentSpaceHelper.hideFlags = HideFlags.HideInHierarchy; } targetSkeletonComponent = GetComponent<SkeletonRenderer>() as ISkeletonAnimation; if (targetSkeletonComponent == null) Debug.LogError("Attached Spine component does not implement ISkeletonAnimation. This script is not compatible."); skeleton = targetSkeletonComponent.Skeleton; if (applyOnStart) { yield return null; Apply(); } } #region API public Rigidbody[] RigidbodyArray { get { if (!isActive) return new Rigidbody[0]; var rigidBodies = new Rigidbody[boneTable.Count]; int i = 0; foreach (Transform t in boneTable.Values) { rigidBodies[i] = t.GetComponent<Rigidbody>(); i++; } return rigidBodies; } } public Vector3 EstimatedSkeletonPosition { get { return RootRigidbody.position - rootOffset; } } /// <summary>Instantiates the ragdoll simulation and applies its transforms to the skeleton.</summary> public void Apply () { isActive = true; mix = 1; StartingBone = skeleton.FindBone(startingBoneName); RecursivelyCreateBoneProxies(StartingBone); RootRigidbody = boneTable[StartingBone].GetComponent<Rigidbody>(); RootRigidbody.isKinematic = pinStartBone; RootRigidbody.mass = rootMass; var boneColliders = new List<Collider>(); foreach (var pair in boneTable) { var b = pair.Key; var t = pair.Value; Transform parentTransform; boneColliders.Add(t.GetComponent<Collider>()); if (b == StartingBone) { ragdollRoot = new GameObject("RagdollRoot").transform; ragdollRoot.SetParent(transform, false); if (b == skeleton.RootBone) { // RagdollRoot is skeleton root. ragdollRoot.localPosition = new Vector3(b.WorldX, b.WorldY, 0); ragdollRoot.localRotation = Quaternion.Euler(0, 0, GetPropagatedRotation(b)); } else { ragdollRoot.localPosition = new Vector3(b.Parent.WorldX, b.Parent.WorldY, 0); ragdollRoot.localRotation = Quaternion.Euler(0, 0, GetPropagatedRotation(b.Parent)); } parentTransform = ragdollRoot; rootOffset = t.position - transform.position; } else { parentTransform = boneTable[b.Parent]; } // Add joint and attach to parent. var rbParent = parentTransform.GetComponent<Rigidbody>(); if (rbParent != null) { var joint = t.gameObject.AddComponent<HingeJoint>(); joint.connectedBody = rbParent; Vector3 localPos = parentTransform.InverseTransformPoint(t.position); localPos.x *= 1; joint.connectedAnchor = localPos; joint.axis = Vector3.forward; joint.GetComponent<Rigidbody>().mass = joint.connectedBody.mass * massFalloffFactor; joint.limits = new JointLimits { min = -rotationLimit, max = rotationLimit, }; joint.useLimits = true; joint.enableCollision = enableJointCollision; } } // Ignore collisions among bones. for (int x = 0; x < boneColliders.Count; x++) { for (int y = 0; y < boneColliders.Count; y++) { if (x == y) continue; Physics.IgnoreCollision(boneColliders[x], boneColliders[y]); } } // Destroy existing override-mode SkeletonUtilityBones. var utilityBones = GetComponentsInChildren<SkeletonUtilityBone>(); if (utilityBones.Length > 0) { var destroyedUtilityBoneNames = new List<string>(); foreach (var ub in utilityBones) { if (ub.mode == SkeletonUtilityBone.Mode.Override) { destroyedUtilityBoneNames.Add(ub.gameObject.name); Destroy(ub.gameObject); } } if (destroyedUtilityBoneNames.Count > 0) { string msg = "Destroyed Utility Bones: "; for (int i = 0; i < destroyedUtilityBoneNames.Count; i++) { msg += destroyedUtilityBoneNames[i]; if (i != destroyedUtilityBoneNames.Count - 1) { msg += ","; } } Debug.LogWarning(msg); } } // Disable skeleton constraints. if (disableIK) { var ikConstraints = skeleton.IkConstraints; for (int i = 0, n = ikConstraints.Count; i < n; i++) ikConstraints.Items[i].mix = 0; } if (disableOtherConstraints) { var transformConstraints = skeleton.transformConstraints; for (int i = 0, n = transformConstraints.Count; i < n; i++) { transformConstraints.Items[i].rotateMix = 0; transformConstraints.Items[i].scaleMix = 0; transformConstraints.Items[i].shearMix = 0; transformConstraints.Items[i].translateMix = 0; } var pathConstraints = skeleton.pathConstraints; for (int i = 0, n = pathConstraints.Count; i < n; i++) { pathConstraints.Items[i].rotateMix = 0; pathConstraints.Items[i].translateMix = 0; } } targetSkeletonComponent.UpdateWorld += UpdateSpineSkeleton; } /// <summary>Transitions the mix value from the current value to a target value.</summary> public Coroutine SmoothMix (float target, float duration) { return StartCoroutine(SmoothMixCoroutine(target, duration)); } IEnumerator SmoothMixCoroutine (float target, float duration) { float startTime = Time.time; float startMix = mix; while (mix > 0) { skeleton.SetBonesToSetupPose(); mix = Mathf.SmoothStep(startMix, target, (Time.time - startTime) / duration); yield return null; } } /// <summary>Set the transform world position while preserving the ragdoll parts world position.</summary> public void SetSkeletonPosition (Vector3 worldPosition) { if (!isActive) { Debug.LogWarning("Can't call SetSkeletonPosition while Ragdoll is not active!"); return; } Vector3 offset = worldPosition - transform.position; transform.position = worldPosition; foreach (Transform t in boneTable.Values) t.position -= offset; UpdateSpineSkeleton(null); skeleton.UpdateWorldTransform(); } /// <summary>Removes the ragdoll instance and effect from the animated skeleton.</summary> public void Remove () { isActive = false; foreach (var t in boneTable.Values) Destroy(t.gameObject); Destroy(ragdollRoot.gameObject); boneTable.Clear(); targetSkeletonComponent.UpdateWorld -= UpdateSpineSkeleton; } public Rigidbody GetRigidbody (string boneName) { var bone = skeleton.FindBone(boneName); return (bone != null && boneTable.ContainsKey(bone)) ? boneTable[bone].GetComponent<Rigidbody>() : null; } #endregion void RecursivelyCreateBoneProxies (Bone b) { string boneName = b.data.name; if (stopBoneNames.Contains(boneName)) return; var boneGameObject = new GameObject(boneName); boneGameObject.layer = colliderLayer; Transform t = boneGameObject.transform; boneTable.Add(b, t); t.parent = transform; t.localPosition = new Vector3(b.WorldX, b.WorldY, 0); t.localRotation = Quaternion.Euler(0, 0, b.WorldRotationX - b.shearX); t.localScale = new Vector3(b.WorldScaleX, b.WorldScaleY, 1); // MITCH: You left "todo: proper ragdoll branching" var colliders = AttachBoundingBoxRagdollColliders(b); if (colliders.Count == 0) { float length = b.Data.Length; if (length == 0) { var ball = boneGameObject.AddComponent<SphereCollider>(); ball.radius = thickness * 0.5f; } else { var box = boneGameObject.AddComponent<BoxCollider>(); box.size = new Vector3(length, thickness, thickness); box.center = new Vector3(length * 0.5f, 0); } } var rb = boneGameObject.AddComponent<Rigidbody>(); rb.constraints = RigidbodyConstraints.FreezePositionZ; foreach (Bone child in b.Children) RecursivelyCreateBoneProxies(child); } void UpdateSpineSkeleton (ISkeletonAnimation skeletonRenderer) { bool flipX = skeleton.flipX; bool flipY = skeleton.flipY; bool flipXOR = flipX ^ flipY; bool flipOR = flipX || flipY; foreach (var pair in boneTable) { var b = pair.Key; var t = pair.Value; bool isStartingBone = b == StartingBone; Transform parentTransform = isStartingBone ? ragdollRoot : boneTable[b.Parent]; Vector3 parentTransformWorldPosition = parentTransform.position; Quaternion parentTransformWorldRotation = parentTransform.rotation; parentSpaceHelper.position = parentTransformWorldPosition; parentSpaceHelper.rotation = parentTransformWorldRotation; parentSpaceHelper.localScale = parentTransform.localScale; Vector3 boneWorldPosition = t.position; Vector3 right = parentSpaceHelper.InverseTransformDirection(t.right); Vector3 boneLocalPosition = parentSpaceHelper.InverseTransformPoint(boneWorldPosition); float boneLocalRotation = Mathf.Atan2(right.y, right.x) * Mathf.Rad2Deg; if (flipOR) { if (isStartingBone) { if (flipX) boneLocalPosition.x *= -1f; if (flipY) boneLocalPosition.y *= -1f; boneLocalRotation = boneLocalRotation * (flipXOR ? -1f : 1f); if (flipX) boneLocalRotation += 180; } else { if (flipXOR) { boneLocalRotation *= -1f; boneLocalPosition.y *= -1f; // wtf?? } } } b.x = Mathf.Lerp(b.x, boneLocalPosition.x, mix); b.y = Mathf.Lerp(b.y, boneLocalPosition.y, mix); b.rotation = Mathf.Lerp(b.rotation, boneLocalRotation, mix); //b.AppliedRotation = Mathf.Lerp(b.AppliedRotation, boneLocalRotation, mix); } } List<Collider> AttachBoundingBoxRagdollColliders (Bone b) { const string AttachmentNameMarker = "ragdoll"; var colliders = new List<Collider>(); Transform t = boneTable[b]; GameObject go = t.gameObject; var skin = skeleton.Skin ?? skeleton.Data.DefaultSkin; var attachments = new List<Attachment>(); foreach (Slot s in skeleton.Slots) { if (s.Bone == b) { skin.FindAttachmentsForSlot(skeleton.Slots.IndexOf(s), attachments); foreach (var a in attachments) { var bbAttachment = a as BoundingBoxAttachment; if (bbAttachment != null) { if (!a.Name.ToLower().Contains(AttachmentNameMarker)) continue; var bbCollider = go.AddComponent<BoxCollider>(); var bounds = SkeletonUtility.GetBoundingBoxBounds(bbAttachment, thickness); bbCollider.center = bounds.center; bbCollider.size = bounds.size; colliders.Add(bbCollider); } } } } return colliders; } static float GetPropagatedRotation (Bone b) { Bone parent = b.Parent; float a = b.AppliedRotation; while (parent != null) { a += parent.AppliedRotation; parent = parent.parent; } return a; } public class LayerFieldAttribute : PropertyAttribute {} } }
412
0.920094
1
0.920094
game-dev
MEDIA
0.976709
game-dev
0.975655
1
0.975655
kkuramitsu/othello2024
3,872
Fox42.py
import math BLACK = 1 WHITE = 2 # 初期の盤面 board = [ [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 1, 2, 0, 0], [0, 0, 2, 1, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], ] # 石を置く def apply_move(board, stone, x, y): new_board = [row[:] for row in board] new_board[y][x] = stone opponent = 3 - stone directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] for dx, dy in directions: nx, ny = x + dx, y + dy stones_to_flip = [] while 0 <= nx < len(new_board[0]) and 0 <= ny < len(new_board) and new_board[ny][nx] == opponent: stones_to_flip.append((nx, ny)) nx += dx ny += dy if stones_to_flip and 0 <= nx < len(new_board[0]) and 0 <= ny < len(new_board) and new_board[ny][nx] == stone: for flip_x, flip_y in stones_to_flip: new_board[flip_y][flip_x] = stone return new_board # 有効な手を取得 def get_valid_moves(board, stone): valid_moves = [] for y in range(len(board)): for x in range(len(board[0])): if can_place_x_y(board, stone, x, y): valid_moves.append((x, y)) return valid_moves # 手を置けるかチェック def can_place_x_y(board, stone, x, y): if board[y][x] != 0: return False opponent = 3 - stone directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] for dx, dy in directions: nx, ny = x + dx, y + dy found_opponent = False while 0 <= nx < len(board[0]) and 0 <= ny < len(board) and board[ny][nx] == opponent: nx += dx ny += dy found_opponent = True if found_opponent and 0 <= nx < len(board[0]) and 0 <= ny < len(board) and board[ny][nx] == stone: return True return False # 評価関数 def evaluate_board(board, stone): weight = [ [10, 5, 5, 5, 5, 10], [5, 1, 2, 2, 1, 5], [5, 2, 0, 0, 2, 5], [5, 2, 0, 0, 2, 5], [5, 1, 2, 2, 1, 5], [10, 5, 5, 5, 5, 10] ] score = 0 for y in range(len(board)): for x in range(len(board[0])): if board[y][x] == stone: score += weight[y][x] return score # ミニマックス法 def minimax(board, stone, depth, maximizing_player, alpha=-math.inf, beta=math.inf): valid_moves = get_valid_moves(board, stone) # 終端条件: 深さ0またはこれ以上石を置けない場合 if depth == 0 or not valid_moves: return evaluate_board(board, stone) if maximizing_player: max_eval = -math.inf for x, y in valid_moves: new_board = apply_move(board, stone, x, y) eval = minimax(new_board, 3 - stone, depth - 1, False, alpha, beta) max_eval = max(max_eval, eval) alpha = max(alpha, eval) if beta <= alpha: break # βカット return max_eval else: min_eval = math.inf for x, y in valid_moves: new_board = apply_move(board, stone, x, y) eval = minimax(new_board, 3 - stone, depth - 1, True, alpha, beta) min_eval = min(min_eval, eval) beta = min(beta, eval) if beta <= alpha: break # αカット return min_eval # FoxAI クラス class FoxAI: def name(self): return "FoxAI" def face(self): return "🦊" def place(self, board, stone): valid_moves = get_valid_moves(board, stone) if not valid_moves: return None best_move = None best_score = -math.inf for x, y in valid_moves: temp_board = apply_move(board, stone, x, y) score = minimax(temp_board, 3 - stone, depth=5, maximizing_player=False) if score > best_score: best_score = score best_move = (x, y) return best_move
412
0.947884
1
0.947884
game-dev
MEDIA
0.562669
game-dev,ml-ai
0.95248
1
0.95248
Roblox/creator-docs
5,555
content/en-us/resources/battle-royale/pickup-system.md
--- title: Pickup system comments: description: Explains the pickup system for the Battle Royale game kit. prev: /resources/battle-royale/core-scripts next: /resources/battle-royale/building-system --- The Roblox Battle Royale **pickup system** lets players pick up different kinds of objects, although it's currently only used for weapon pickups. In game, weapons are spawned around the game map and — when players get close enough — an on-screen key/action/button prompt appears along with the weapon name and description. <img alt="Battle Royale Weapon Example" src="../../assets/resources/battle-royale/pickup-system/Battle-Royale-Weapon-Pickup.jpg" width="100%" /> <Alert severity="info"> Roblox Battle Royale uses the [Weapons Kit](../../resources/weapons-kit.md), so please consult its documentation for details and customization options. </Alert> ## Structure There are several important folders related to the pickup system. Make sure that these folders are set up correctly in your project: - `Workspace/PickupSpawners` — Contains pickup spawner `Class.Part|Parts` which tell the system where to place visual pickup `Class.Model|Models` (see the next point). Note that these spawners are **not required** to be in this folder since the system looks for parts tagged with the **PickupSpawner** tag instead of the folder path. <img alt="Pickup Spawners" src="../../assets/resources/battle-royale/pickup-system/Battle-Royale-PickupSpawners.png" width="320" /> <Alert severity="info"> Pickup spawners can be placed at any physical location in the game, but they will choose a weapon **randomly** from `ReplicatedStorage/Assets/Weapons` and use the name-matched pickup model as a visual representation. </Alert> - `ReplicatedStorage/Assets/Weapons` — Contains the weapons (functional `Class.Tool|Tools`) that the pickup system grants when a weapon pickup is activated. <img alt="Battle Royale Items" src="../../assets/resources/battle-royale/pickup-system/Battle-Royale-Weapons.png" width="320" /> - `ReplicatedStorage/Assets/Pickups` — Contains the pickup `Class.Model|Models` that the system will place at pickup spawners in the game world. **These should be visual models only**, not functional weapon Tools. <img alt="Battle Royale Pickups" src="../../assets/resources/battle-royale/pickup-system/Battle-Royale-Pickups.png" width="320" /> ## Add new pickups As noted above, pickups require both a functional `Class.Tool` and a visual `Class.Model` that will be spawned in the game world. ### Tool 1. Create a `Class.Tool` and give it a unique name. You can create new weapons based upon those in the [Weapons Kit](../../resources/weapons-kit.md) or take tools from the [Toolbox](../../projects/assets/toolbox.md). 2. Place the `Class.Tool` in `ReplicatedStorage/Assets/Weapons`. <img alt="Battle Royale New Weapon" src="../../assets/resources/battle-royale/pickup-system/Battle-Royale-New-Weapon.png" width="320" /> ### Model 1. Create a `Class.Model` for the visual pickup and give it the **same name** as you gave the `Class.Tool`. 2. Through the [Tags](../../studio/properties.md#instance-tags) section of its properties, apply the following tags to the model: - **Action** - **Pickup** - **WeaponPickup** - **WeaponSystemIgnore** - One of the rarity tags as outlined in [Rarity](#rarity). 3. Place the model in `ReplicatedStorage/Assets/Pickups`. <img alt="Battle Royale New Pickup" src="../../assets/resources/battle-royale/pickup-system/Battle-Royale-New-Pickup.png" width="320" /> ### Rarity Pickup rarity is not defined by any mathematical formula, but you can associate an on-screen GUI like those pictured below to suggest an item's rarity. 1. Open the `ReplicatedFirst/Configurations/RarityConfiguration` script. This script contains tables for each rarity category, each of which includes a color value (`Color`) for the pickup's particle effect and an asset ID (`Image`) for the on-screen GUI background. For each GUI: - The item name will appear as the model/weapon name. - The description will appear as the rarity name (such as **Epic**) plus **Item**. The default rarities are as follows, but feel free to define your own. <table> <thead> <tr> <th>Rarity</th> <th>GUI</th> </tr> </thead> <tbody> <tr> <td>Common</td> <td><img src="../../assets/resources/battle-royale/pickup-system/Battle-Royale-Item-Common.png" width="45%" /></td> </tr> <tr> <td>Uncommon</td> <td><img src="../../assets/resources/battle-royale/pickup-system/Battle-Royale-Item-Uncommon.png" width="45%" /></td> </tr> <tr> <td>Rare</td> <td><img src="../../assets/resources/battle-royale/pickup-system/Battle-Royale-Item-Rare.png" width="45%" /></td> </tr> <tr> <td>Epic</td> <td><img src="../../assets/resources/battle-royale/pickup-system/Battle-Royale-Item-Epic.png" width="45%" /></td> </tr> <tr> <td>Legendary</td> <td><img src="../../assets/resources/battle-royale/pickup-system/Battle-Royale-Item-Legendary.png" width="45%" /></td> </tr> <tr> <td>Special</td> <td><img src="../../assets/resources/battle-royale/pickup-system/Battle-Royale-Item-Special.png" width="45%" /></td> </tr> </tbody> </table> 2. For the pickup `Class.Model` you created previously (located in `ReplicatedStorage/Assets/Pickups`), assign one of the tags you've defined in the `RarityConfiguration` script.
412
0.850014
1
0.850014
game-dev
MEDIA
0.841901
game-dev
0.61411
1
0.61411
Kaedrin/nwn2cc
2,703
NWN2 WIP/Source/ScriptMaster_146/nx_s2_damnation.NSS
//:://///////////////////////////////////////////// //:: Damnation //:: nx_s2_damnation //:: Copyright (c) 2007 Obsidian Entertainment, Inc. //::////////////////////////////////////////////// /* Classes: Cleric, Warlock Spellcraft Required: 33 Caster Level: Epic Innate Level: Epic School: Enchantment Descriptor(s): Teleportation Components: Verbal, Somatic Range: Touch Area of Effect / Target: Creature touched Duration: Instant Save: Will negates (DC +5) Spell Resistance: Yes You banish a single foe to the Hells, with no possibility of return. You must succeed at a melee touch attack, and the target must fail at a Will saving throw (DC +5). If the target fails the saving throw, it is dragged screaming into the Hells, to be tormented and ultimately devoured by fiends. Creatures that succeed at their saving throw are nonetheless exhausted from resisting so powerful an enchantment, and they are Dazed for 1d6+1 rounds. */ //::////////////////////////////////////////////// //:: Created By: Andrew Woo //:: Created On: 04/12/2007 //::////////////////////////////////////////////// //:: AFW-OEI 06/25/2007: Reduce DC from +15 to +5. //:: AFW-OEI 07/11/2007: Defer to NX1 Damnation hit VFX in spells.2da. //:: RPGplayer1 03/25/2008: Uses epic spell save workaround #include "X0_I0_SPELLS" #include "x2_i0_spells" #include "x2_inc_spellhook" #include "nx1_inc_epicsave" void main() { if (!X2PreSpellCastCode()) { // If code within the PreSpellCastHook (i.e. UMD) reports FALSE, do not run this spell return; } int nSaveDC = GetEpicSpellSaveDC2(SPELL_SCHOOL_ENCHANTMENT) + 5; int nDazeDuration = d6(1) + 1; object oTarget = GetSpellTargetObject(); //effect eVis = EffectVisualEffect(VFX_HIT_SPELL_EVIL); effect eDeath = EffectDeath(FALSE, TRUE, TRUE); // No spectacular death, yes display feedback, yes ignore death immunity. effect eDaze = EffectDazed(); // Make a melee touch attack. if (TouchAttackMelee(oTarget) != FALSE) { // If we succeed at a melee touch attack if (spellsIsTarget(oTarget, SPELL_TARGET_STANDARDHOSTILE, OBJECT_SELF)) { SignalEvent(oTarget, EventSpellCastAt(OBJECT_SELF, GetSpellId(), TRUE)); if (!MyResistSpell(OBJECT_SELF, oTarget)) { //ApplyEffectToObject(DURATION_TYPE_INSTANT, eVis, oTarget); if (!MySavingThrow(SAVING_THROW_WILL, oTarget, nSaveDC, SAVING_THROW_TYPE_SPELL, OBJECT_SELF)) { // Fail save and die. DelayCommand(1.0, ApplyEffectToObject(DURATION_TYPE_INSTANT, eDeath, oTarget)); } else { // Make save, so be dazed. DelayCommand(1.0, ApplyEffectToObject(DURATION_TYPE_TEMPORARY, eDaze, oTarget, RoundsToSeconds(nDazeDuration))); } } } } }
412
0.894147
1
0.894147
game-dev
MEDIA
0.983034
game-dev
0.989321
1
0.989321
Unity-Technologies/com.unity.multiplayer.samples.coop
6,936
Assets/Scripts/Editor/SceneBootstrapper.cs
using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; namespace Unity.BossRoom.Editor { /// <summary> /// Class that permits auto-loading a bootstrap scene when the editor switches play state. This class is /// initialized when Unity is opened and when scripts are recompiled. This is to be able to subscribe to /// EditorApplication's playModeStateChanged event, which is when we wish to open a new scene. /// </summary> /// <remarks> /// A critical edge case scenario regarding NetworkManager is accounted for here. /// A NetworkObject's GlobalObjectIdHash value is currently generated in OnValidate() which is invoked during a /// build and when the asset is loaded/viewed in the editor. /// If we were to manually open Bootstrap scene via EditorSceneManager.OpenScene(...) as the editor is exiting play /// mode, Bootstrap scene would be entering play mode within the editor prior to having loaded any assets, meaning /// NetworkManager itself has no entry within the AssetDatabase cache. As a result of this, any referenced Network /// Prefabs wouldn't have any entry either. /// To account for this necessary AssetDatabase step, whenever we're redirecting from a new scene, or a scene /// existing in our EditorBuildSettings, we forcefully stop the editor, open Bootstrap scene, and re-enter play /// mode. This provides the editor the chance to create AssetDatabase cache entries for the Network Prefabs assigned /// to the NetworkManager. /// If we are entering play mode directly from Bootstrap scene, no additional steps need to be taken and the scene /// is loaded normally. /// </remarks> [InitializeOnLoad] public class SceneBootstrapper { const string k_PreviousSceneKey = "PreviousScene"; const string k_ShouldLoadBootstrapSceneKey = "LoadBootstrapScene"; const string k_LoadBootstrapSceneOnPlay = "Boss Room/Load Bootstrap Scene On Play"; const string k_DoNotLoadBootstrapSceneOnPlay = "Boss Room/Don't Load Bootstrap Scene On Play"; const string k_TestRunnerSceneName = "InitTestScene"; static bool s_RestartingToSwitchScene; static string BootstrapScene => EditorBuildSettings.scenes[0].path; // to track where to go back to static string PreviousScene { get => EditorPrefs.GetString(k_PreviousSceneKey); set => EditorPrefs.SetString(k_PreviousSceneKey, value); } static bool ShouldLoadBootstrapScene { get { if (!EditorPrefs.HasKey(k_ShouldLoadBootstrapSceneKey)) { EditorPrefs.SetBool(k_ShouldLoadBootstrapSceneKey, true); } return EditorPrefs.GetBool(k_ShouldLoadBootstrapSceneKey, true); } set => EditorPrefs.SetBool(k_ShouldLoadBootstrapSceneKey, value); } static SceneBootstrapper() { EditorApplication.playModeStateChanged += EditorApplicationOnplayModeStateChanged; } [MenuItem(k_LoadBootstrapSceneOnPlay, true)] static bool ShowLoadBootstrapSceneOnPlay() { return !ShouldLoadBootstrapScene; } [MenuItem(k_LoadBootstrapSceneOnPlay)] static void EnableLoadBootstrapSceneOnPlay() { ShouldLoadBootstrapScene = true; } [MenuItem(k_DoNotLoadBootstrapSceneOnPlay, true)] static bool ShowDoNotLoadBootstrapSceneOnPlay() { return ShouldLoadBootstrapScene; } [MenuItem(k_DoNotLoadBootstrapSceneOnPlay)] static void DisableDoNotLoadBootstrapSceneOnPlay() { ShouldLoadBootstrapScene = false; } static void EditorApplicationOnplayModeStateChanged(PlayModeStateChange playModeStateChange) { if (IsTestRunnerActive()) { return; } if (!ShouldLoadBootstrapScene) { return; } if (s_RestartingToSwitchScene) { if (playModeStateChange == PlayModeStateChange.EnteredPlayMode) { // for some reason there's multiple start and stops events happening while restarting the editor playmode. We're making sure to // set stoppingAndStarting only when we're done and we've entered playmode. This way we won't corrupt "activeScene" with the multiple // start and stop and will be able to return to the scene we were editing at first s_RestartingToSwitchScene = false; } return; } if (playModeStateChange == PlayModeStateChange.ExitingEditMode) { // cache previous scene so we return to this scene after play session, if possible PreviousScene = EditorSceneManager.GetActiveScene().path; if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) { // user either hit "Save" or "Don't Save"; open bootstrap scene if (!string.IsNullOrEmpty(BootstrapScene) && System.Array.Exists(EditorBuildSettings.scenes, scene => scene.path == BootstrapScene)) { var activeScene = EditorSceneManager.GetActiveScene(); s_RestartingToSwitchScene = activeScene.path == string.Empty || !BootstrapScene.Contains(activeScene.path); // we only manually inject Bootstrap scene if we are in a blank empty scene, // or if the active scene is not already BootstrapScene if (s_RestartingToSwitchScene) { EditorApplication.isPlaying = false; // scene is included in build settings; open it EditorSceneManager.OpenScene(BootstrapScene); EditorApplication.isPlaying = true; } } } else { // user either hit "Cancel" or exited window; don't open bootstrap scene & return to editor EditorApplication.isPlaying = false; } } else if (playModeStateChange == PlayModeStateChange.EnteredEditMode) { if (!string.IsNullOrEmpty(PreviousScene)) { EditorSceneManager.OpenScene(PreviousScene); } } } static bool IsTestRunnerActive() { return EditorSceneManager.GetActiveScene().name.StartsWith(k_TestRunnerSceneName); } } }
412
0.880495
1
0.880495
game-dev
MEDIA
0.939812
game-dev
0.922627
1
0.922627
espertechinc/nesper
16,424
src/NEsper.Common/common/internal/event/property/IndexedProperty.cs
/////////////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2006-2024 Esper Team. All rights reserved. / // http://esper.codehaus.org / // ---------------------------------------------------------------------------------- / // The software in this package is published under the terms of the GPL license / // a copy of which has been included with this distribution in the license.txt file. / /////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.IO; using com.espertech.esper.common.client; using com.espertech.esper.common.@internal.@event.arr; using com.espertech.esper.common.@internal.@event.bean.core; using com.espertech.esper.common.@internal.@event.bean.getter; using com.espertech.esper.common.@internal.@event.bean.service; using com.espertech.esper.common.@internal.@event.core; using com.espertech.esper.common.@internal.@event.map; using com.espertech.esper.common.@internal.@event.xml; using com.espertech.esper.common.@internal.util; using com.espertech.esper.compat.collections; namespace com.espertech.esper.common.@internal.@event.property { /// <summary> /// Represents an indexed property or array property, ie. an 'value' property with read method getValue(int index) /// or a 'array' property via read method getArray() returning an array. /// </summary> public class IndexedProperty : PropertyBase, PropertyWithIndex { private int _index; public IndexedProperty(string propertyName) : base(propertyName) { } /// <summary> /// Ctor. /// </summary> /// <param name="propertyName">is the property name</param> /// <param name="index">is the index to use to access the property value</param> public IndexedProperty( string propertyName, int index) : base(propertyName) { _index = index; } public override bool IsDynamic => false; public override string[] ToPropertyArray() { return new string[] { PropertyNameAtomic }; } /// <summary> /// Returns index for indexed access. /// </summary> /// <value>index value</value> public int Index => _index; public override EventPropertyGetterSPI GetGetter( BeanEventType eventType, EventBeanTypedEventFactory eventBeanTypedEventFactory, BeanEventTypeFactory beanEventTypeFactory) { var propertyDesc = eventType.GetIndexedProperty(PropertyNameAtomic); if (propertyDesc is { IsIndexedReadMethod: true }) { return new KeyedMethodPropertyGetter( propertyDesc.ReadMethod, _index, eventBeanTypedEventFactory, beanEventTypeFactory); } // Try the array as a simple property propertyDesc = eventType.GetSimpleProperty(PropertyNameAtomic); if (propertyDesc == null) { return null; } var returnType = propertyDesc.ReturnType; if (returnType.IsArray) { return GetGetterFromArray( eventBeanTypedEventFactory, beanEventTypeFactory, propertyDesc); } if (returnType.IsGenericList()) { return GetGetterFromList( eventBeanTypedEventFactory, beanEventTypeFactory, propertyDesc); } if (returnType.IsGenericEnumerable() || returnType.IsImplementsInterface(typeof(System.Collections.IEnumerable))) { return GetGetterFromEnumerable( eventBeanTypedEventFactory, beanEventTypeFactory, propertyDesc); } return null; } private EventPropertyGetterSPI GetGetterFromEnumerable( EventBeanTypedEventFactory eventBeanTypedEventFactory, BeanEventTypeFactory beanEventTypeFactory, PropertyStem propertyDesc) { if (propertyDesc.AccessorProp != null) { return new IterablePropertyPropertyGetter( propertyDesc.AccessorProp, Index, eventBeanTypedEventFactory, beanEventTypeFactory); } if (propertyDesc.IsSimpleReadMethod) { return new IterableMethodPropertyGetter( propertyDesc.ReadMethod, Index, eventBeanTypedEventFactory, beanEventTypeFactory); } if (propertyDesc.AccessorField != null) { return new IterableFieldPropertyGetter( propertyDesc.AccessorField, Index, eventBeanTypedEventFactory, beanEventTypeFactory); } throw new EPRuntimeException("unable to determine property enumerator accessor"); } private EventPropertyGetterSPI GetGetterFromList( EventBeanTypedEventFactory eventBeanTypedEventFactory, BeanEventTypeFactory beanEventTypeFactory, PropertyStem propertyDesc) { var prop = propertyDesc.AccessorProp; if (prop != null) { return new ListPropertyPropertyGetter(prop, Index, eventBeanTypedEventFactory, beanEventTypeFactory); } if (propertyDesc.IsSimpleReadMethod) { var method = propertyDesc.ReadMethod; return new ListMethodPropertyGetter( method, Index, eventBeanTypedEventFactory, beanEventTypeFactory); } var field = propertyDesc.AccessorField; if (field != null) { return new ListFieldPropertyGetter(field, Index, eventBeanTypedEventFactory, beanEventTypeFactory); } throw new EPRuntimeException("unable to determine property list accessor"); } private EventPropertyGetterSPI GetGetterFromArray( EventBeanTypedEventFactory eventBeanTypedEventFactory, BeanEventTypeFactory beanEventTypeFactory, PropertyStem propertyDesc) { var prop = propertyDesc.AccessorProp; if (prop != null) { return new ArrayPropertyPropertyGetter(prop, Index, eventBeanTypedEventFactory, beanEventTypeFactory); } if (propertyDesc.IsSimpleReadMethod) { var method = propertyDesc.ReadMethod; return new ArrayMethodPropertyGetter( method, Index, eventBeanTypedEventFactory, beanEventTypeFactory); } var field = propertyDesc.AccessorField; if (field != null) { return new ArrayFieldPropertyGetter(field, Index, eventBeanTypedEventFactory, beanEventTypeFactory); } throw new EPRuntimeException("unable to determine property array accessor"); } public override Type GetPropertyType( BeanEventType eventType, BeanEventTypeFactory beanEventTypeFactory) { var descriptor = eventType.GetIndexedProperty(PropertyNameAtomic); if (descriptor is { IsIndexedReadMethod: true }) { return descriptor.ReturnType; } // Check if this is an method returning array which is a type of simple property descriptor = eventType.GetSimpleProperty(PropertyNameAtomic); if (descriptor == null) { return null; } var returnType = descriptor.ReturnType; if (returnType.IsArray) { return returnType.GetComponentType(); } if (returnType.IsGenericDictionary()) { // no-op since we do not treat dictionaries as indexable... } else if (returnType.IsGenericEnumerable() || returnType.IsImplementsInterface(typeof(System.Collections.IEnumerable))) { if (descriptor.AccessorProp != null) { return TypeHelper.GetGenericPropertyType(descriptor.AccessorProp, false); } if (descriptor.ReadMethod != null) { return TypeHelper.GetGenericReturnType(descriptor.ReadMethod, false); } if (descriptor.AccessorField != null) { return TypeHelper.GetGenericFieldType(descriptor.AccessorField, false); } return null; } return null; } public override Type GetPropertyTypeMap( IDictionary<string, object> optionalMapPropTypes, BeanEventTypeFactory beanEventTypeFactory) { var type = optionalMapPropTypes.Get(PropertyNameAtomic); if (type == null) { return null; } if (type is TypeBeanOrUnderlying[] typeBeanOrUnderlyings) { var innerType = typeBeanOrUnderlyings[0].EventType; if (innerType is MapEventType) { return typeof(IDictionary<string, object>); } } else { if (type is Type { IsArray: true } typeClass) { return typeClass.GetElementType(); } } return null; } public override MapEventPropertyGetter GetGetterMap( IDictionary<string, object> optionalMapPropTypes, EventBeanTypedEventFactory eventBeanTypedEventFactory, BeanEventTypeFactory beanEventTypeFactory) { var type = optionalMapPropTypes.Get(PropertyNameAtomic); if (type == null) { return null; } if (type is TypeBeanOrUnderlying[] typeBeanOrUnderlyings) { var innerType = typeBeanOrUnderlyings[0].EventType; if (innerType is MapEventType) { return new MapArrayPropertyGetter( PropertyNameAtomic, _index, eventBeanTypedEventFactory, innerType); } } else if (type is Type asType) { if (asType.IsArray) { var componentType = asType.GetElementType(); // its an array return new MapArrayPONOEntryIndexedPropertyGetter( PropertyNameAtomic, _index, eventBeanTypedEventFactory, beanEventTypeFactory, componentType); } } return null; } public override void ToPropertyEPL(TextWriter writer) { writer.Write(PropertyNameAtomic); writer.Write("["); writer.Write(_index); writer.Write("]"); } public override EventPropertyGetterSPI GetterDOM => new DOMIndexedGetter(PropertyNameAtomic, _index, null); public override EventPropertyGetterSPI GetGetterDOM( SchemaElementComplex complexProperty, EventBeanTypedEventFactory eventBeanTypedEventFactory, BaseXMLEventType eventType, string propertyExpression) { foreach (var simple in complexProperty.SimpleElements) { if (!simple.IsArray) { continue; } if (!simple.Name.Equals(PropertyNameAtomic)) { continue; } return new DOMIndexedGetter(PropertyNameAtomic, _index, null); } foreach (var complex in complexProperty.ComplexElements) { if (!complex.IsArray) { continue; } if (!complex.Name.Equals(PropertyNameAtomic)) { continue; } return new DOMIndexedGetter( PropertyNameAtomic, _index, new FragmentFactoryDOMGetter(eventBeanTypedEventFactory, eventType, propertyExpression)); } return null; } public override SchemaItem GetPropertyTypeSchema(SchemaElementComplex complexProperty) { foreach (var simple in complexProperty.SimpleElements) { if (!simple.IsArray) { continue; } if (!simple.Name.Equals(PropertyNameAtomic)) { continue; } // return the simple as a non-array since an index is provided return new SchemaElementSimple( simple.Name, simple.Namespace, simple.SimpleType, simple.TypeName, false, simple.FractionDigits); } foreach (var complex in complexProperty.ComplexElements) { if (!complex.IsArray) { continue; } if (!complex.Name.Equals(PropertyNameAtomic)) { continue; } // return the complex as a non-array since an index is provided return new SchemaElementComplex( complex.Name, complex.Namespace, complex.Attributes, complex.ComplexElements, complex.SimpleElements, false, complex.OptionalSimpleType, complex.OptionalSimpleTypeName); } return null; } /// <summary> /// Returns the index number for an indexed property expression. /// </summary> /// <param name="propertyName">property expression</param> /// <returns>index</returns> public static int GetIndex(string propertyName) { var start = propertyName.IndexOf('['); var end = propertyName.IndexOf(']'); var indexStr = propertyName.Substring(start, end); return int.Parse(indexStr); } public override ObjectArrayEventPropertyGetter GetGetterObjectArray( IDictionary<string, int> indexPerProperty, IDictionary<string, object> nestableTypes, EventBeanTypedEventFactory eventBeanTypedEventFactory, BeanEventTypeFactory beanEventTypeFactory) { if (!indexPerProperty.TryGetValue(PropertyNameAtomic, out var propertyIndex)) { return null; } var type = nestableTypes.Get(PropertyNameAtomic); if (type == null) { return null; } if (type is TypeBeanOrUnderlying[] typeBeanOrUnderlyings) { var innerType = typeBeanOrUnderlyings[0].EventType; if (!(innerType is ObjectArrayEventType)) { return null; } return new ObjectArrayArrayPropertyGetter( propertyIndex, _index, eventBeanTypedEventFactory, innerType); } if (type is Type asType && asType.IsArray) { var componentType = asType.GetElementType(); // its an array return new ObjectArrayArrayPONOEntryIndexedPropertyGetter( propertyIndex, _index, eventBeanTypedEventFactory, beanEventTypeFactory, componentType); } return null; } } } // end of namespace
412
0.930206
1
0.930206
game-dev
MEDIA
0.346022
game-dev
0.929677
1
0.929677
walbourn/directx-vs-templates
4,581
d3d11game_win32_dr/Game.cpp
// // Game.cpp // #include "pch.h" #include "Game.h" extern void ExitGame() noexcept; using namespace DirectX; using Microsoft::WRL::ComPtr; Game::Game() noexcept(false) { m_deviceResources = std::make_unique<DX::DeviceResources>(); // TODO: Provide parameters for swapchain format, depth/stencil format, and backbuffer count. // Add DX::DeviceResources::c_AllowTearing to opt-in to variable rate displays. // Add DX::DeviceResources::c_EnableHDR for HDR10 display. m_deviceResources->RegisterDeviceNotify(this); } // Initialize the Direct3D resources required to run. void Game::Initialize(HWND window, int width, int height) { m_deviceResources->SetWindow(window, width, height); m_deviceResources->CreateDeviceResources(); CreateDeviceDependentResources(); m_deviceResources->CreateWindowSizeDependentResources(); CreateWindowSizeDependentResources(); // TODO: Change the timer settings if you want something other than the default variable timestep mode. // e.g. for 60 FPS fixed timestep update logic, call: /* m_timer.SetFixedTimeStep(true); m_timer.SetTargetElapsedSeconds(1.0 / 60); */ } #pragma region Frame Update // Executes the basic game loop. void Game::Tick() { m_timer.Tick([&]() { Update(m_timer); }); Render(); } // Updates the world. void Game::Update(DX::StepTimer const& timer) { float elapsedTime = float(timer.GetElapsedSeconds()); // TODO: Add your game logic here. elapsedTime; } #pragma endregion #pragma region Frame Render // Draws the scene. void Game::Render() { // Don't try to render anything before the first Update. if (m_timer.GetFrameCount() == 0) { return; } Clear(); m_deviceResources->PIXBeginEvent(L"Render"); auto context = m_deviceResources->GetD3DDeviceContext(); // TODO: Add your rendering code here. context; m_deviceResources->PIXEndEvent(); // Show the new frame. m_deviceResources->Present(); } // Helper method to clear the back buffers. void Game::Clear() { m_deviceResources->PIXBeginEvent(L"Clear"); // Clear the views. auto context = m_deviceResources->GetD3DDeviceContext(); auto renderTarget = m_deviceResources->GetRenderTargetView(); auto depthStencil = m_deviceResources->GetDepthStencilView(); context->ClearRenderTargetView(renderTarget, Colors::CornflowerBlue); context->ClearDepthStencilView(depthStencil, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); context->OMSetRenderTargets(1, &renderTarget, depthStencil); // Set the viewport. const auto viewport = m_deviceResources->GetScreenViewport(); context->RSSetViewports(1, &viewport); m_deviceResources->PIXEndEvent(); } #pragma endregion #pragma region Message Handlers // Message handlers void Game::OnActivated() { // TODO: Game is becoming active window. } void Game::OnDeactivated() { // TODO: Game is becoming background window. } void Game::OnSuspending() { // TODO: Game is being power-suspended (or minimized). } void Game::OnResuming() { m_timer.ResetElapsedTime(); // TODO: Game is being power-resumed (or returning from minimize). } void Game::OnWindowMoved() { const auto r = m_deviceResources->GetOutputSize(); m_deviceResources->WindowSizeChanged(r.right, r.bottom); } void Game::OnDisplayChange() { m_deviceResources->UpdateColorSpace(); } void Game::OnWindowSizeChanged(int width, int height) { if (!m_deviceResources->WindowSizeChanged(width, height)) return; CreateWindowSizeDependentResources(); // TODO: Game window is being resized. } // Properties void Game::GetDefaultSize(int& width, int& height) const noexcept { // TODO: Change to desired default window size (note minimum size is 320x200). width = 800; height = 600; } #pragma endregion #pragma region Direct3D Resources // These are the resources that depend on the device. void Game::CreateDeviceDependentResources() { auto device = m_deviceResources->GetD3DDevice(); // TODO: Initialize device dependent objects here (independent of window size). device; } // Allocate all memory resources that change on a window SizeChanged event. void Game::CreateWindowSizeDependentResources() { // TODO: Initialize windows-size dependent objects here. } void Game::OnDeviceLost() { // TODO: Add Direct3D resource cleanup here. } void Game::OnDeviceRestored() { CreateDeviceDependentResources(); CreateWindowSizeDependentResources(); } #pragma endregion
412
0.915959
1
0.915959
game-dev
MEDIA
0.767841
game-dev,graphics-rendering
0.931098
1
0.931098
DynamicTreesTeam/DynamicTrees
1,376
src/main/java/com/ferreusveritas/dynamictrees/systems/nodemapper/DiseaseNode.java
package com.ferreusveritas.dynamictrees.systems.nodemapper; import com.ferreusveritas.dynamictrees.api.TreeHelper; import com.ferreusveritas.dynamictrees.api.network.NodeInspector; import com.ferreusveritas.dynamictrees.block.branch.BranchBlock; import com.ferreusveritas.dynamictrees.tree.species.Species; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.block.state.BlockState; /** * Destroys all thin(radius == 1) branches on a tree.. leaving it to postRot. * * @author ferreusveritas */ public class DiseaseNode implements NodeInspector { Species species;//Destroy any thin branches made of the same kind of wood. public DiseaseNode(Species tree) { this.species = tree; } @Override public boolean run(BlockState state, LevelAccessor level, BlockPos pos, Direction fromDir) { BranchBlock branch = TreeHelper.getBranch(state); if (branch != null && species.getFamily() == branch.getFamily()) { if (branch.getRadius(state) == 1) { level.removeBlock(pos, false);//Destroy the thin branch } } return true; } @Override public boolean returnRun(BlockState state, LevelAccessor level, BlockPos pos, Direction fromDir) { return false; } }
412
0.923216
1
0.923216
game-dev
MEDIA
0.949014
game-dev
0.76792
1
0.76792
CyberdyneCC/Thermos
19,349
patches/net/minecraft/server/management/ItemInWorldManager.java.patch
--- ../src-base/minecraft/net/minecraft/server/management/ItemInWorldManager.java +++ ../src-work/minecraft/net/minecraft/server/management/ItemInWorldManager.java @@ -4,6 +4,7 @@ import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemSword; import net.minecraft.network.play.server.S23PacketBlockChange; @@ -13,13 +14,32 @@ import net.minecraft.world.WorldSettings; import net.minecraftforge.common.ForgeHooks; import net.minecraftforge.common.MinecraftForge; -import cpw.mods.fml.common.eventhandler.Event; import net.minecraftforge.event.ForgeEventFactory; import net.minecraftforge.event.entity.player.PlayerDestroyItemEvent; -import net.minecraftforge.event.entity.player.PlayerInteractEvent; -import net.minecraftforge.event.entity.player.PlayerInteractEvent.Action; import net.minecraftforge.event.world.BlockEvent; +// CraftBukkit start +import net.minecraft.init.Blocks; + +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.craftbukkit.inventory.CraftInventory; +import org.bukkit.event.Event; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; + +// CraftBukkit end +// Cauldron start +import net.minecraft.inventory.ContainerPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.server.MinecraftServer; + +import org.bukkit.craftbukkit.inventory.CraftInventoryView; +import org.bukkit.event.inventory.InventoryType; +// Cauldron end + +import cpw.mods.fml.common.FMLLog; + public class ItemInWorldManager { /** Forge reach distance */ @@ -135,15 +155,27 @@ public void onBlockClicked(int p_73074_1_, int p_73074_2_, int p_73074_3_, int p_73074_4_) { + // CraftBukkit start if (!this.gameType.isAdventure() || this.thisPlayerMP.isCurrentToolAdventureModeExempt(p_73074_1_, p_73074_2_, p_73074_3_)) { - PlayerInteractEvent event = ForgeEventFactory.onPlayerInteract(thisPlayerMP, Action.LEFT_CLICK_BLOCK, p_73074_1_, p_73074_2_, p_73074_3_, p_73074_4_, theWorld); - if (event.isCanceled()) + org.bukkit.event.player.PlayerInteractEvent cbEvent = CraftEventFactory.callPlayerInteractEvent(this.thisPlayerMP, Action.LEFT_CLICK_BLOCK, p_73074_1_, p_73074_2_, p_73074_3_, p_73074_4_, this.thisPlayerMP.inventory.getCurrentItem()); + net.minecraftforge.event.entity.player.PlayerInteractEvent event = ForgeEventFactory.onPlayerBukkitInteract(this.thisPlayerMP, net.minecraftforge.event.entity.player.PlayerInteractEvent.Action.LEFT_CLICK_BLOCK, p_73074_1_, p_73074_2_, p_73074_3_, p_73074_4_, theWorld, cbEvent); // Forge + if (event.isCanceled()) { - thisPlayerMP.playerNetServerHandler.sendPacket(new S23PacketBlockChange(p_73074_1_, p_73074_2_, p_73074_3_, theWorld)); + // Let the client know the block still exists + ((EntityPlayerMP) this.thisPlayerMP).playerNetServerHandler.sendPacket(new S23PacketBlockChange(p_73074_1_, p_73074_2_, p_73074_3_, this.theWorld)); + // Update any tile entity data for this block + TileEntity tileentity = this.theWorld.getTileEntity(p_73074_1_, p_73074_2_, p_73074_3_); + + if (tileentity != null) + { + this.thisPlayerMP.playerNetServerHandler.sendPacket(tileentity.getDescriptionPacket()); + } + return; } + // CraftBukkit end if (this.isCreative()) { if (!this.theWorld.extinguishFire((EntityPlayer)null, p_73074_1_, p_73074_2_, p_73074_3_, p_73074_4_)) @@ -157,30 +189,56 @@ float f = 1.0F; Block block = this.theWorld.getBlock(p_73074_1_, p_73074_2_, p_73074_3_); - - if (!block.isAir(theWorld, p_73074_1_, p_73074_2_, p_73074_3_)) + // CraftBukkit start - Swings at air do *NOT* exist. + if (cbEvent.useInteractedBlock() == org.bukkit.event.Event.Result.DENY || event.useBlock == cpw.mods.fml.common.eventhandler.Event.Result.DENY) // Cauldron { - if (event.useBlock != Event.Result.DENY) + // If we denied a door from opening, we need to send a correcting update to the client, as it already opened the door. + if (block == Blocks.wooden_door) { - block.onBlockClicked(theWorld, p_73074_1_, p_73074_2_, p_73074_3_, thisPlayerMP); - theWorld.extinguishFire(null, p_73074_1_, p_73074_2_, p_73074_3_, p_73074_4_); + // For some reason *BOTH* the bottom/top part have to be marked updated. + boolean bottom = (this.theWorld.getBlockMetadata(p_73074_1_, p_73074_2_, p_73074_3_) & 8) == 0; + ((EntityPlayerMP) this.thisPlayerMP).playerNetServerHandler.sendPacket(new S23PacketBlockChange(p_73074_1_, p_73074_2_, p_73074_3_, this.theWorld)); + ((EntityPlayerMP) this.thisPlayerMP).playerNetServerHandler.sendPacket(new S23PacketBlockChange(p_73074_1_, p_73074_2_ + (bottom ? 1 : -1), p_73074_3_, this.theWorld)); } - else + else if (block == Blocks.trapdoor) { - thisPlayerMP.playerNetServerHandler.sendPacket(new S23PacketBlockChange(p_73074_1_, p_73074_2_, p_73074_3_, theWorld)); + ((EntityPlayerMP) this.thisPlayerMP).playerNetServerHandler.sendPacket(new S23PacketBlockChange(p_73074_1_, p_73074_2_, p_73074_3_, this.theWorld)); } - f = block.getPlayerRelativeBlockHardness(thisPlayerMP, thisPlayerMP.worldObj, p_73074_1_, p_73074_2_, p_73074_3_); } - - if (event.useItem == Event.Result.DENY) + else if (!block.isAir(theWorld, p_73074_1_, p_73074_2_, p_73074_3_)) { - if (f >= 1.0f) + block.onBlockClicked(this.theWorld, p_73074_1_, p_73074_2_, p_73074_3_, this.thisPlayerMP); + f = block.getPlayerRelativeBlockHardness(this.thisPlayerMP, this.thisPlayerMP.worldObj, p_73074_1_, p_73074_2_, p_73074_3_); + // Allow fire punching to be blocked + this.theWorld.extinguishFire((EntityPlayer) null, p_73074_1_, p_73074_2_, p_73074_3_, p_73074_4_); + } + if (cbEvent.useItemInHand() == org.bukkit.event.Event.Result.DENY || event.useItem == cpw.mods.fml.common.eventhandler.Event.Result.DENY) // Forge + { + // If we 'insta destroyed' then the client needs to be informed. + if (f > 1.0f) { - thisPlayerMP.playerNetServerHandler.sendPacket(new S23PacketBlockChange(p_73074_1_, p_73074_2_, p_73074_3_, theWorld)); + ((EntityPlayerMP) this.thisPlayerMP).playerNetServerHandler.sendPacket(new S23PacketBlockChange(p_73074_1_, p_73074_2_, p_73074_3_, this.theWorld)); } + return; } + org.bukkit.event.block.BlockDamageEvent blockEvent = CraftEventFactory.callBlockDamageEvent(this.thisPlayerMP, p_73074_1_, p_73074_2_, p_73074_3_, this.thisPlayerMP.inventory.getCurrentItem(), f >= 1.0f); + + if (blockEvent.isCancelled()) + { + // Let the client know the block still exists + ((EntityPlayerMP) this.thisPlayerMP).playerNetServerHandler.sendPacket(new S23PacketBlockChange(p_73074_1_, p_73074_2_, p_73074_3_, this.theWorld)); + return; + } + + if (blockEvent.getInstaBreak()) + { + f = 2.0f; + } + + // CraftBukkit end + if (!block.isAir(theWorld, p_73074_1_, p_73074_2_, p_73074_3_) && f >= 1.0F) { this.tryHarvestBlock(p_73074_1_, p_73074_2_, p_73074_3_); @@ -197,6 +255,10 @@ } } } + else + { + org.bukkit.event.player.PlayerInteractEvent cbEvent = CraftEventFactory.callPlayerInteractEvent(this.thisPlayerMP, Action.LEFT_CLICK_BLOCK, p_73074_1_, p_73074_2_, p_73074_3_, p_73074_4_, this.thisPlayerMP.inventory.getCurrentItem()); + } } public void uncheckedTryHarvestBlock(int p_73082_1_, int p_73082_2_, int p_73082_3_) @@ -269,6 +331,12 @@ return false; } Block block = this.theWorld.getBlock(p_73084_1_, p_73084_2_, p_73084_3_); + + if (block == Blocks.air) + { + return false; // CraftBukkit - A plugin set block to air without cancelling + } + int l = this.theWorld.getBlockMetadata(p_73084_1_, p_73084_2_, p_73084_3_); this.theWorld.playAuxSFXAtEntity(this.thisPlayerMP, 2001, p_73084_1_, p_73084_2_, p_73084_3_, Block.getIdFromBlock(block) + (this.theWorld.getBlockMetadata(p_73084_1_, p_73084_2_, p_73084_3_) << 12)); boolean flag = false; @@ -312,6 +380,7 @@ public boolean tryUseItem(EntityPlayer p_73085_1_, World p_73085_2_, ItemStack p_73085_3_) { int i = p_73085_3_.stackSize; + if (i <= 0) return false; int j = p_73085_3_.getItemDamage(); ItemStack itemstack1 = p_73085_3_.useItemRightClick(p_73085_2_, p_73085_1_); @@ -350,57 +419,113 @@ public boolean activateBlockOrUseItem(EntityPlayer p_73078_1_, World p_73078_2_, ItemStack p_73078_3_, int p_73078_4_, int p_73078_5_, int p_73078_6_, int p_73078_7_, float p_73078_8_, float p_73078_9_, float p_73078_10_) { - PlayerInteractEvent event = ForgeEventFactory.onPlayerInteract(p_73078_1_, Action.RIGHT_CLICK_BLOCK, p_73078_4_, p_73078_5_, p_73078_6_, p_73078_7_, p_73078_2_); - if (event.isCanceled()) - { - thisPlayerMP.playerNetServerHandler.sendPacket(new S23PacketBlockChange(p_73078_4_, p_73078_5_, p_73078_6_, theWorld)); - return false; - } + // CraftBukkit start - Interact + Block block = p_73078_2_.getBlock(p_73078_4_, p_73078_5_, p_73078_6_); + boolean isAir = block.isAir(p_73078_2_, p_73078_4_, p_73078_5_, p_73078_6_); // Cauldron + boolean denyResult = false, denyItem = false, denyBlock = false; - if (p_73078_3_ != null && p_73078_3_.getItem().onItemUseFirst(p_73078_3_, p_73078_1_, p_73078_2_, p_73078_4_, p_73078_5_, p_73078_6_, p_73078_7_, p_73078_8_, p_73078_9_, p_73078_10_)) + if (!isAir) { - if (p_73078_3_.stackSize <= 0) ForgeEventFactory.onPlayerDestroyItem(thisPlayerMP, p_73078_3_); - return true; - } + org.bukkit.event.player.PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent(p_73078_1_, org.bukkit.event.block.Action.RIGHT_CLICK_BLOCK, p_73078_4_, p_73078_5_, p_73078_6_, p_73078_7_, p_73078_3_); + net.minecraftforge.event.entity.player.PlayerInteractEvent forgeEvent = ForgeEventFactory.onPlayerBukkitInteract(p_73078_1_, net.minecraftforge.event.entity.player.PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK, p_73078_4_, p_73078_5_, p_73078_6_, p_73078_7_, p_73078_2_, event); + + // Cauldron start + // if forge event is explicitly cancelled, return + if (forgeEvent.isCanceled()) + { + thisPlayerMP.playerNetServerHandler.sendPacket(new S23PacketBlockChange(p_73078_4_, p_73078_5_, p_73078_6_, theWorld)); + return false; + } + denyItem = event.useItemInHand() == org.bukkit.event.Event.Result.DENY || forgeEvent.useItem == cpw.mods.fml.common.eventhandler.Event.Result.DENY; + denyBlock = event.useInteractedBlock() == org.bukkit.event.Event.Result.DENY || forgeEvent.useBlock == cpw.mods.fml.common.eventhandler.Event.Result.DENY; + denyResult = denyItem || denyBlock; + // if we have no explicit deny, check if item can be used + if (!denyItem) + { + Item item = (p_73078_3_ != null ? p_73078_3_.getItem() : null); + // try to use an item in hand before activating a block. Used for items such as IC2's wrench. + if (item != null && item.onItemUseFirst(p_73078_3_, p_73078_1_, p_73078_2_, p_73078_4_, p_73078_5_, p_73078_6_, p_73078_7_, p_73078_8_, p_73078_9_, p_73078_10_)) + { + if (p_73078_3_.stackSize <= 0) ForgeEventFactory.onPlayerDestroyItem(thisPlayerMP, p_73078_3_); + return true; + } + } + // Cauldron end + if (denyBlock) + { + // If we denied a door from opening, we need to send a correcting update to the client, as it already opened the door. + if (block == Blocks.wooden_door) + { + boolean bottom = (p_73078_2_.getBlockMetadata(p_73078_4_, p_73078_5_, p_73078_6_) & 8) == 0; + ((EntityPlayerMP) p_73078_1_).playerNetServerHandler.sendPacket(new S23PacketBlockChange(p_73078_4_, p_73078_5_ + (bottom ? 1 : -1), p_73078_6_, p_73078_2_)); + } + } + else if (!p_73078_1_.isSneaking() || p_73078_3_ == null || p_73078_1_.getHeldItem().getItem().doesSneakBypassUse(p_73078_2_, p_73078_4_, p_73078_5_, p_73078_6_, p_73078_1_)) + { + denyResult |= block.onBlockActivated(p_73078_2_, p_73078_4_, p_73078_5_, p_73078_6_, p_73078_1_, p_73078_7_, p_73078_8_, p_73078_9_, p_73078_10_); + // Cauldron start - if bukkitView is null, create one. Required for Ender Chests since they do not use NetworkRegistry.openRemoteGUI + if (thisPlayerMP != null && !(thisPlayerMP.openContainer instanceof ContainerPlayer)) + { + if (thisPlayerMP.openContainer.getBukkitView() == null) + { + TileEntity te = thisPlayerMP.worldObj.getTileEntity(p_73078_4_, p_73078_5_, p_73078_6_); + if (te != null && te instanceof IInventory) + { + IInventory teInv = (IInventory)te; + CraftInventory inventory = new CraftInventory(teInv); + thisPlayerMP.openContainer.bukkitView = new CraftInventoryView(thisPlayerMP.getBukkitEntity(), inventory, thisPlayerMP.openContainer); + } + else + { + thisPlayerMP.openContainer.bukkitView = new CraftInventoryView(thisPlayerMP.getBukkitEntity(), MinecraftServer.getServer().server.createInventory(thisPlayerMP.getBukkitEntity(), InventoryType.CHEST), thisPlayerMP.openContainer); + } - Block block = p_73078_2_.getBlock(p_73078_4_, p_73078_5_, p_73078_6_); - boolean isAir = block.isAir(p_73078_2_, p_73078_4_, p_73078_5_, p_73078_6_); - boolean useBlock = !p_73078_1_.isSneaking() || p_73078_1_.getHeldItem() == null; - if (!useBlock) useBlock = p_73078_1_.getHeldItem().getItem().doesSneakBypassUse(p_73078_2_, p_73078_4_, p_73078_5_, p_73078_6_, p_73078_1_); - boolean result = false; + thisPlayerMP.openContainer = CraftEventFactory.callInventoryOpenEvent(thisPlayerMP, thisPlayerMP.openContainer, false); + if (thisPlayerMP.openContainer == null) + { + thisPlayerMP.openContainer = thisPlayerMP.inventoryContainer; + return false; + } + } + } + // Cauldron end + } - if (useBlock) - { - if (event.useBlock != Event.Result.DENY) + if (p_73078_3_ != null && !denyResult && p_73078_3_.stackSize > 0) { - result = block.onBlockActivated(p_73078_2_, p_73078_4_, p_73078_5_, p_73078_6_, p_73078_1_, p_73078_7_, p_73078_8_, p_73078_9_, p_73078_10_); + int meta = p_73078_3_.getItemDamage(); + int size = p_73078_3_.stackSize; + denyResult = p_73078_3_.tryPlaceItemIntoWorld(p_73078_1_, p_73078_2_, p_73078_4_, p_73078_5_, p_73078_6_, p_73078_7_, p_73078_8_, p_73078_9_, p_73078_10_); + + // The item count should not decrement in Creative mode. + if (this.isCreative()) + { + p_73078_3_.setItemDamage(meta); + p_73078_3_.stackSize = size; + } + + if (p_73078_3_.stackSize <= 0) + { + ForgeEventFactory.onPlayerDestroyItem(this.thisPlayerMP, p_73078_3_); + } } - else + else if(p_73078_3_ != null && !denyResult) // Thermos call the Forge item destruction event... { - thisPlayerMP.playerNetServerHandler.sendPacket(new S23PacketBlockChange(p_73078_4_, p_73078_5_, p_73078_6_, theWorld)); - result = event.useItem != Event.Result.ALLOW; + if (p_73078_3_.stackSize <= 0) + { + ForgeEventFactory.onPlayerDestroyItem(this.thisPlayerMP, p_73078_3_); + } } - } - if (p_73078_3_ != null && !result && event.useItem != Event.Result.DENY) - { - int meta = p_73078_3_.getItemDamage(); - int size = p_73078_3_.stackSize; - result = p_73078_3_.tryPlaceItemIntoWorld(p_73078_1_, p_73078_2_, p_73078_4_, p_73078_5_, p_73078_6_, p_73078_7_, p_73078_8_, p_73078_9_, p_73078_10_); - if (isCreative()) + // If we have 'true' and no explicit deny *or* an explicit allow -- run the item part of the hook + if (p_73078_3_ != null && ((!denyResult && event.useItemInHand() != org.bukkit.event.Event.Result.DENY) || event.useItemInHand() == org.bukkit.event.Event.Result.ALLOW)) { - p_73078_3_.setItemDamage(meta); - p_73078_3_.stackSize = size; + this.tryUseItem(p_73078_1_, p_73078_2_, p_73078_3_); } - if (p_73078_3_.stackSize <= 0) ForgeEventFactory.onPlayerDestroyItem(thisPlayerMP, p_73078_3_); } - /* Re-enable if this causes bukkit incompatibility, or re-write client side to only send a single packet per right click. - if (par3ItemStack != null && ((!result && event.useItem != Event.Result.DENY) || event.useItem == Event.Result.ALLOW)) - { - this.tryUseItem(thisPlayerMP, par2World, par3ItemStack); - }*/ - return result; + return denyResult; + // CraftBukkit end } public void setWorld(WorldServer p_73080_1_)
412
0.928946
1
0.928946
game-dev
MEDIA
0.991506
game-dev
0.702863
1
0.702863
IAFEnvoy/IceAndFire-CE
18,892
common/src/main/java/com/iafenvoy/iceandfire/entity/PixieEntity.java
package com.iafenvoy.iceandfire.entity; import com.google.common.base.Predicate; import com.iafenvoy.iceandfire.entity.ai.*; import com.iafenvoy.iceandfire.item.block.entity.PixieHouseBlockEntity; import com.iafenvoy.iceandfire.network.payload.UpdatePixieHouseS2CPayload; import com.iafenvoy.iceandfire.registry.IafBlocks; import com.iafenvoy.iceandfire.registry.IafParticles; import com.iafenvoy.iceandfire.registry.IafSounds; import com.iafenvoy.iceandfire.registry.tag.IafItemTags; import com.iafenvoy.uranus.ServerHelper; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.entity.*; import net.minecraft.entity.ai.control.MoveControl; import net.minecraft.entity.ai.goal.LookAroundGoal; import net.minecraft.entity.ai.goal.LookAtEntityGoal; import net.minecraft.entity.ai.goal.SwimGoal; import net.minecraft.entity.attribute.DefaultAttributeContainer; import net.minecraft.entity.attribute.EntityAttributes; import net.minecraft.entity.damage.DamageSource; import net.minecraft.entity.data.DataTracker; import net.minecraft.entity.data.TrackedData; import net.minecraft.entity.data.TrackedDataHandlerRegistry; import net.minecraft.entity.effect.StatusEffect; import net.minecraft.entity.effect.StatusEffectInstance; import net.minecraft.entity.effect.StatusEffects; import net.minecraft.entity.mob.MobEntity; import net.minecraft.entity.passive.PassiveEntity; import net.minecraft.entity.passive.TameableEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.nbt.NbtCompound; import net.minecraft.registry.entry.RegistryEntry; import net.minecraft.server.world.ServerWorld; import net.minecraft.sound.SoundEvent; import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.random.Random; import net.minecraft.world.Heightmap; import net.minecraft.world.LocalDifficulty; import net.minecraft.world.ServerWorldAccess; import net.minecraft.world.World; @SuppressWarnings("ALL") public class PixieEntity extends TameableEntity { public static final float[][] PARTICLE_RGB = new float[][]{new float[]{1F, 0.752F, 0.792F}, new float[]{0.831F, 0.662F, 1F}, new float[]{0.513F, 0.843F, 1F}, new float[]{0.654F, 0.909F, 0.615F}, new float[]{0.996F, 0.788F, 0.407F}}; public static final int STEAL_COOLDOWN = 3000; private static final TrackedData<Integer> COLOR = DataTracker.registerData(PixieEntity.class, TrackedDataHandlerRegistry.INTEGER); private static final TrackedData<Integer> COMMAND = DataTracker.registerData(PixieEntity.class, TrackedDataHandlerRegistry.INTEGER); public final RegistryEntry<StatusEffect>[] positivePotions = new RegistryEntry[]{StatusEffects.STRENGTH, StatusEffects.JUMP_BOOST, StatusEffects.SPEED, StatusEffects.LUCK, StatusEffects.HASTE}; public final RegistryEntry<StatusEffect>[] negativePotions = new RegistryEntry[]{StatusEffects.WEAKNESS, StatusEffects.NAUSEA, StatusEffects.SLOWNESS, StatusEffects.UNLUCK, StatusEffects.MINING_FATIGUE}; public boolean slowSpeed = false; public int ticksUntilHouseAI; public int ticksHeldItemFor; public int stealCooldown = 0; private BlockPos housePos; private boolean isSitting; public PixieEntity(EntityType<? extends PixieEntity> type, World worldIn) { super(type, worldIn); this.moveControl = new AIMoveControl(this); this.experiencePoints = 3; this.setEquipmentDropChance(EquipmentSlot.MAINHAND, 0F); } public static BlockPos getPositionRelativetoGround(Entity entity, World world, double x, double z, Random rand) { BlockPos pos = BlockPos.ofFloored(x, entity.getBlockY(), z); for (int yDown = 0; yDown < 3; yDown++) { if (!world.isAir(pos.down(yDown))) { return pos.up(yDown); } } return pos; } public static BlockPos findAHouse(Entity entity, World world) { for (int xSearch = -10; xSearch < 10; xSearch++) { for (int ySearch = -10; ySearch < 10; ySearch++) { for (int zSearch = -10; zSearch < 10; zSearch++) { if (world.getBlockEntity(entity.getBlockPos().add(xSearch, ySearch, zSearch)) != null && world.getBlockEntity(entity.getBlockPos().add(xSearch, ySearch, zSearch)) instanceof PixieHouseBlockEntity house) { if (!house.hasPixie) { return entity.getBlockPos().add(xSearch, ySearch, zSearch); } } } } } return entity.getBlockPos(); } public static DefaultAttributeContainer.Builder bakeAttributes() { return MobEntity.createMobAttributes() //HEALTH .add(EntityAttributes.GENERIC_MAX_HEALTH, 10D) //SPEED .add(EntityAttributes.GENERIC_MOVEMENT_SPEED, 0.25D); } public boolean isPixieSitting() { if (this.getWorld().isClient) { boolean isSitting = (this.dataTracker.get(TAMEABLE_FLAGS) & 1) != 0; this.isSitting = isSitting; this.setSitting(isSitting); return isSitting; } return this.isSitting; } public void setPixieSitting(boolean sitting) { if (!this.getWorld().isClient) { this.isSitting = sitting; this.setInSittingPose(sitting); } byte b0 = this.dataTracker.get(TAMEABLE_FLAGS); if (sitting) { this.dataTracker.set(TAMEABLE_FLAGS, (byte) (b0 | 1)); } else { this.dataTracker.set(TAMEABLE_FLAGS, (byte) (b0 & -2)); } } @Override public boolean isSitting() { return this.isPixieSitting(); } @Override public int getXpToDrop() { return 3; } @Override public boolean isBreedingItem(ItemStack stack) { return stack.isOf(Items.SUGAR); } @Override public boolean damage(DamageSource source, float amount) { if (!this.getWorld().isClient && this.getRandom().nextInt(3) == 0 && !this.getStackInHand(Hand.MAIN_HAND).isEmpty()) { this.dropStack(this.getStackInHand(Hand.MAIN_HAND), 0); this.setStackInHand(Hand.MAIN_HAND, ItemStack.EMPTY); this.stealCooldown = STEAL_COOLDOWN; return true; } if (this.isOwnerClose() && ((source.getAttacker() != null && source == this.getWorld().getDamageSources().fallingBlock(source.getAttacker())) || source == this.getWorld().getDamageSources().inWall() || this.getOwner() != null && source.getAttacker() == this.getOwner())) { return false; } return super.damage(source, amount); } @Override public boolean isInvulnerableTo(DamageSource source) { boolean invulnerable = super.isInvulnerableTo(source); if (!invulnerable) { Entity owner = this.getOwner(); if (owner != null && source.getAttacker() == owner) { return true; } } return invulnerable; } @Override public void onDeath(DamageSource cause) { if (!this.getWorld().isClient && !this.getStackInHand(Hand.MAIN_HAND).isEmpty()) { this.dropStack(this.getStackInHand(Hand.MAIN_HAND), 0); this.setStackInHand(Hand.MAIN_HAND, ItemStack.EMPTY); } super.onDeath(cause); } @Override protected void initDataTracker(DataTracker.Builder builder) { super.initDataTracker(builder); builder.add(COLOR, 0); builder.add(COMMAND, 0); } @Override protected void pushAway(Entity entityIn) { if (this.getOwner() != entityIn) { entityIn.pushAwayFrom(this); } } @Override protected void fall(double y, boolean onGroundIn, BlockState state, BlockPos pos) { } @Override public ActionResult interactMob(PlayerEntity player, Hand hand) { if (this.isOwner(player)) { if (player.getStackInHand(hand).isIn(IafItemTags.HEAL_PIXIE) && this.getHealth() < this.getMaxHealth()) { this.heal(5); player.getStackInHand(hand).decrement(1); this.playSound(IafSounds.PIXIE_TAUNT.get(), 1F, 1F); return ActionResult.SUCCESS; } else { this.setCommand(this.getCommand() + 1); if (this.getCommand() > 1) this.setCommand(0); return ActionResult.SUCCESS; } } else if (player.getStackInHand(hand).getItem() == IafBlocks.JAR_EMPTY.get().asItem() && !this.isTamed()) { if (!player.isCreative()) player.getStackInHand(hand).decrement(1); Block jar = switch (this.getColor()) { case 0 -> IafBlocks.JAR_PIXIE_0.get(); case 1 -> IafBlocks.JAR_PIXIE_1.get(); case 2 -> IafBlocks.JAR_PIXIE_2.get(); case 3 -> IafBlocks.JAR_PIXIE_3.get(); case 4 -> IafBlocks.JAR_PIXIE_4.get(); default -> Blocks.AIR; }; ItemStack stack = new ItemStack(jar, 1); if (!this.getWorld().isClient) { if (!this.getStackInHand(Hand.MAIN_HAND).isEmpty()) { this.dropStack(this.getStackInHand(Hand.MAIN_HAND), 0.0F); this.stealCooldown = STEAL_COOLDOWN; } this.dropStack(stack, 0.0F); } this.remove(RemovalReason.DISCARDED); } return super.interactMob(player, hand); } @Override protected void initGoals() { this.goalSelector.add(0, new SwimGoal(this)); this.goalSelector.add(1, new PixieAIFollowOwnerGoal(this, 1.0D, 2.0F, 4.0F)); this.goalSelector.add(2, new PixieAIPickupItemGoal<>(this, false)); this.goalSelector.add(2, new PixieAIFleeGoal<>(this, PlayerEntity.class, 10, (Predicate<PlayerEntity>) entity -> true)); this.goalSelector.add(2, new PixieAIStealGoal(this)); this.goalSelector.add(3, new PixieAIMoveRandomGoal(this)); this.goalSelector.add(4, new PixieAIEnterHouseGoal(this)); this.goalSelector.add(6, new LookAtEntityGoal(this, PlayerEntity.class, 6.0F)); this.goalSelector.add(7, new LookAroundGoal(this)); } @Override public EntityData initialize(ServerWorldAccess worldIn, LocalDifficulty difficultyIn, SpawnReason reason, EntityData spawnDataIn) { spawnDataIn = super.initialize(worldIn, difficultyIn, reason, spawnDataIn); this.setColor(this.random.nextInt(5)); this.setStackInHand(Hand.MAIN_HAND, ItemStack.EMPTY); return spawnDataIn; } private boolean isBeyondHeight() { if (this.getY() > this.getWorld().getTopY()) return true; BlockPos height = this.getWorld().getTopPosition(Heightmap.Type.MOTION_BLOCKING_NO_LEAVES, this.getBlockPos()); int maxY = 20 + height.getY(); return this.getY() > maxY; } public int getCommand() { return this.dataTracker.get(COMMAND); } public void setCommand(int command) { this.dataTracker.set(COMMAND, command); this.setPixieSitting(command == 1); } @Override public void tickMovement() { super.tickMovement(); if (!this.getWorld().isClient) { // NOTE: This code was taken from HippogryphEntity basically same idea if (this.isPixieSitting() && this.getCommand() != 1) this.setPixieSitting(false); if (!this.isPixieSitting() && this.getCommand() == 1) this.setPixieSitting(true); if (this.isPixieSitting()) this.getNavigation().stop(); } if (this.stealCooldown > 0) this.stealCooldown--; if (!this.getMainHandStack().isEmpty() && !this.isTamed()) this.ticksHeldItemFor++; else this.ticksHeldItemFor = 0; if (!this.isPixieSitting() && !this.isBeyondHeight()) this.setVelocity(this.getVelocity().add(0, 0.08, 0)); if (this.getWorld().isClient) this.getWorld().addParticle(IafParticles.PIXIE_DUST.get(), this.getX() + (double) (this.random.nextFloat() * this.getWidth() * 2F) - (double) this.getWidth(), this.getY() + (double) (this.random.nextFloat() * this.getHeight()), this.getZ() + (double) (this.random.nextFloat() * this.getWidth() * 2F) - (double) this.getWidth(), PARTICLE_RGB[this.getColor()][0], PARTICLE_RGB[this.getColor()][1], PARTICLE_RGB[this.getColor()][2]); if (this.ticksUntilHouseAI > 0) this.ticksUntilHouseAI--; if (!this.getWorld().isClient) { if (this.housePos != null && this.squaredDistanceTo(Vec3d.ofCenter(this.housePos)) < 1.5F && this.getWorld().getBlockEntity(this.housePos) != null && this.getWorld().getBlockEntity(this.housePos) instanceof PixieHouseBlockEntity house) { if (house.hasPixie) this.housePos = null; else { house.hasPixie = true; house.pixieType = this.getColor(); house.pixieItems.set(0, this.getStackInHand(Hand.MAIN_HAND)); house.tamedPixie = this.isTamed(); house.pixieOwnerUUID = this.getOwnerUuid(); ServerHelper.sendToAll(new UpdatePixieHouseS2CPayload(this.housePos, true, this.getColor())); this.remove(RemovalReason.DISCARDED); } } } if (this.getOwner() != null && this.isOwnerClose() && this.age % 80 == 0) { this.getOwner().addStatusEffect(new StatusEffectInstance(this.positivePotions[this.getColor()], 100, 0, false, false)); } } public int getColor() { return MathHelper.clamp(this.getDataTracker().get(COLOR), 0, 4); } public void setColor(int color) { this.getDataTracker().set(COLOR, color); } @Override public void readCustomDataFromNbt(NbtCompound compound) { this.setColor(compound.getInt("Color")); this.stealCooldown = compound.getInt("StealCooldown"); this.ticksHeldItemFor = compound.getInt("HoldingTicks"); this.setPixieSitting(compound.getBoolean("PixieSitting")); this.setCommand(compound.getInt("Command")); super.readCustomDataFromNbt(compound); } @Override public void writeCustomDataToNbt(NbtCompound compound) { compound.putInt("Color", this.getColor()); compound.putInt("Command", this.getCommand()); compound.putInt("StealCooldown", this.stealCooldown); compound.putInt("HoldingTicks", this.ticksHeldItemFor); compound.putBoolean("PixieSitting", this.isPixieSitting()); super.writeCustomDataToNbt(compound); } @Override public PassiveEntity createChild(ServerWorld serverWorld, PassiveEntity ageable) { return null; } public void setHousePosition(BlockPos blockPos) { this.housePos = blockPos; } public BlockPos getHousePos() { return this.housePos; } public boolean isOwnerClose() { return this.isTamed() && this.getOwner() != null && this.squaredDistanceTo(this.getOwner()) < 100; } @Override protected SoundEvent getAmbientSound() { return IafSounds.PIXIE_IDLE.get(); } @Override protected SoundEvent getHurtSound(DamageSource damageSourceIn) { return IafSounds.PIXIE_HURT.get(); } @Override protected SoundEvent getDeathSound() { return IafSounds.PIXIE_DIE.get(); } @Override public boolean isTeammate(Entity entityIn) { if (this.isTamed()) { LivingEntity livingentity = this.getOwner(); if (entityIn == livingentity) return true; if (entityIn instanceof TameableEntity tameable) return tameable.isOwner(livingentity); if (livingentity != null) return livingentity.isTeammate(entityIn); } return super.isTeammate(entityIn); } class AIMoveControl extends MoveControl { public AIMoveControl(PixieEntity pixie) { super(pixie); } @Override public void tick() { float speedMod = 1; if (PixieEntity.this.slowSpeed) speedMod = 2F; if (this.state == State.MOVE_TO) { if (PixieEntity.this.horizontalCollision) { PixieEntity.this.setYaw(this.entity.getYaw() + 180.0F); speedMod = 0.1F; BlockPos target = PixieEntity.getPositionRelativetoGround(PixieEntity.this, PixieEntity.this.getWorld(), PixieEntity.this.getX() + PixieEntity.this.random.nextInt(15) - 7, PixieEntity.this.getZ() + PixieEntity.this.random.nextInt(15) - 7, PixieEntity.this.random); this.targetX = target.getX(); this.targetY = target.getY(); this.targetZ = target.getZ(); } double d0 = this.targetX - PixieEntity.this.getX(); double d1 = this.targetY - PixieEntity.this.getY(); double d2 = this.targetZ - PixieEntity.this.getZ(); double d3 = d0 * d0 + d1 * d1 + d2 * d2; d3 = Math.sqrt(d3); if (d3 < PixieEntity.this.getBoundingBox().getAverageSideLength()) { this.state = State.WAIT; PixieEntity.this.setVelocity(PixieEntity.this.getVelocity().multiply(0.5D, 0.5D, 0.5D)); } else { PixieEntity.this.setVelocity(PixieEntity.this.getVelocity().add(d0 / d3 * 0.05D * this.speed * speedMod, d1 / d3 * 0.05D * this.speed * speedMod, d2 / d3 * 0.05D * this.speed * speedMod)); if (PixieEntity.this.getTarget() == null) { PixieEntity.this.setYaw(-((float) MathHelper.atan2(PixieEntity.this.getVelocity().x, PixieEntity.this.getVelocity().z)) * (180F / (float) Math.PI)); PixieEntity.this.bodyYaw = PixieEntity.this.getYaw(); } else { double d4 = PixieEntity.this.getTarget().getX() - PixieEntity.this.getX(); double d5 = PixieEntity.this.getTarget().getZ() - PixieEntity.this.getZ(); PixieEntity.this.setYaw(-((float) MathHelper.atan2(d4, d5)) * (180F / (float) Math.PI)); PixieEntity.this.bodyYaw = PixieEntity.this.getYaw(); } } } } } }
412
0.942647
1
0.942647
game-dev
MEDIA
0.996859
game-dev
0.98238
1
0.98238
Sigma-Skidder-Team/SigmaRebase
4,672
src/main/java/net/minecraft/item/EnchantedBookItem.java
package net.minecraft.item; import java.util.List; import javax.annotation.Nullable; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.EnchantmentData; import net.minecraft.nbt.CompoundNBT; import net.minecraft.nbt.ListNBT; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraft.util.registry.Registry; import net.minecraft.util.text.ITextComponent; import net.minecraft.world.World; public class EnchantedBookItem extends Item { public EnchantedBookItem(Item.Properties builder) { super(builder); } /** * Returns true if this item has an enchantment glint. By default, this returns * <code>stack.isItemEnchanted()</code>, but other items can override it (for instance, written books always return * true). * * Note that if you override this method, you generally want to also call the super version (on {@link Item}) to get * the glint for enchanted items. Of course, that is unnecessary if the overwritten version always returns true. */ public boolean hasEffect(ItemStack stack) { return true; } /** * Checks isDamagable and if it cannot be stacked */ public boolean isEnchantable(ItemStack stack) { return false; } public static ListNBT getEnchantments(ItemStack stack) { CompoundNBT compoundnbt = stack.getTag(); return compoundnbt != null ? compoundnbt.getList("StoredEnchantments", 10) : new ListNBT(); } /** * allows items to add custom lines of information to the mouseover description */ public void addInformation(ItemStack stack, @Nullable World worldIn, List<ITextComponent> tooltip, ITooltipFlag flagIn) { super.addInformation(stack, worldIn, tooltip, flagIn); ItemStack.addEnchantmentTooltips(tooltip, getEnchantments(stack)); } /** * Adds an stored enchantment to an enchanted book ItemStack */ public static void addEnchantment(ItemStack p_92115_0_, EnchantmentData stack) { ListNBT listnbt = getEnchantments(p_92115_0_); boolean flag = true; ResourceLocation resourcelocation = Registry.ENCHANTMENT.getKey(stack.enchantment); for (int i = 0; i < listnbt.size(); ++i) { CompoundNBT compoundnbt = listnbt.getCompound(i); ResourceLocation resourcelocation1 = ResourceLocation.tryCreate(compoundnbt.getString("id")); if (resourcelocation1 != null && resourcelocation1.equals(resourcelocation)) { if (compoundnbt.getInt("lvl") < stack.enchantmentLevel) { compoundnbt.putShort("lvl", (short)stack.enchantmentLevel); } flag = false; break; } } if (flag) { CompoundNBT compoundnbt1 = new CompoundNBT(); compoundnbt1.putString("id", String.valueOf((Object)resourcelocation)); compoundnbt1.putShort("lvl", (short)stack.enchantmentLevel); listnbt.add(compoundnbt1); } p_92115_0_.getOrCreateTag().put("StoredEnchantments", listnbt); } /** * Returns the ItemStack of an enchanted version of this item. */ public static ItemStack getEnchantedItemStack(EnchantmentData enchantData) { ItemStack itemstack = new ItemStack(Items.ENCHANTED_BOOK); addEnchantment(itemstack, enchantData); return itemstack; } /** * returns a list of items with the same ID, but different meta (eg: dye returns 16 items) */ public void fillItemGroup(ItemGroup group, NonNullList<ItemStack> items) { if (group == ItemGroup.SEARCH) { for (Enchantment enchantment : Registry.ENCHANTMENT) { if (enchantment.type != null) { for (int i = enchantment.getMinLevel(); i <= enchantment.getMaxLevel(); ++i) { items.add(getEnchantedItemStack(new EnchantmentData(enchantment, i))); } } } } else if (group.getRelevantEnchantmentTypes().length != 0) { for (Enchantment enchantment1 : Registry.ENCHANTMENT) { if (group.hasRelevantEnchantmentType(enchantment1.type)) { items.add(getEnchantedItemStack(new EnchantmentData(enchantment1, enchantment1.getMaxLevel()))); } } } } }
412
0.870504
1
0.870504
game-dev
MEDIA
0.995519
game-dev
0.882388
1
0.882388
mastercomfig/tf2-patches-old
6,882
src/utils/vbsp/boundbox.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "vbsp.h" #include "BoundBox.h" //#include "hammer_mathlib.h" //#include "MapDefs.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" float V_rint(float f) { if (f > 0.0f) { return (float) floor(f + 0.5f); } else if (f < 0.0f) { return (float) ceil(f - 0.5f); } else return 0.0f; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- BoundBox::BoundBox(void) { ResetBounds(); } BoundBox::BoundBox(const Vector &mins, const Vector &maxs) { bmins = mins; bmaxs = maxs; } //----------------------------------------------------------------------------- // Purpose: Sets the box to an uninitialized state, so that calls to UpdateBounds // will properly set the mins and maxs. //----------------------------------------------------------------------------- void BoundBox::ResetBounds(void) { bmins[0] = bmins[1] = bmins[2] = COORD_NOTINIT; bmaxs[0] = bmaxs[1] = bmaxs[2] = -COORD_NOTINIT; } //----------------------------------------------------------------------------- // Purpose: // Input : pt - //----------------------------------------------------------------------------- void BoundBox::UpdateBounds(const Vector& pt) { if(pt[0] < bmins[0]) bmins[0] = pt[0]; if(pt[1] < bmins[1]) bmins[1] = pt[1]; if(pt[2] < bmins[2]) bmins[2] = pt[2]; if(pt[0] > bmaxs[0]) bmaxs[0] = pt[0]; if(pt[1] > bmaxs[1]) bmaxs[1] = pt[1]; if(pt[2] > bmaxs[2]) bmaxs[2] = pt[2]; } //----------------------------------------------------------------------------- // Purpose: // Input : bmins - // bmaxs - //----------------------------------------------------------------------------- void BoundBox::UpdateBounds(const Vector& mins, const Vector& maxs) { if(mins[0] < bmins[0]) bmins[0] = mins[0]; if(mins[1] < bmins[1]) bmins[1] = mins[1]; if(mins[2] < bmins[2]) bmins[2] = mins[2]; if(maxs[0] > bmaxs[0]) bmaxs[0] = maxs[0]; if(maxs[1] > bmaxs[1]) bmaxs[1] = maxs[1]; if(maxs[2] > bmaxs[2]) bmaxs[2] = maxs[2]; } //----------------------------------------------------------------------------- // Purpose: // Input : pBox - //----------------------------------------------------------------------------- void BoundBox::UpdateBounds(const BoundBox *pBox) { UpdateBounds(pBox->bmins, pBox->bmaxs); } //----------------------------------------------------------------------------- // Purpose: // Input : ptdest - //----------------------------------------------------------------------------- void BoundBox::GetBoundsCenter(Vector& ptdest) { ptdest = (bmins + bmaxs)/2.0f; } //----------------------------------------------------------------------------- // Purpose: // Input : pt - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool BoundBox::ContainsPoint(const Vector& pt) const { for (int i = 0; i < 3; i++) { if (pt[i] < bmins[i] || pt[i] > bmaxs[i]) { return(false); } } return(true); } //----------------------------------------------------------------------------- // Purpose: // Input : pfMins - // pfMaxs - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool BoundBox::IsIntersectingBox(const Vector& pfMins, const Vector& pfMaxs) const { if ((bmins[0] >= pfMaxs[0]) || (bmaxs[0] <= pfMins[0])) { return(false); } if ((bmins[1] >= pfMaxs[1]) || (bmaxs[1] <= pfMins[1])) { return(false); } if ((bmins[2] >= pfMaxs[2]) || (bmaxs[2] <= pfMins[2])) { return(false); } return(true); } //----------------------------------------------------------------------------- // Purpose: // Input : pfMins - // pfMaxs - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool BoundBox::IsInsideBox(const Vector& pfMins, const Vector& pfMaxs) const { if ((bmins[0] < pfMins[0]) || (bmaxs[0] > pfMaxs[0])) { return(false); } if ((bmins[1] < pfMins[1]) || (bmaxs[1] > pfMaxs[1])) { return(false); } if ((bmins[2] < pfMins[2]) || (bmaxs[2] > pfMaxs[2])) { return(false); } return(true); } //----------------------------------------------------------------------------- // Purpose: Returns whether this bounding box is valid, ie maxs >= mins. //----------------------------------------------------------------------------- bool BoundBox::IsValidBox(void) const { for (int i = 0; i < 3; i++) { if (bmins[i] > bmaxs[i]) { return(false); } } return(true); } //----------------------------------------------------------------------------- // Purpose: // Input : size - //----------------------------------------------------------------------------- void BoundBox::GetBoundsSize(Vector& size) { size[0] = bmaxs[0] - bmins[0]; size[1] = bmaxs[1] - bmins[1]; size[2] = bmaxs[2] - bmins[2]; } //----------------------------------------------------------------------------- // Purpose: // Input : iValue - // iGridSize - // Output : //----------------------------------------------------------------------------- static int Snap(/*int*/ float iValue, int iGridSize) { return (int)(V_rint(iValue/iGridSize) * iGridSize); } //----------------------------------------------------------------------------- // Purpose: // Input : iGridSize - //----------------------------------------------------------------------------- void BoundBox::SnapToGrid(int iGridSize) { // does not alter the size of the box .. snaps its minimal coordinates // to the grid size specified in iGridSize Vector size; GetBoundsSize(size); for(int i = 0; i < 3; i++) { bmins[i] = (float)Snap(/* YWB (int)*/bmins[i], iGridSize); bmaxs[i] = bmins[i] + size[i]; } } //----------------------------------------------------------------------------- // Purpose: // Input : axis - //----------------------------------------------------------------------------- void BoundBox::Rotate90(int axis) { int e1 = AXIS_X, e2 = AXIS_Y; // get bounds center first Vector center; GetBoundsCenter(center); switch(axis) { case AXIS_Z: e1 = AXIS_X; e2 = AXIS_Y; break; case AXIS_X: e1 = AXIS_Y; e2 = AXIS_Z; break; case AXIS_Y: e1 = AXIS_X; e2 = AXIS_Z; break; } float tmp1, tmp2; tmp1 = bmins[e1] - center[e1] + center[e2]; tmp2 = bmaxs[e1] - center[e1] + center[e2]; bmins[e1] = bmins[e2] - center[e2] + center[e1]; bmaxs[e1] = bmaxs[e2] - center[e2] + center[e1]; bmins[e2] = tmp1; bmaxs[e2] = tmp2; }
412
0.760903
1
0.760903
game-dev
MEDIA
0.450223
game-dev
0.965228
1
0.965228
Monkestation/Monkestation2.0
13,867
code/modules/mob/living/basic/ruin_defender/mimic/mimic.dm
#define CANT_INSERT_FULL -1 /// Mimics can't be made out of these objects GLOBAL_LIST_INIT(animatable_blacklist, typecacheof(list( /obj/structure/table, /obj/structure/cable, /obj/structure/window, /obj/structure/blob, ))) /mob/living/basic/mimic response_help_continuous = "touches" response_help_simple = "touch" response_disarm_simple = "push" speed = 6 maxHealth = 250 health = 250 gender = NEUTER mob_biotypes = NONE pass_flags = PASSFLAPS melee_damage_lower = 8 melee_damage_upper = 12 attack_sound = 'sound/items/weapons/punch1.ogg' speak_emote = list("creaks") unsuitable_cold_damage = 0 unsuitable_heat_damage = 0 unsuitable_atmos_damage = 0 faction = list(FACTION_MIMIC) basic_mob_flags = DEL_ON_DEATH istate = ISTATE_HARM|ISTATE_BLOCKING /// can we stun people on hit var/knockdown_people = FALSE /mob/living/basic/mimic/melee_attack(mob/living/carbon/target, list/modifiers, ignore_cooldown) . = ..() if(!. || !knockdown_people || !prob(15) || !istype(target)) return target.Paralyze(4 SECONDS) target.visible_message(span_danger("\The [src] knocks down \the [target]!"), \ span_userdanger("\The [src] knocks you down!")) // **************************** // CRATE MIMIC // **************************** // Aggro when you try to open them. Will also pickup loot when spawns and drop it when dies. /mob/living/basic/mimic/crate name = "crate" desc = "A rectangular steel crate." icon = 'icons/obj/storage/crates.dmi' icon_state = "crate" icon_living = "crate" attack_verb_continuous = "bites" attack_verb_simple = "bite" speak_emote = list("clatters") layer = BELOW_MOB_LAYER ai_controller = /datum/ai_controller/basic_controller/mimic_crate /// are we open var/opened = FALSE /// max mob size var/max_mob_size = MOB_SIZE_HUMAN /// can we be opened or closed, if false we can var/locked = FALSE /// action to lock us var/datum/action/innate/mimic_lock/lock ///A cap for items in the mimic. Prevents the mimic from eating enough stuff to cause lag when opened. var/storage_capacity = 50 ///A cap for mobs. Mobs count towards the item cap. Same purpose as above. var/mob_storage_capacity = 10 // Pickup loot /mob/living/basic/mimic/crate/Initialize(mapload) . = ..() lock = new lock.Grant(src) ADD_TRAIT(src, TRAIT_AI_PAUSED, INNATE_TRAIT) ai_controller?.set_ai_status(AI_STATUS_OFF) //start inert, let gullible people pull us into cargo or something and then go nuts when opened if(mapload) //eat shit for(var/obj/item/item in loc) item.forceMove(src) /mob/living/basic/mimic/crate/Destroy() lock = null return ..() /mob/living/basic/mimic/crate/attack_hand(mob/living/carbon/human/user, list/modifiers) if(user.istate & ISTATE_HARM) return ..() if(trigger()) to_chat(user, span_danger("As you try to open [src] it [length(contents) ? "stiffens up and " : ""]nearly clamps down on your fingers!")) return TRUE toggle_open(user) return TRUE /mob/living/basic/mimic/crate/melee_attack(mob/living/carbon/target, list/modifiers, ignore_cooldown) . = ..() toggle_open() // show our cool lid at the dumbass humans /mob/living/basic/mimic/crate/proc/trigger() if(isnull(ai_controller) || client) return FALSE if(ai_controller.ai_status != AI_STATUS_OFF) return FALSE visible_message(span_danger("[src] starts to move!")) REMOVE_TRAIT(src, TRAIT_AI_PAUSED, INNATE_TRAIT) ai_controller.set_ai_status(AI_STATUS_ON) if(length(contents)) locked = TRUE //if this was a crate with loot then we dont want people to just leftclick it to open it then bait it somewhere and steal its loot return TRUE /mob/living/basic/mimic/crate/adjust_health(amount, updating_health = TRUE, forced = FALSE) if(amount > 0) trigger() return ..() /mob/living/basic/mimic/crate/death() var/obj/structure/closet/crate/lootbox = new(get_turf(src)) // Put loot in crate for(var/obj/loot in src) loot.forceMove(lootbox) return ..() /mob/living/basic/mimic/crate/proc/pre_attack(atom/target, list/modifiers, ignore_cooldown) if(target == src) toggle_open() return FALSE return /mob/living/basic/mimic/crate/CanAllowThrough(atom/movable/mover, border_dir) . = ..() if(istype(mover, /obj/structure/closet)) return FALSE /** * Used to open and close the mimic * * Will insert tile contents into the mimic when closing * Will dump mimic contents into the time when opening * Does nothing if the mimic locked itself */ /mob/living/basic/mimic/crate/proc/toggle_open(mob/user) if(locked) if(user) balloon_alert(user, "too stiff!") return if(!opened) ADD_TRAIT(src, TRAIT_UNDENSE, MIMIC_TRAIT) opened = TRUE icon_state = "crateopen" playsound(src, 'sound/machines/crate_open.ogg', 50, TRUE) for(var/atom/movable/movable as anything in src) movable.forceMove(loc) else REMOVE_TRAIT(src, TRAIT_UNDENSE, MIMIC_TRAIT) opened = FALSE icon_state = "crate" playsound(src, 'sound/machines/crate_close.ogg', 50, TRUE) for(var/atom/movable/movable as anything in get_turf(src)) if(movable != src && insert(movable) == CANT_INSERT_FULL) playsound(src, 'sound/items/trayhit2.ogg', 50, TRUE) break /** * Called by toggle_open to put items inside the mimic when it's being closed * * Will return CANT_INSERT_FULL (-1) if the insertion fails due to the storage capacity of the mimic having been reached * Will return FALSE if insertion fails * Will return TRUE if insertion succeeds * Arguments: * * AM - item to be inserted */ /mob/living/basic/mimic/crate/proc/insert(atom/movable/movable) if(contents.len >= storage_capacity) return CANT_INSERT_FULL if(insertion_allowed(movable)) movable.forceMove(src) return TRUE return FALSE /mob/living/basic/mimic/crate/proc/insertion_allowed(atom/movable/movable) if(movable.anchored) return FALSE if(ismob(movable)) if(!isliving(movable)) //Don't let ghosts and such get trapped in the beast. return FALSE var/mob/living/living = movable if(living.anchored || living.buckled || living.incorporeal_move || living.has_buckled_mobs()) return FALSE if(living.mob_size > MOB_SIZE_TINY) // Tiny mobs are treated as items. if(living.density || living.mob_size > max_mob_size) return FALSE var/mobs_stored = 0 for(var/mob/living/living_mob in contents) mobs_stored++ if(mobs_stored >= mob_storage_capacity) return FALSE living.stop_pulling() else if(istype(movable, /obj/structure/closet)) return FALSE else if(isobj(movable)) if(movable.has_buckled_mobs()) return FALSE else if(isitem(movable) && !HAS_TRAIT(movable, TRAIT_NODROP)) return TRUE else return FALSE return TRUE /mob/living/basic/mimic/crate/xenobio health = 210 maxHealth = 210 attack_verb_continuous = "bites" attack_verb_simple = "bite" speak_emote = list("clatters") gold_core_spawnable = HOSTILE_SPAWN /datum/action/innate/mimic_lock name = "Lock/Unlock" desc = "Toggle preventing yourself from being opened or closed." button_icon = 'icons/hud/radial.dmi' button_icon_state = "radial_lock" background_icon_state = "bg_default" overlay_icon_state = "bg_default_border" /datum/action/innate/mimic/lock/Activate() var/mob/living/basic/mimic/crate/mimic = owner mimic.locked = !mimic.locked if(!mimic.locked) to_chat(mimic, span_warning("You loosen up, allowing yourself to be opened and closed.")) else to_chat(mimic, span_warning("You stiffen up, preventing anyone from opening or closing you.")) // **************************** // COPYING (actually imitates target object) MIMIC // **************************** /mob/living/basic/mimic/copy health = 100 maxHealth = 100 mob_biotypes = MOB_MINERAL ai_controller = /datum/ai_controller/basic_controller/mimic_copy /// our creator var/datum/weakref/creator_ref /// googly eyes overlay var/static/mutable_appearance/googly_eyes = mutable_appearance('icons/mob/simple/mob.dmi', "googly_eyes") /// do we overlay googly eyes over whatever we copy var/overlay_googly_eyes = TRUE /// do we take damage when we are not sentient and have no target var/idledamage = TRUE /// copied object var/atom/movable/copied /mob/living/basic/mimic/copy/Initialize(mapload, obj/copy, mob/living/creator, destroy_original = FALSE, no_googlies = FALSE) . = ..() ADD_TRAIT(src, TRAIT_PERMANENTLY_MORTAL, INNATE_TRAIT) // They won't remember their original contents upon ressurection and would just be floating eyes if (no_googlies) overlay_googly_eyes = FALSE CopyObject(copy, creator, destroy_original) /mob/living/basic/mimic/copy/Destroy() creator_ref = null copied = null return ..() /mob/living/basic/mimic/copy/Life(seconds_per_tick = SSMOBS_DT, times_fired) . = ..() if(idledamage && !ckey && !ai_controller?.blackboard[BB_BASIC_MOB_CURRENT_TARGET]) //Objects eventually revert to normal if no one is around to terrorize adjustBruteLoss(0.5 * seconds_per_tick) for(var/mob/living/victim in contents) //a fix for animated statues from the flesh to stone spell death() return /mob/living/basic/mimic/copy/death() for(var/atom/movable/movable as anything in src) movable.forceMove(get_turf(src)) return ..() /mob/living/basic/mimic/copy/wabbajack(what_to_randomize, change_flags = WABBAJACK) visible_message(span_warning("[src] resists polymorphing into a new creature!")) /mob/living/basic/mimic/copy/animate_atom_living(mob/living/owner) change_owner(owner) /mob/living/basic/mimic/copy/Exited(atom/movable/gone, direction) // if our object gets deleted it calls Exited . = ..() if(QDELETED(src) || gone != copied) return death() /mob/living/basic/mimic/copy/proc/change_owner(mob/owner) var/mob/creator_resolved = creator_ref?.resolve() if(!creator_resolved) creator_ref = null if(isnull(owner) || creator_resolved == owner) return unfriend(creator_resolved) befriend(owner) creator_ref = WEAKREF(owner) /// Check whether this object can be copied. If destroy_original is true, this proc is ignored. /mob/living/basic/mimic/copy/proc/check_object(obj/target) return ((isitem(target) || isstructure(target)) && !is_type_in_typecache(target, GLOB.animatable_blacklist)) /mob/living/basic/mimic/copy/proc/CopyObject(obj/original, mob/living/user, destroy_original = FALSE) if(!destroy_original && !check_object(original)) return FALSE if(!destroy_original) original.forceMove(src) copied = original CopyObjectVisuals(original) if (overlay_googly_eyes) add_overlay(googly_eyes) if(isstructure(original) || ismachinery(original)) health = (anchored * 50) + 50 if(original.density && original.anchored) knockdown_people = TRUE melee_damage_lower *= 2 melee_damage_upper *= 2 else if(isitem(original)) var/obj/item/I = original health = 15 * I.w_class melee_damage_lower = 2 + I.force melee_damage_upper = 2 + I.force maxHealth = health if(user) change_owner(user) if(destroy_original) qdel(original) return TRUE /// Copies the object visually including name and desc /mob/living/basic/mimic/copy/proc/CopyObjectVisuals(obj/original) name = original.name desc = original.desc icon = original.icon icon_state = original.icon_state icon_living = icon_state copy_overlays(original, cut_old = TRUE) /mob/living/basic/mimic/copy/machine ai_controller = /datum/ai_controller/basic_controller/mimic_copy/machine faction = list(FACTION_MIMIC, FACTION_SILICON) /mob/living/basic/mimic/copy/ranged icon = 'icons/turf/floors.dmi' icon_state = "invisible" ai_controller = /datum/ai_controller/basic_controller/mimic_copy/gun /mob/living/basic/mimic/copy/ranged/Destroy() vis_contents.Cut() return ..() /mob/living/basic/mimic/copy/ranged/RangedAttack(atom/atom_target, modifiers) INVOKE_ASYNC(src, PROC_REF(fire_gun), atom_target, modifiers) /mob/living/basic/mimic/copy/ranged/proc/fire_gun(atom/target, modifiers) // i cant find any better way to do this var/obj/item/gun/gun = locate() in contents if(!gun.can_shoot()) if(istype(gun, /obj/item/gun/ballistic)) var/obj/item/gun/ballistic/ballistic = gun if(!ballistic.chambered || ballistic.bolt_locked) ballistic.rack() //we racked so both checked variables should be something else now // do we have nothing chambered/chambered is spent AND we have no mag or our mag is empty if(!ballistic.chambered?.loaded_projectile && magazine_useless(gun)) // ran out of ammo ai_controller?.set_blackboard_key(BB_GUNMIMIC_GUN_EMPTY, TRUE) //BANZAIIIIIIII ai_controller?.CancelActions() else //if we cant fire we probably like ran out of energy or magic charges or whatever the hell idk ai_controller?.set_blackboard_key(BB_GUNMIMIC_GUN_EMPTY, TRUE) ai_controller?.CancelActions() // Stop our firing behavior so we can plan melee else ai_controller?.set_blackboard_key(BB_GUNMIMIC_GUN_EMPTY, FALSE) gun.fire_gun(target, user = src, flag = FALSE, params = modifiers) //still make like a cool click click sound if trying to fire empty /mob/living/basic/mimic/copy/ranged/proc/magazine_useless(obj/item/gun/ballistic/ballistic) if(isnull(ballistic.magazine) || !length(ballistic.magazine.stored_ammo)) return TRUE // is there ATLEAST one unspent round (for the sake of revolvers or a magazine somehow having spent rounds in it) for(var/obj/item/ammo_casing/thing as anything in ballistic.magazine.stored_ammo) if(ispath(thing)) return FALSE // unspent if(!isnull(thing.loaded_projectile)) return FALSE //unspent return TRUE /mob/living/basic/mimic/copy/ranged/CopyObject(obj/item/gun/original, mob/living/creator, destroy_original = 0) if(..()) obj_damage = 0 melee_damage_upper = original.force melee_damage_lower = original.force - max(0, (original.force / 2)) /mob/living/basic/mimic/copy/ranged/CopyObjectVisuals(obj/original) name = original.name desc = original.desc vis_contents += original /mob/living/basic/mimic/copy/ranged/can_use_guns(obj/item/gun) return TRUE #undef CANT_INSERT_FULL
412
0.776165
1
0.776165
game-dev
MEDIA
0.971664
game-dev
0.939845
1
0.939845
octonion/basketball
1,576
demo/feature_selection.R
sink("feature_selection.txt") library(MASS) library(RPostgreSQL) drv <- dbDriver("PostgreSQL") con <- dbConnect(drv,host="localhost",port="5432",dbname="basketball") query <- dbSendQuery(con, " select split_part(n.height,'-',1)::integer*12+split_part(n.height,'-',2)::integer as height, --d.pick as pick, --sqrt(d.pick) as s_pick, lower(n.position) as position, n.games, n.field_goals::float/nullif(n.field_goal_attempts,0) as fgp, --n.three_pointers::float/nullif(n.three_pointer_attempts,0) as tpp, n.free_throws::float/nullif(n.free_throw_attempts,0) as ftp, n.rebounds_per_game, n.assists_per_game, --n.blocks_per_game, n.steals_per_game, n.points_per_game, n.rebounds, n.assists, n.blocks, n.steals, n.points, sum(b.minutes_played) as minutes_played from ncaa.statistics n join alias.players p on (p.ncaa_id)=(n.player_id) join bbref.draft_picks d on (d.player_id,d.year)=(p.bbref_id,n.year) join bbref.basic_statistics b on (b.player_id,b.year)=(d.player_id,d.year+1) where not(b.team_id='TOT') and not(n.three_pointer_attempts=0) group by height, --d.pick, --s_pick, position, n.games, fgp, --tpp, ftp, n.rebounds_per_game, n.assists_per_game, --n.blocks_per_game, n.steals_per_game, n.points_per_game, n.rebounds, n.assists, n.blocks, n.steals, n.points --order by minutes_played desc; "); players <- fetch(query,n=-1) dim(players) players$position <- as.factor(players$position) model <- minutes_played ~ . fit <- lm(model,data=players) out <- stepAIC(fit,direction="both",k=2) out$anova coef(out) AIC(out) deviance(out) summary(out) out quit("no")
412
0.590348
1
0.590348
game-dev
MEDIA
0.304337
game-dev
0.742819
1
0.742819
MinecraftForge/MCPConfig
1,140
versions/pre/1.16/1.16-pre1/patches/server/net/minecraft/loot/LootTypesManager.java.patch
--- a/net/minecraft/loot/LootTypesManager.java +++ b/net/minecraft/loot/LootTypesManager.java @@ -83,13 +83,13 @@ public JsonElement serialize(E p_serialize_1_, Type p_serialize_2_, JsonSerializationContext p_serialize_3_) { T t = this.field_237401_d_.apply(p_serialize_1_); if (this.field_237402_e_ != null && this.field_237402_e_.getFirst() == t) { - return this.field_237402_e_.getSecond().func_237397_a_(p_serialize_1_, p_serialize_3_); + return ((ISerializer)this.field_237402_e_.getSecond()).func_237397_a_(p_serialize_1_, p_serialize_3_); } else if (t == null) { throw new JsonSyntaxException("Unknown type: " + p_serialize_1_); } else { JsonObject jsonobject = new JsonObject(); jsonobject.addProperty(this.field_237400_c_, this.field_237398_a_.func_177774_c(t).toString()); - t.func_237408_a_().func_230424_a_(jsonobject, p_serialize_1_, p_serialize_3_); + ((LootType)t).func_237408_a_().func_230424_a_(jsonobject, p_serialize_1_, p_serialize_3_); return jsonobject; } }
412
0.592137
1
0.592137
game-dev
MEDIA
0.529337
game-dev,networking
0.659829
1
0.659829
memberRE/AsyncDriver
16,288
nuplan/planning/simulation/planner/abstract_idm_planner.py
import logging from abc import ABC from typing import Dict, List, Optional, Tuple, Type import numpy as np from shapely.geometry import LineString, Point, Polygon from shapely.geometry.base import CAP_STYLE from shapely.ops import unary_union from nuplan.common.actor_state.agent import Agent from nuplan.common.actor_state.ego_state import EgoState from nuplan.common.actor_state.scene_object import SceneObject from nuplan.common.actor_state.state_representation import StateSE2, StateVector2D, TimePoint from nuplan.common.actor_state.vehicle_parameters import VehicleParameters from nuplan.common.geometry.transform import transform from nuplan.common.maps.abstract_map import AbstractMap from nuplan.common.maps.abstract_map_objects import RoadBlockGraphEdgeMapObject from nuplan.common.maps.maps_datatypes import SemanticMapLayer, TrafficLightStatusData, TrafficLightStatusType from nuplan.planning.metrics.utils.expert_comparisons import principal_value from nuplan.planning.simulation.observation.idm.idm_policy import IDMPolicy from nuplan.planning.simulation.observation.idm.idm_states import IDMAgentState, IDMLeadAgentState from nuplan.planning.simulation.observation.idm.utils import path_to_linestring from nuplan.planning.simulation.observation.observation_type import DetectionsTracks, Observation from nuplan.planning.simulation.occupancy_map.abstract_occupancy_map import OccupancyMap from nuplan.planning.simulation.occupancy_map.strtree_occupancy_map import STRTreeOccupancyMapFactory from nuplan.planning.simulation.path.path import AbstractPath from nuplan.planning.simulation.path.utils import trim_path from nuplan.planning.simulation.planner.abstract_planner import AbstractPlanner from nuplan.planning.simulation.trajectory.interpolated_trajectory import InterpolatedTrajectory UniqueObjects = Dict[str, SceneObject] logger = logging.getLogger(__name__) class AbstractIDMPlanner(AbstractPlanner, ABC): """ An interface for IDM based planners. Inherit from this class to use IDM policy to control the longitudinal behaviour of the ego. """ def __init__( self, target_velocity: float, min_gap_to_lead_agent: float, headway_time: float, accel_max: float, decel_max: float, planned_trajectory_samples: int, planned_trajectory_sample_interval: float, occupancy_map_radius: float, ): """ Constructor for IDMPlanner :param target_velocity: [m/s] Desired velocity in free traffic. :param min_gap_to_lead_agent: [m] Minimum relative distance to lead vehicle. :param headway_time: [s] Desired time headway. The minimum possible time to the vehicle in front. :param accel_max: [m/s^2] maximum acceleration. :param decel_max: [m/s^2] maximum deceleration (positive value). :param planned_trajectory_samples: number of elements to sample for the planned trajectory. :param planned_trajectory_sample_interval: [s] time interval of sequence to sample from. :param occupancy_map_radius: [m] The range around the ego to add objects to be considered. """ self._policy = IDMPolicy(target_velocity, min_gap_to_lead_agent, headway_time, accel_max, decel_max) self._planned_trajectory_samples = planned_trajectory_samples self._planned_trajectory_sample_interval = planned_trajectory_sample_interval self._planned_horizon = planned_trajectory_samples * planned_trajectory_sample_interval self._occupancy_map_radius = occupancy_map_radius self._max_path_length = self._policy.target_velocity * self._planned_horizon self._ego_token = "ego_token" self._red_light_token = "red_light" # To be lazy loaded self._route_roadblocks: List[RoadBlockGraphEdgeMapObject] = [] self._candidate_lane_edge_ids: Optional[List[str]] = None self._map_api: Optional[AbstractMap] = None # To be intialized by inherited classes self._ego_path: Optional[AbstractPath] = None self._ego_path_linestring: Optional[LineString] = None def name(self) -> str: """Inherited, see superclass.""" return self.__class__.__name__ def observation_type(self) -> Type[Observation]: """Inherited, see superclass.""" return DetectionsTracks # type: ignore def _initialize_route_plan(self, route_roadblock_ids: List[str]) -> None: """ Initializes the route plan with roadblocks. :param route_roadblock_ids: A list of roadblock ids that make up the ego's route """ assert self._map_api, "_map_api has not yet been initialized. Please call the initialize() function first!" self._route_roadblocks = [] for id_ in route_roadblock_ids: block = self._map_api.get_map_object(id_, SemanticMapLayer.ROADBLOCK) block = block or self._map_api.get_map_object(id_, SemanticMapLayer.ROADBLOCK_CONNECTOR) self._route_roadblocks.append(block) self._candidate_lane_edge_ids = [ edge.id for block in self._route_roadblocks if block for edge in block.interior_edges ] assert ( self._route_roadblocks ), "Cannot create route plan. No roadblocks were extracted from the given route_roadblock_ids!" def _get_expanded_ego_path(self, ego_state: EgoState, ego_idm_state: IDMAgentState) -> Polygon: """ Returns the ego's expanded path as a Polygon. :return: A polygon representing the ego's path. """ assert self._ego_path, "_ego_path has not yet been initialized. Please call the initialize() function first!" ego_footprint = ego_state.car_footprint path_to_go = trim_path( self._ego_path, max(self._ego_path.get_start_progress(), min(ego_idm_state.progress, self._ego_path.get_end_progress())), max( self._ego_path.get_start_progress(), min( ego_idm_state.progress + abs(self._policy.target_velocity) * self._planned_horizon, self._ego_path.get_end_progress(), ), ), ) expanded_path = path_to_linestring(path_to_go).buffer((ego_footprint.width / 2), cap_style=CAP_STYLE.square) return unary_union([expanded_path, ego_state.car_footprint.geometry]) @staticmethod def _get_leading_idm_agent(ego_state: EgoState, agent: SceneObject, relative_distance: float) -> IDMLeadAgentState: """ Returns a lead IDM agent state that represents another static and dynamic agent. :param agent: A scene object. :param relative_distance: [m] The relative distance from the scene object to the ego. :return: A IDM lead agents state """ if isinstance(agent, Agent): # Dynamic object longitudinal_velocity = agent.velocity.magnitude() # Wrap angle to [-pi, pi] relative_heading = principal_value(agent.center.heading - ego_state.center.heading) projected_velocity = transform( StateSE2(longitudinal_velocity, 0, 0), StateSE2(0, 0, relative_heading).as_matrix() ).x else: # Static object projected_velocity = 0.0 return IDMLeadAgentState(progress=relative_distance, velocity=projected_velocity, length_rear=0.0) def _get_free_road_leading_idm_state(self, ego_state: EgoState, ego_idm_state: IDMAgentState) -> IDMLeadAgentState: """ Returns a lead IDM agent state when there is no leading agent. :return: A IDM lead agents state. """ assert self._ego_path, "_ego_path has not yet been initialized. Please call the initialize() function first!" projected_velocity = 0.0 relative_distance = self._ego_path.get_end_progress() - ego_idm_state.progress length_rear = ego_state.car_footprint.length / 2 return IDMLeadAgentState(progress=relative_distance, velocity=projected_velocity, length_rear=length_rear) @staticmethod def _get_red_light_leading_idm_state(relative_distance: float) -> IDMLeadAgentState: """ Returns a lead IDM agent state that represents a red light intersection. :param relative_distance: [m] The relative distance from the intersection to the ego. :return: A IDM lead agents state. """ return IDMLeadAgentState(progress=relative_distance, velocity=0, length_rear=0) def _get_leading_object( self, ego_idm_state: IDMAgentState, ego_state: EgoState, occupancy_map: OccupancyMap, unique_observations: UniqueObjects, ) -> IDMLeadAgentState: """ Get the most suitable leading object based on the occupancy map. :param ego_idm_state: The ego's IDM state at current iteration. :param ego_state: EgoState at current iteration. :param occupancy_map: OccupancyMap containing all objects in the scene. :param unique_observations: A mapping between the object token and the object itself. """ intersecting_agents = occupancy_map.intersects(self._get_expanded_ego_path(ego_state, ego_idm_state)) # Check if there are agents intersecting the ego's baseline if intersecting_agents.size > 0: # Extract closest object intersecting_agents.insert(self._ego_token, ego_state.car_footprint.geometry) nearest_id, nearest_agent_polygon, relative_distance = intersecting_agents.get_nearest_entry_to( self._ego_token ) # Red light at intersection if self._red_light_token in nearest_id: return self._get_red_light_leading_idm_state(relative_distance) # An agent is the leading agent return self._get_leading_idm_agent(ego_state, unique_observations[nearest_id], relative_distance) else: # No leading agent return self._get_free_road_leading_idm_state(ego_state, ego_idm_state) def _construct_occupancy_map( self, ego_state: EgoState, observation: Observation ) -> Tuple[OccupancyMap, UniqueObjects]: """ Constructs an OccupancyMap from Observations. :param ego_state: Current EgoState :param observation: Observations of other agents and static objects in the scene. :return: - OccupancyMap. - A mapping between the object token and the object itself. """ if isinstance(observation, DetectionsTracks): unique_observations = { detection.track_token: detection for detection in observation.tracked_objects.tracked_objects if np.linalg.norm(ego_state.center.array - detection.center.array) < self._occupancy_map_radius } return ( STRTreeOccupancyMapFactory.get_from_boxes(list(unique_observations.values())), unique_observations, ) else: raise ValueError(f"IDM planner only supports DetectionsTracks. Got {observation.detection_type()}") def _propagate(self, ego: IDMAgentState, lead_agent: IDMLeadAgentState, tspan: float) -> None: """ Propagate agent forward according to the IDM policy. :param ego: The ego's IDM state. :param lead_agent: The agent leading this agent. :param tspan: [s] The interval of time to propagate for. """ # TODO: Set target velocity to speed limit solution = self._policy.solve_forward_euler_idm_policy(IDMAgentState(0, ego.velocity), lead_agent, tspan) ego.progress += solution.progress ego.velocity = max(solution.velocity, 0) def _get_planned_trajectory( self, ego_state: EgoState, occupancy_map: OccupancyMap, unique_observations: UniqueObjects ) -> InterpolatedTrajectory: """ Plan a trajectory w.r.t. the occupancy map. :param ego_state: EgoState at current iteration. :param occupancy_map: OccupancyMap containing all objects in the scene. :param unique_observations: A mapping between the object token and the object itself. :return: A trajectory representing the predicted ego's position in future. """ assert ( self._ego_path_linestring ), "_ego_path_linestring has not yet been initialized. Please call the initialize() function first!" # Extract ego IDM state ego_progress = self._ego_path_linestring.project(Point(*ego_state.center.point.array)) ego_idm_state = IDMAgentState(progress=ego_progress, velocity=ego_state.dynamic_car_state.center_velocity_2d.x) vehicle_parameters = ego_state.car_footprint.vehicle_parameters # Initialize planned trajectory with current state current_time_point = ego_state.time_point projected_ego_state = self._idm_state_to_ego_state(ego_idm_state, current_time_point, vehicle_parameters) planned_trajectory: List[EgoState] = [projected_ego_state] # Propagate planned trajectory for set number of samples for _ in range(self._planned_trajectory_samples): # Propagate IDM state w.r.t. selected leading agent leading_agent = self._get_leading_object(ego_idm_state, ego_state, occupancy_map, unique_observations) self._propagate(ego_idm_state, leading_agent, self._planned_trajectory_sample_interval) # Convert IDM state back to EgoState current_time_point += TimePoint(int(self._planned_trajectory_sample_interval * 1e6)) ego_state = self._idm_state_to_ego_state(ego_idm_state, current_time_point, vehicle_parameters) planned_trajectory.append(ego_state) return InterpolatedTrajectory(planned_trajectory) def _idm_state_to_ego_state( self, idm_state: IDMAgentState, time_point: TimePoint, vehicle_parameters: VehicleParameters ) -> EgoState: """ Convert IDMAgentState to EgoState :param idm_state: The IDMAgentState to be converted. :param time_point: The TimePoint corresponding to the state. :param vehicle_parameters: VehicleParameters of the ego. """ assert self._ego_path, "_ego_path has not yet been initialized. Please call the initialize() function first!" new_ego_center = self._ego_path.get_state_at_progress( max(self._ego_path.get_start_progress(), min(idm_state.progress, self._ego_path.get_end_progress())) ) return EgoState.build_from_center( center=StateSE2(new_ego_center.x, new_ego_center.y, new_ego_center.heading), center_velocity_2d=StateVector2D(idm_state.velocity, 0), center_acceleration_2d=StateVector2D(0, 0), tire_steering_angle=0.0, time_point=time_point, vehicle_parameters=vehicle_parameters, ) def _annotate_occupancy_map( self, traffic_light_data: List[TrafficLightStatusData], occupancy_map: OccupancyMap ) -> None: """ Add red light lane connectors on the route plan to the occupancy map. Note: the function works inline, hence, the occupancy map will be modified in this function. :param traffic_light_data: A list of all available traffic status data. :param occupancy_map: The occupancy map to be annotated. """ assert self._map_api, "_map_api has not yet been initialized. Please call the initialize() function first!" assert ( self._candidate_lane_edge_ids is not None ), "_candidate_lane_edge_ids has not yet been initialized. Please call the initialize() function first!" for data in traffic_light_data: if ( data.status == TrafficLightStatusType.RED and str(data.lane_connector_id) in self._candidate_lane_edge_ids ): id_ = str(data.lane_connector_id) lane_conn = self._map_api.get_map_object(id_, SemanticMapLayer.LANE_CONNECTOR) occupancy_map.insert(f"{self._red_light_token}_{id_}", lane_conn.polygon)
412
0.898208
1
0.898208
game-dev
MEDIA
0.458044
game-dev
0.967582
1
0.967582
facebookarchive/xcbuild
1,345
Libraries/xcassets/Headers/xcassets/Asset/GCLeaderboard.h
/** Copyright (c) 2015-present, Facebook, Inc. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. */ #ifndef __xcassets_Asset_GCLeaderboard_h #define __xcassets_Asset_GCLeaderboard_h #include <xcassets/Asset/Asset.h> #include <xcassets/Asset/ImageStack.h> #include <xcassets/ContentReference.h> #include <plist/Dictionary.h> #include <memory> #include <string> #include <vector> #include <ext/optional> namespace xcassets { namespace Asset { class GCLeaderboard : public Asset { private: ext::optional<ContentReference> _contentReference; private: friend class Asset; using Asset::Asset; public: ext::optional<ContentReference> const &contentReference() const { return _contentReference; } public: ImageStack const *contentEmbedded() const { return this->child<ImageStack>(); } public: static AssetType Type() { return AssetType::GCLeaderboard; } virtual AssetType type() const { return AssetType::GCLeaderboard; } public: static ext::optional<std::string> Extension() { return std::string("gcleaderboard"); } protected: virtual bool parse(plist::Dictionary const *dict, std::unordered_set<std::string> *seen, bool check); }; } } #endif // !__xcassets_Asset_GCLeaderboard_h
412
0.920076
1
0.920076
game-dev
MEDIA
0.714947
game-dev
0.580032
1
0.580032
SammySemicolon/Malum-Mod
2,380
src/main/java/com/sammy/malum/core/systems/rite/effect/SpiritRiteEmpowermentEffect.java
package com.sammy.malum.core.systems.rite.effect; import com.sammy.malum.core.systems.registry.*; import com.sammy.malum.core.systems.spirit.type.*; import com.sammy.malum.registry.common.*; import net.minecraft.core.*; import net.minecraft.server.level.*; import net.minecraft.sounds.*; import net.minecraft.world.effect.*; import net.minecraft.world.entity.*; import net.minecraft.world.entity.player.*; import java.util.*; public abstract class SpiritRiteEmpowermentEffect<T extends LivingEntity> extends SpiritRiteEntityEffect<T> { protected final List<Holder<MobEffect>> effectTypes; protected final List<SpiritHolder<SpiritArcanaType>> spirits; @SafeVarargs public SpiritRiteEmpowermentEffect(List<Holder<MobEffect>> effectTypes, SpiritHolder<SpiritArcanaType>... spirits) { this(List.of(SpiritRiteEffectTag.AURA), effectTypes, spirits); } @SafeVarargs public SpiritRiteEmpowermentEffect(List<SpiritRiteEffectTag> tags, List<Holder<MobEffect>> effectTypes, SpiritHolder<SpiritArcanaType>... spirits) { super(tags); this.effectTypes = effectTypes; this.spirits = Arrays.asList(spirits); } @Override public boolean canApplyEffect(ServerLevel level, T target) { for (Holder<MobEffect> effectType : effectTypes) { MobEffectInstance effect = target.getEffect(effectType); if (effect == null) { continue; } if (effect.getAmplifier() <= 1) { return true; } } return false; } @Override public void applyEffect(ServerLevel level, T target) { applyEffect(level, target, 6000, 2); } public final void applyEffect(ServerLevel level, T target, int duration, int amplifier) { for (Holder<MobEffect> effectType : effectTypes) { if (target.hasEffect(effectType)) { var instance = new MobEffectInstance(effectType, duration, amplifier, true, true); target.addEffect(instance); } } createEffect(level, target, spirits); } @Override public Holder<SoundEvent> getImpactSound() { return MalumSoundEvents.SPARK_POTION_IMPACT; } @Override public float getImpactSoundVolume(LivingEntity target) { return target instanceof Player ? 1.2f : 0.6f; } }
412
0.724022
1
0.724022
game-dev
MEDIA
0.93302
game-dev
0.925379
1
0.925379
lets-all-be-stupid-forever/circuit-artist
9,747
luasrc/api.lua
local ffi = require 'ffi' local R = require 'raylib_api' local C = require 'c_api' local help = require 'tutorial' local Camera = require 'camera' local textbox = require 'textbox' local utils = require 'utils' -- File storing the save data for the game. local SAVEFILE_PATH='../save.json' local S = C.GetSharedState() local free = ffi.C.free local malloc = ffi.C.malloc local cast = ffi.cast local sizeof = ffi.sizeof local idToLevelLut = {} -- Level registry local levelOptions = {} function getLevelComponents() return levelOptions[S.level_desc.ilevel+1].chips end function getLevel() return levelOptions[S.level_desc.ilevel+1] end -- Copies a int* bits to the internal buffer space in a level -- Used only in input bits local function copyInputBits(srcPtr, dstBuffer) local c = 0 for _, name in ipairs(dstBuffer.__order) do local v = dstBuffer[name] for j = 1, #v do v[j] = srcPtr[c] c = c + 1 end end end local function copyOutputBits(srcBuffer, dstPtr) local c = 0 for _, name in ipairs(srcBuffer.__order) do local v = srcBuffer[name] for j = 1, #v do dstPtr[c] = v[j] c = c + 1 end end end local function toSprite(img) if type(img)== 'string' then local tex = R.LoadTexture(img) img = { tex, 0, 0, tex.width, tex.height, } end local s = ffi.new('Sprite') s.tex = img[1] local x = img[2] local y = img[3] local w = img[4] local h = img[5] s.region = ffi.new('Rectangle', {x,y,w,h}) return s end function initTutorial() for ih=1,#help do local h = help[ih] S.level_options.help_name[ih-1] = h.name local t = textbox.prepareText(h.text) -- Hack to make lua keep the table with the string so the reference in C is -- still valid. -- If we don't do this, the string will be garbage collected and the C -- pointer will be invalidated -- Ideally, we would like to do a strdup here, but idk how to do it :( h._t = t S.level_options.help_txt[ih-1] = t.text for i=1,#t.sprites do S.level_options.help_sprites[ih-1][i-1] = t.sprites[i] end end end function addLevel(co) table.insert(levelOptions, co) local i = #levelOptions local levelId = co.id if levelId ~= nil then idToLevelLut[levelId] = i end print('added level ' .. i .. ' ' .. co.name) -- local co = levelOptions[i] local opt = S.level_options.options[i-1] opt.ilevel = i-1 local icon = R.LoadTexture(co.icon) opt.icon = toSprite({icon, 0, 0, 33, 33}) opt.complete = false; local t = textbox.prepareText(co.desc) co._t = t -- Hack to make lua keep the table with the string so the reference in C is -- still valid. -- If we don't do this, the string will be garbage collected and the C -- pointer will be invalidated opt.desc = t.text for k=1,#t.sprites do opt.sprites[k-1] = t.sprites[k] end opt.name = co.name return i end function initApp() initTutorial() end local function setDirtyFlag(i, value) S.level_desc.extcomps[i-1].dirty = true end local function setLevelsDirty() local nc = S.level_desc.num_components for i =1,nc do setDirtyFlag(i, true) end end local function setApiClockValueAndCount(clock_value, clock_count, por) S.clock_update_value = clock_value S.clock_count = clock_count S.por = por end local function unloadStateLevels() local cd = S.level_desc if cd.pindesc ~= nil then free(cd.pindesc) cd.pindesc = nil end if cd.extcomps ~= nil then free(cd.extcomps) cd.extcomps = nil end cd.num_components = 0 end function setInitialLevelByName(levelName) for i=1,#levelOptions do if levelOptions[i].name == levelName then S.requested_level = i-1 end end end -- Called by C but can also be called from lua function apiLoadLevel() unloadStateLevels() ilevel = S.requested_level local cd = S.level_desc cd.ilevel = ilevel local co = levelOptions[ilevel+1] local nc = #co.chips cd.num_components = nc cd.pindesc = malloc(sizeof('PinDesc') * nc) cd.extcomps = malloc(sizeof('ExtComp') * nc) local y = 0 for i = 1, nc do local comp = co.chips[i] local pins = comp.pins local pd = cd.pindesc[i-1] pd.num_conn = #pins local ec= cd.extcomps[i-1] ec.ni = 0 ec.dirty = true ec.no = 0 for j = 1, #pins do local pin = pins[j] local len = pin[2] pd.conn[j-1].len = len pd.conn[j-1].name = pin[3] if pin[1] == 'input' then pd.conn[j-1].type = 0 for k = 1, len do ec.wires_in_x[ec.ni] = 0 ec.wires_in_y[ec.ni] = y + 4 ec.ni = ec.ni + 1 y = y + 2 end else pd.conn[j-1].type = 1 for k = 1, len do ec.wires_out_x[ec.no] = 0 ec.wires_out_y[ec.no] = y + 4 ec.no = ec.no + 1 y = y + 2 end end y = y + 6 end end end -- Called by C function apiStartSimulation() setLevelsDirty() local comps = getLevelComponents() for i = 1, #comps do comps[i].running = true comps[i]:onStart() S.level_desc.extcomps[i-1].dirty = true end end -- Called by C function apiStopSimulation() local comps = getLevelComponents() for i = 1, #comps do comps[i].running = false comps[i]:onStop() end end -- Called by C function apiOnLevelTick() local comps = getLevelComponents() for i = 1, #comps do comps[i].dirty = S.level_desc.extcomps[i-1].dirty comps[i]:onTick(S.dt) S.level_desc.extcomps[i-1].dirty = comps[i].dirty if i == 1 then local level = comps[1] local clock_value = -1 local por = level:getPowerOnReset() if level.dirty and por == 0 then clock_value = level.value end local clock_count = comps[i]:getClockCount() setApiClockValueAndCount(clock_value, clock_count, por) end end end local function getUpdateLevelComponent() local comps = getLevelComponents() local icomp = S.update_ctx.ic + 1 return icomp, comps[icomp] end -- Called by C function apiOnLevelClock() local inputs = S.update_ctx.next_in local icomp, level = getUpdateLevelComponent() local buffers = level:_updateBuffers() local reset = S.update_ctx.reset copyInputBits(inputs, buffers.nextIn) level.dirty = S.level_desc.extcomps[icomp-1].dirty level:onClock(buffers.nextIn, reset) S.level_desc.extcomps[icomp-1].dirty = level.dirty end -- Called by C function apiUpdateLevelComponent() local icomp, level = getUpdateLevelComponent() local buffers = level:_updateBuffers() local nextIn = buffers.nextIn local prevIn = buffers.prevIn local output = buffers.output copyInputBits(S.update_ctx.next_in, nextIn) copyInputBits(S.update_ctx.prev_in, prevIn) copyInputBits(S.update_ctx.output, output) level.dirty = S.level_desc.extcomps[icomp-1].dirty level:onUpdate(prevIn, nextIn, output) S.level_desc.extcomps[icomp-1].dirty = level.dirty copyOutputBits(output, S.update_ctx.output) end -- Called by C function apiOnLevelDraw() local rt = S.rt local cam = Camera(S.cx, S.cy, S.cs) local comps = getLevelComponents() for icomp=1,#comps do comps[icomp]:onDraw(rt, cam) end end function initPaletteFromImage(path) local img = R.LoadImage(path) C.CaSetPalFromImage(img) end -- Sets initial image of the game. -- It's useful when you're developping a level so you don't need -- to re-open your image every time. function setStartupImage(image_path) C.CaSetStartupImage(image_path) end local function updateSteamAchievements() if not C.SteamEnabled() then return end for i=1, #levelOptions do local level = levelOptions[i] if level.id ~= nil then local achievementName = 'ACHIEVEMENT_LVL_' .. level.id local opt = S.level_options.options[i-1] local isComplete = opt.complete if isComplete then local hasAchievement = C.SteamGetAchievement(achievementName) if not hasAchievement then C.SteamSetAchievement(achievementName) end end end end C.SteamRefreshAchievement(); end function notifyLevelCompleted() local opt = S.level_options.options[S.level_desc.ilevel] local complete_before = opt.complete opt.complete = true if not complete_before then saveProgress() local levelId = getLevel().id C.CaAddMessage("Level Complete!", 4) updateSteamAchievements() end end local function initSteam() if not C.SteamEnabled() then return end C.SteamInit() end local function shutdownSteam() if not C.SteamEnabled() then return end C.SteamShutdown() end -- loadProgress() should be called after all levels have been defined. It will -- read the save json file and override the C structs with the data written in -- the json. function loadProgress() local progress = utils.loadJson(SAVEFILE_PATH) if progress == nil then return end -- Checks whether a level is complete or not. for i=1,#levelOptions do local levelId = levelOptions[i].id if levelId ~= nil then local complete = progress['COMPLETE_' .. levelId] if complete ~= nil then S.level_options.options[i-1].complete = complete end end end updateSteamAchievements() end -- The saveProgress() function will read the data from the C structs and write -- a JSON file. -- Progress for levels need a "id" field in the level definition. function saveProgress() local progress = {} for i=1,#levelOptions do local levelId = levelOptions[i].id if levelId ~= nil then progress['COMPLETE_' .. levelId] = S.level_options.options[i-1].complete end end utils.saveJson(progress, SAVEFILE_PATH) end -- Called by C API before API is closed. function apiOnExit() saveProgress() end
412
0.909853
1
0.909853
game-dev
MEDIA
0.286082
game-dev
0.938151
1
0.938151
arranger1044/iSoul
9,003
Museek/NewNet/nnevent.h
/* NewNet - A networking framework in C++ Copyright (C) 2006-2007 Ingmar K. Steen (iksteen@gmail.com) Copyright 2008 little blue poney <lbponey@users.sourceforge.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef NEWNET_EVENT_H #define NEWNET_EVENT_H #include "nnobject.h" #include "nnrefptr.h" #include <vector> #include <functional> #include <algorithm> namespace NewNet { //! Simple event dispatcher class. /*! The NewNet::Event class provides a simple and easy to use event aggregation solution. Callbacks can be registered to an event that will be invoked upon emitting the event. */ template<typename T> class Event : public Object { public: //! Abstract callback type for Event. /*! A callback can be added to an event so that operator()(T t) will be called when the event is emitted. */ class Callback : public Object { public: //! Constructor. Callback() { } //! Destructor. virtual ~Callback() { } //! Slot method. /*! Override this and implement your callback function. */ virtual void operator()(T t) = 0; #ifndef DOXYGEN_UNDOCUMENTED /* Callback was added to an Event */ void onConnected(Event * event) { m_Events.push_back(event); } /* Callback was disconnected from an Event */ void onDisconnected(Event * event) { typename std::vector<Event *>::iterator it; it = std::find(m_Events.begin(), m_Events.end(), event); if (it != m_Events.end()) m_Events.erase(it); } #endif // DOXYGEN_UNDOCUMENTED //! Disconnect this callback from all events. /*! Calling this will result in the disconnection of the callback from all the events it is registered to. Note: Events store a RefPtr to the callbacks. The callback class might be deleted when disconnecting from all registered events. */ void disconnect() { /* Artificially increase our reference count. Otherwise we might get prematurely deleted when we get disconnected from the last Event */ ++(this->refCounter()); /* Disconnect from all the events we're registered to */ while(! m_Events.empty()) m_Events.front()->disconnect(this); /* Decrease the refrence count again and delete if necessary */ if(--(this->refCounter())) delete this; } private: /* Private copy constructor, you don't want this happening */ Callback(const Callback &) { } std::vector<Event *> m_Events; }; private: #ifndef DOXYGEN_UNDOCUMENTED /* Callback to a method of a NewNet::Object */ template<class ObjectType, typename MethodType> class BoundCallback : public Callback { private: /* We use this to track deletion of our Object */ class GuardObjectCallback : public GuardObject::Callback { public: GuardObjectCallback(BoundCallback * callback) : m_Callback(callback) { } /* If the Object is destroyed, notify our Callback */ void operator()(Object *) { m_Callback->onObjectDeleted(); } private: BoundCallback * m_Callback; }; GuardObjectCallback * m_GuardObjectCallback; public: BoundCallback(ObjectType * object, MethodType method) : m_Object(object), m_Method(method) { /* Register to the Object's delete guard */ m_GuardObjectCallback = new GuardObjectCallback(this); m_Object->guardObject() += m_GuardObjectCallback; } ~BoundCallback() { /* If the object is still valid, remove our delete callback from its delete guard */ if(m_Object) m_Object->guardObject() -= m_GuardObjectCallback; delete m_GuardObjectCallback; } void operator()(T t) { /* Since C++ methods are internally called as Class::Method(object, ...), this results in a valid C++ bound method call. */ if(m_Object) std::bind1st(std::mem_fun(m_Method), m_Object)(t); } protected: /* Object we're bound to was deleted, reset pointer and disconnect from all Events we're registered to */ void onObjectDeleted() { m_Object = 0; Callback::disconnect(); } private: /* Private copy constructor, you don't want this happening */ BoundCallback(const BoundCallback &) { } ObjectType * m_Object; MethodType m_Method; }; #endif // DOXYGEN_UNDOCUMENTED public: //! Constructor. /*! Create a new event to which you can register callbacks. */ Event() { } //! Copy constructor. /*! When an event is copied, all the callbacks registered to the original event will also be connected to this event. */ Event(const Event & that) { typename std::vector<RefPtr<Callback> >::const_iterator it, end; end = that.m_Callbacks.end(); for(it = that.m_Callbacks.begin(); it != end; ++it) connect(*it); } //! Destructor. /*! Disconnects all callbacks from the event. Note: see clear(). */ virtual ~Event() { /* Disconnect all Callbacks */ clear(); } //! Empty the event callback list. /*! Call this to remove all the callbacks from this event. Note: the event stores a RefPtr to all the callbacks registered. Clearing the event may delete the callback if there are no other references to it. */ void clear() { while(! m_Callbacks.empty()) disconnect(m_Callbacks.front()); } //! Connect a callback to the event. /*! Add a callback to this event so that it will get invoked when the event is emitted. Note: stores a RefPtr to the callback. */ Callback * connect(Callback * callback) { /* Push a RefPtr to the Callback to our list */ m_Callbacks.push_back(callback); /* Notify the Callback that it's connected to us */ callback->onConnected(this); return callback; } //! Create a callback to a bound method. /*! This will construct a callback object that will invoke a method of an object. */ template<class ObjectType, typename MethodType> static Callback * bind(ObjectType * object, MethodType method) { return new BoundCallback<ObjectType, MethodType>(object, method); } //! Connect callback to a method of an object to the event. /*! Add a callback to a method of an object so that it will get invoked when the event is emitted. Note: stores a RefPtr to the newly created callback. */ template<class ObjectType, typename MethodType> Callback * connect(ObjectType * object, MethodType method) { return connect(bind(object, method)); } //! Disconnect a callback from the event. /*! Remove a callback from the invocation list. Note: the event stores a RefPtr to the callback. If the event holds the last RefPtr, the callback will be deleted. */ void disconnect(Callback * callback) { /* Artificially increase the reference count so it doesn't get deleted prematurely */ ++(callback->refCounter()); /* Delete the Callback from our list */ typename std::vector<RefPtr<Callback> >::iterator it; it = std::find(m_Callbacks.begin(), m_Callbacks.end(), callback); if (it != m_Callbacks.end()) m_Callbacks.erase(it); /* Notify the Callback it was disconnected */ callback->onDisconnected(this); /* Decrease the reference count of the Callback and delete if necessary */ if(--(callback->refCounter())) delete callback; } //! Emit the event. /*! Emit the event, invokes the Callback::operator()(T t) method of all registered callbacks. */ void operator()(T t) { std::vector<RefPtr<Callback> > callbacks(m_Callbacks); typename std::vector<RefPtr<Callback> >::iterator it, end = callbacks.end(); for(it = callbacks.begin(); it != end; ++it) { (*(*it))(t); } } private: std::vector<RefPtr<Callback> > m_Callbacks; }; } #endif // NEWNET_EVENT_H
412
0.971947
1
0.971947
game-dev
MEDIA
0.179807
game-dev
0.955516
1
0.955516
Gethe/wow-ui-source
2,183
Interface/AddOns/Blizzard_UnitFrame/Mists/MonkHarmonyBar.lua
MonkHarmonyBarMixin = {} MonkLightEnergyMixin = {} function MonkLightEnergyMixin:SetEnergy(active) if self.active == active then return; end self.active = active; if active then if (self.deactivate:IsPlaying()) then self.deactivate:Stop(); end if (not self.activate:IsPlaying()) then self.activate:Play(); end else if (self.activate:IsPlaying()) then self.activate:Stop(); end if (not self.deactivate:IsPlaying()) then self.deactivate:Play(); end end end function MonkHarmonyBarMixin:Update() local light = UnitPower("player", Enum.PowerType.Chi ); -- if max light changed, show/hide the 5th and update anchors local maxLight = UnitPowerMax("player", Enum.PowerType.Chi ); if ( self.maxLight ~= maxLight ) then if ( maxLight == 4 ) then self.lightEnergy1:SetPoint("LEFT", -43, 1); self.lightEnergy2:SetPoint("LEFT", self.lightEnergy1, "RIGHT", 5, 0); self.lightEnergy3:SetPoint("LEFT", self.lightEnergy2, "RIGHT", 5, 0); self.lightEnergy4:SetPoint("LEFT", self.lightEnergy3, "RIGHT", 5, 0); self.lightEnergy5:Hide(); else self.lightEnergy1:SetPoint("LEFT", -46, 1); self.lightEnergy2:SetPoint("LEFT", self.lightEnergy1, "RIGHT", 1, 0); self.lightEnergy3:SetPoint("LEFT", self.lightEnergy2, "RIGHT", 1, 0); self.lightEnergy4:SetPoint("LEFT", self.lightEnergy3, "RIGHT", 1, 0); self.lightEnergy5:Show(); end self.maxLight = maxLight; end for i = 1, self.maxLight do self["lightEnergy"..i]:SetEnergy(i<=light); end end function MonkHarmonyBarMixin:OnLoad() -- Disable frame if not a monk local _, class = UnitClass("player"); if ( class ~= "MONK" ) then self:Hide(); return; end self.maxLight = 4; --self:SetFrameLevel(self:GetParent():GetFrameLevel() + 2); self:RegisterEvent("PLAYER_ENTERING_WORLD"); self:RegisterEvent("UNIT_DISPLAYPOWER"); self:RegisterUnitEvent("UNIT_POWER_FREQUENT", "player"); self:RegisterUnitEvent("UNIT_MAXPOWER", "player"); end function MonkHarmonyBarMixin:OnEvent(event, arg1, arg2) if ( event == "UNIT_POWER_FREQUENT" ) then if ( arg2 == "CHI" or arg2 == "DARK_FORCE" ) then self:Update(self); end else self:Update(self); end end
412
0.854401
1
0.854401
game-dev
MEDIA
0.912515
game-dev
0.933388
1
0.933388
Gaby-Station/Gaby-Station
7,899
Content.Shared/_Shitcode/Heretic/Systems/SharedEntropicPlumeSystem.cs
// SPDX-FileCopyrightText: 2025 Aiden <28298836+Aidenkrz@users.noreply.github.com> // SPDX-FileCopyrightText: 2025 Aidenkrz <aiden@djkraz.com> // SPDX-FileCopyrightText: 2025 Aviu00 <93730715+Aviu00@users.noreply.github.com> // SPDX-FileCopyrightText: 2025 Misandry <mary@thughunt.ing> // SPDX-FileCopyrightText: 2025 gus <august.eymann@gmail.com> // // SPDX-License-Identifier: AGPL-3.0-or-later using System.Linq; using Content.Goobstation.Common.Religion; using Content.Shared._Goobstation.Heretic.Components; using Content.Shared._Goobstation.Wizard.TimeStop; using Content.Shared._Goobstation.Wizard.Traps; using Content.Shared.Administration; using Content.Shared.Chemistry.Components; using Content.Shared.Chemistry.EntitySystems; using Content.Shared.CombatMode; using Content.Shared.Examine; using Content.Shared.Eye.Blinding.Components; using Content.Shared.Heretic; using Content.Shared.Mobs.Components; using Content.Shared.Mobs.Systems; using Content.Shared.StatusEffect; using Content.Shared.Stunnable; using Content.Shared.Weapons.Melee; using Content.Shared.Weapons.Ranged.Systems; using Content.Shared.Inventory; using Robust.Shared.Network; using Robust.Shared.Physics.Components; using Robust.Shared.Physics.Events; using Robust.Shared.Physics.Systems; using Robust.Shared.Player; using Robust.Shared.Random; using Robust.Shared.Timing; namespace Content.Shared._Goobstation.Heretic.Systems; public abstract class SharedEntropicPlumeSystem : EntitySystem { [Dependency] private readonly IGameTiming _timing = default!; [Dependency] private readonly INetManager _net = default!; [Dependency] private readonly ISharedPlayerManager _player = default!; [Dependency] private readonly StatusEffectsSystem _status = default!; [Dependency] private readonly SharedSolutionContainerSystem _solution = default!; [Dependency] private readonly SharedGunSystem _gun = default!; [Dependency] private readonly SharedMeleeWeaponSystem _weapon = default!; [Dependency] private readonly EntityLookupSystem _lookup = default!; [Dependency] private readonly ExamineSystemShared _examine = default!; [Dependency] private readonly SharedCombatModeSystem _combat = default!; [Dependency] private readonly MobStateSystem _mobState = default!; [Dependency] private readonly SharedPhysicsSystem _physics = default!; [Dependency] private readonly InventorySystem _inventory = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<EntropicPlumeComponent, StartCollideEvent>(OnStartCollide); UpdatesOutsidePrediction = true; } private void OnStartCollide(Entity<EntropicPlumeComponent> ent, ref StartCollideEvent args) { if (ent.Comp.AffectedEntities.Contains(args.OtherEntity)) return; if (!HasComp<MobStateComponent>(args.OtherEntity) || HasComp<HereticComponent>(args.OtherEntity) || HasComp<GhoulComponent>(args.OtherEntity)) return; if (_inventory.GetHandOrInventoryEntities(args.OtherEntity, SlotFlags.WITHOUT_POCKET) .Any(item => HasComp<DivineInterventionComponent>(item))) return; ent.Comp.AffectedEntities.Add(args.OtherEntity); _status.TryAddStatusEffect<TemporaryBlindnessComponent>(args.OtherEntity, "TemporaryBlindness", TimeSpan.FromSeconds(ent.Comp.Duration), true); var affected = EnsureComp<EntropicPlumeAffectedComponent>(args.OtherEntity); affected.Duration = MathF.Max(affected.Duration, ent.Comp.Duration); var solution = new Solution(); foreach (var reagent in ent.Comp.Reagents) { solution.AddReagent(reagent.Key, reagent.Value); } if (!_solution.TryGetInjectableSolution(args.OtherEntity, out var targetSolution, out _)) return; _solution.TryAddSolution(targetSolution.Value, solution); } public override void Update(float frameTime) { base.Update(frameTime); var rand = new System.Random((int) _timing.CurTick.Value); var query = EntityQueryEnumerator<EntropicPlumeAffectedComponent, MobStateComponent, TransformComponent>(); while (query.MoveNext(out var uid, out var affected, out var mobState, out var xform)) { Amok(); if (_net.IsClient) continue; affected.Duration -= frameTime; if (affected.Duration > 0) continue; RemCompDeferred(uid, affected); continue; void Amok() { if (_net.IsClient && _player.LocalEntity != uid) return; var curTime = _timing.CurTime; if (curTime < affected.NextAttack) return; if (!TryComp(uid, out CombatModeComponent? combat)) return; if (_mobState.IsIncapacitated(uid, mobState)) return; if (HasComp<StunnedComponent>(uid) || HasComp<FrozenComponent>(uid) || HasComp<AdminFrozenComponent>(uid) || HasComp<IceCubeComponent>(uid)) return; _gun.TryGetGun(uid, out var gun, out var gunComp); _weapon.TryGetWeapon(uid, out var weapon, out var meleeComp); float range; float attackRate; if (gunComp != null) { if (gunComp.NextFire > curTime) return; attackRate = gunComp.FireRate; range = 3f; } else if (meleeComp != null) { if (meleeComp.NextAttack > curTime) return; attackRate = meleeComp.AttackRate; range = meleeComp.Range; } else return; if (attackRate == 0f) return; var targets = FindPotentialTargets((uid, xform), range); if (targets.Count == 0) return; affected.NextAttack = curTime + TimeSpan.FromSeconds(1f / attackRate); Dirty(uid, affected); _combat.SetInCombatMode(uid, true, combat); var target = rand.Pick(targets); var coords = Transform(target).Coordinates; if (gunComp != null) _gun.AttemptShoot(uid, gun, gunComp, coords, target); else if (meleeComp != null) _weapon.AttemptLightAttack(uid, weapon, meleeComp, target); } } if (!_timing.IsFirstTimePredicted) return; // Prevent it from behaving weirdly on moving shuttles var plumeQuery = EntityQueryEnumerator<EntropicPlumeComponent, PhysicsComponent>(); while (plumeQuery.MoveNext(out var uid, out _, out var physics)) { if (physics.BodyStatus != BodyStatus.OnGround) _physics.SetBodyStatus(uid, physics, BodyStatus.OnGround); } } private List<EntityUid> FindPotentialTargets(Entity<TransformComponent> attacker, float range) { List<EntityUid> result = new(); var ents = _lookup.GetEntitiesInRange<MobStateComponent>(attacker.Comp.Coordinates, range, LookupFlags.Dynamic); foreach (var ent in ents) { if (ent.Owner == attacker.Owner) continue; if (HasComp<HereticComponent>(ent.Owner) || HasComp<GhoulComponent>(ent.Owner)) continue; if (_examine.InRangeUnOccluded(attacker, ent, range + 1f)) result.Add(ent); } return result; } }
412
0.95037
1
0.95037
game-dev
MEDIA
0.983063
game-dev
0.943394
1
0.943394
MergHQ/CRYENGINE
23,096
Code/CryEngine/Cry3DEngine/Brush.cpp
// Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved. // ------------------------------------------------------------------------- // File name: brush.cpp // Version: v1.00 // Created: 28/5/2001 by Vladimir Kajalin // Compilers: Visual Studio.NET // Description: // ------------------------------------------------------------------------- // History: // //////////////////////////////////////////////////////////////////////////// #include "StdAfx.h" #include "StatObj.h" #include "ObjMan.h" #include "VisAreas.h" #include "terrain_sector.h" #include "PolygonClipContext.h" #include "3dEngine.h" #include "IndexedMesh.h" #include "Brush.h" #include "terrain.h" const char* CBrush::GetEntityClassName() const { return "Brush"; } const char* CBrush::GetName() const { if (m_pStatObj) return m_pStatObj->GetFilePath(); return "StatObjNotSet"; } bool CBrush::HasChanged() { return false; } #if CRY_PLATFORM_WINDOWS && CRY_PLATFORM_64BIT #pragma warning( push ) //AMD Port #pragma warning( disable : 4311 ) #endif CLodValue CBrush::ComputeLod(int wantedLod, const SRenderingPassInfo& passInfo) { CVars* pCVars = GetCVars(); uint8 nDissolveRefA = 0; int nLodA = -1; int nLodB = -1; if (CStatObj* pStatObj = (CStatObj*)CBrush::GetEntityStatObj()) { const Vec3 vCamPos = passInfo.GetCamera().GetPosition(); const float fEntDistance = sqrt_tpl(Distance::Point_AABBSq(vCamPos, CBrush::GetBBox())) * passInfo.GetZoomFactor(); // update LOD faster in zoom mode if (passInfo.IsGeneralPass() && passInfo.IsZoomActive()) { wantedLod = CObjManager::GetObjectLOD(this, fEntDistance); } if (pCVars->e_Dissolve && passInfo.IsGeneralPass() && !(pStatObj->m_nFlags & STATIC_OBJECT_COMPOUND)) { int nLod = CLAMP(wantedLod, pStatObj->GetMinUsableLod(), (int)pStatObj->m_nMaxUsableLod); nLod = pStatObj->FindNearesLoadedLOD(nLod, true); SLodDistDissolveTransitionState& rState = m_pTempData->userData.lodDistDissolveTransitionState; // if we're more than one LOD away we've either zoomed in quickly // or we streamed in some LODs really late. In either case we want // to pop rather than get stuck in a dissolve that started way too late. if (rState.nOldLod >= 0 && nLod >= 0 && (rState.nOldLod > nLod + 1 || rState.nOldLod < nLod - 1) ) rState.nOldLod = nLod; // when we first load before streaming we get a lod of -1. When a lod streams in // we kick off a transition to N, but without moving there's nothing to continue the transition. // Catch this case when we claim to be in lod -1 but are too close, and snap. if (rState.nOldLod == -1 && fEntDistance < 0.5f * m_fWSMaxViewDist) rState.nOldLod = nLod; uint32 prevState = (((uint32)rState.nOldLod) << 8) | rState.nNewLod; float fDissolve = GetObjManager()->GetLodDistDissolveRef(&rState, fEntDistance, nLod, passInfo); uint32 newState = (((uint32)rState.nOldLod) << 8) | rState.nNewLod; // ensure old lod is still around. If not find closest lod if (rState.nOldLod != rState.nNewLod && rState.nOldLod >= 0) { rState.nOldLod = pStatObj->FindNearesLoadedLOD(rState.nOldLod, true); } else if (rState.nOldLod >= 0) { // we can actually fall back into this case (even though we know nLod is valid). rState.nOldLod = rState.nNewLod = pStatObj->FindNearesLoadedLOD(rState.nOldLod, true); } // only bother to check if we are dissolving and we've just kicked off a new dissolve transition if (rState.nOldLod != rState.nNewLod && prevState != newState) { // LOD cutoff point, this is about where the transition should be triggered. const float fEntityLodRatio = std::max(GetLodRatioNormalized(), FLT_MIN); const float fDistMultiplier = 1.0f / (fEntityLodRatio * Get3DEngine()->GetFrameLodInfo().fTargetSize); float dist = pStatObj->GetLodDistance() * max(rState.nOldLod, rState.nNewLod) * fDistMultiplier; // we started way too late, most likely object LOD streamed in very late, just snap. if (fabsf(rState.fStartDist - dist) > GetFloatCVar(e_DissolveDistband)) { rState.nOldLod = rState.nNewLod; } } nDissolveRefA = (uint8)(255.f * SATURATE(fDissolve)); nLodA = rState.nOldLod; nLodB = rState.nNewLod; } else { nDissolveRefA = 0; nLodA = CLAMP(wantedLod, pStatObj->GetMinUsableLod(), (int)pStatObj->m_nMaxUsableLod); if (!(pStatObj->m_nFlags & STATIC_OBJECT_COMPOUND)) nLodA = pStatObj->FindNearesLoadedLOD(nLodA, true); nLodB = -1; } if (pCVars->e_Dissolve && !passInfo.IsCachedShadowPass()) { float fDissolveDist = CLAMP(0.1f * m_fWSMaxViewDist, GetFloatCVar(e_DissolveDistMin), GetFloatCVar(e_DissolveDistMax)); const float fDissolveStartDist = m_fWSMaxViewDist - fDissolveDist; if (fEntDistance > fDissolveStartDist) { float fDissolve = (fEntDistance - fDissolveStartDist) / fDissolveDist; nDissolveRefA = (uint8)(255.f * SATURATE(fDissolve)); nLodB = -1; } } } return CLodValue(nLodA, nDissolveRefA, nLodB); } void CBrush::Render(const struct SRendParams& _EntDrawParams, const SRenderingPassInfo& passInfo) { FUNCTION_PROFILER_3DENGINE; if (!m_pStatObj || m_dwRndFlags & ERF_HIDDEN) return; //false; if (m_dwRndFlags & ERF_COLLISION_PROXY || m_dwRndFlags & ERF_RAYCAST_PROXY) { // Collision proxy is visible in Editor while in editing mode. if (!gEnv->IsEditor() || !gEnv->IsEditing()) { if (GetCVars()->e_DebugDraw == 0) return; //true; } } // some parameters will be modified SRendParams rParms = _EntDrawParams; if (m_nMaterialLayers) rParms.nMaterialLayers = m_nMaterialLayers; rParms.pMatrix = &m_Matrix; rParms.nClipVolumeStencilRef = 0; rParms.pMaterial = m_pMaterial; if (!m_Matrix.m01 && !m_Matrix.m02 && !m_Matrix.m10 && !m_Matrix.m12 && !m_Matrix.m20 && !m_Matrix.m21) rParms.dwFObjFlags &= ~FOB_TRANS_ROTATE; else rParms.dwFObjFlags |= FOB_TRANS_ROTATE; // get statobj for rendering IStatObj* pStatObj = m_pStatObj; // render if (pStatObj) { pStatObj->Render(rParms, passInfo); } } #if CRY_PLATFORM_WINDOWS && CRY_PLATFORM_64BIT #pragma warning( pop ) //AMD Port #endif void CBrush::SetMatrix(const Matrix34& mat) { Get3DEngine()->UnRegisterEntityAsJob(this); bool replacePhys = false; if (!IsMatrixValid(mat)) { Warning("Error: IRenderNode::SetMatrix: Invalid matrix passed from the editor - ignored, reset to identity: %s", GetName()); replacePhys = true; m_Matrix.SetIdentity(); } else { replacePhys = fabs(mat.GetColumn(0).len() - m_Matrix.GetColumn(0).len()) + fabs(mat.GetColumn(1).len() - m_Matrix.GetColumn(1).len()) + fabs(mat.GetColumn(2).len() - m_Matrix.GetColumn(2).len()) > FLT_EPSILON; m_Matrix = mat; } pe_params_foreign_data foreignData; foreignData.iForeignFlags = 0; if (!replacePhys && m_pPhysEnt) { m_pPhysEnt->GetParams(&foreignData); replacePhys = !(foreignData.iForeignFlags & PFF_OUTDOOR_AREA) != !(m_dwRndFlags & ERF_NODYNWATER); } CalcBBox(); Get3DEngine()->RegisterEntity(this); if (replacePhys) Dephysicalize(); if (!m_pPhysEnt) Physicalize(); else { // Just move physics. pe_status_placeholder spc; if (m_pPhysEnt->GetStatus(&spc) && !spc.pFullEntity) { pe_params_bbox pbb; pbb.BBox[0] = m_WSBBox.min; pbb.BBox[1] = m_WSBBox.max; m_pPhysEnt->SetParams(&pbb); } else { pe_params_pos par_pos; par_pos.pos = m_Matrix.GetTranslation(); par_pos.q = Quat(Matrix33(m_Matrix) * Diag33(m_Matrix.GetColumn(0).len(), m_Matrix.GetColumn(1).len(), m_Matrix.GetColumn(2).len()).invert()); m_pPhysEnt->SetParams(&par_pos); } ////////////////////////////////////////////////////////////////////////// // Update physical flags. ////////////////////////////////////////////////////////////////////////// if (m_dwRndFlags & ERF_HIDABLE) foreignData.iForeignFlags |= PFF_HIDABLE; else foreignData.iForeignFlags &= ~PFF_HIDABLE; if (m_dwRndFlags & ERF_HIDABLE_SECONDARY) foreignData.iForeignFlags |= PFF_HIDABLE_SECONDARY; else foreignData.iForeignFlags &= ~PFF_HIDABLE_SECONDARY; // flag to exclude from AI triangulation if (m_dwRndFlags & ERF_EXCLUDE_FROM_TRIANGULATION) foreignData.iForeignFlags |= PFF_EXCLUDE_FROM_STATIC; else foreignData.iForeignFlags &= ~PFF_EXCLUDE_FROM_STATIC; m_pPhysEnt->SetParams(&foreignData); } if (m_pDeform) m_pDeform->BakeDeform(m_Matrix); } void CBrush::CalcBBox() { m_WSBBox.min = SetMaxBB(); m_WSBBox.max = SetMinBB(); if (!m_pStatObj) return; m_WSBBox.min = m_pStatObj->GetBoxMin(); m_WSBBox.max = m_pStatObj->GetBoxMax(); m_WSBBox.SetTransformedAABB(m_Matrix, m_WSBBox); m_fMatrixScale = m_Matrix.GetColumn0().GetLength(); } CBrush::CBrush() { m_WSBBox.min = m_WSBBox.max = Vec3(ZERO); m_dwRndFlags = 0; m_Matrix.SetIdentity(); m_pPhysEnt = 0; m_Matrix.SetIdentity(); m_pMaterial = 0; m_nLayerId = 0; m_pStatObj = NULL; m_pMaterial = NULL; m_bVehicleOnlyPhysics = false; m_bMerged = 0; m_bDrawLast = false; m_fMatrixScale = 1.f; m_collisionClassIdx = 0; m_pDeform = NULL; GetInstCount(GetRenderNodeType())++; } CBrush::~CBrush() { INDENT_LOG_DURING_SCOPE(true, "Destroying brush \"%s\"", this->GetName()); Dephysicalize(); Get3DEngine()->FreeRenderNodeState(this); m_pStatObj = NULL; if (m_pDeform) delete m_pDeform; if (m_pTempData) Get3DEngine()->FreeRenderNodeTempData(&m_pTempData); assert(!m_pTempData); GetInstCount(GetRenderNodeType())--; } void CBrush::Physicalize(bool bInstant) { PhysicalizeOnHeap(NULL, bInstant); } void CBrush::PhysicalizeOnHeap(IGeneralMemoryHeap* pHeap, bool bInstant) { MEMSTAT_CONTEXT_FMT(EMemStatContextTypes::MSC_Physics, 0, "Brush: %s", m_pStatObj ? m_pStatObj->GetFilePath() : "(unknown)"); if (m_pStatObj && (m_pStatObj->GetBreakableByGame() || m_pStatObj->GetIDMatBreakable() != -1)) { pHeap = m_p3DEngine->GetBreakableBrushHeap(); } float fScaleX = m_Matrix.GetColumn(0).len(); float fScaleY = m_Matrix.GetColumn(1).len(); float fScaleZ = m_Matrix.GetColumn(2).len(); if (!m_pStatObj || !m_pStatObj->IsPhysicsExist()) { // skip non uniform scaled object or objects without physics // Check if we are acompound object. if (m_pStatObj && !m_pStatObj->IsPhysicsExist() && (m_pStatObj->GetFlags() & STATIC_OBJECT_COMPOUND)) { // Try to physicalize compound object. } else { Dephysicalize(); return; } } AABB WSBBox = GetBBox(); bool notPodable = max(WSBBox.max.x - WSBBox.min.x, WSBBox.max.y - WSBBox.min.y) > Get3DEngine()->GetCVars()->e_OnDemandMaxSize; if (!(GetCVars()->e_OnDemandPhysics & 0x2) || notPodable || (m_pStatObj->GetFlags() & STATIC_OBJECT_COMPOUND)) bInstant = true; if (m_pDeform) { m_pDeform->CreateDeformableSubObject(true, GetMatrix(), pHeap); } if (!bInstant) { gEnv->pPhysicalWorld->RegisterBBoxInPODGrid(&WSBBox.min); return; } // create new if (!m_pPhysEnt) { m_pPhysEnt = GetSystem()->GetIPhysicalWorld()->CreatePhysicalEntity(PE_STATIC, NULL, (IRenderNode*)this, PHYS_FOREIGN_ID_STATIC, -1, pHeap); if (!m_pPhysEnt) return; } pe_action_remove_all_parts remove_all; m_pPhysEnt->Action(&remove_all); pe_geomparams params; if (m_pStatObj->GetPhysGeom(PHYS_GEOM_TYPE_DEFAULT)) { if (GetRndFlags() & ERF_COLLISION_PROXY) { // Collision proxy only collides with players and vehicles. params.flags = geom_colltype_player | geom_colltype_vehicle; } if (GetRndFlags() & ERF_RAYCAST_PROXY) { // Collision proxy only collides with players and vehicles. params.flags = geom_colltype_ray; } /*if (m_pStatObj->m_arrPhysGeomInfo[PHYS_GEOM_TYPE_NO_COLLIDE]) params.flags &= ~geom_colltype_ray;*/ if (m_bVehicleOnlyPhysics || (m_pStatObj->GetVehicleOnlyPhysics() != 0)) params.flags = geom_colltype_vehicle; if (GetCVars()->e_ObjQuality != CONFIG_LOW_SPEC) { params.idmatBreakable = m_pStatObj->GetIDMatBreakable(); if (m_pStatObj->GetBreakableByGame()) params.flags |= geom_manually_breakable; } else params.idmatBreakable = -1; } Matrix34 mtxScale; mtxScale.SetScale(Vec3(fScaleX, fScaleY, fScaleZ)); params.pMtx3x4 = &mtxScale; m_pStatObj->Physicalize(m_pPhysEnt, &params); if (m_dwRndFlags & (ERF_HIDABLE | ERF_HIDABLE_SECONDARY | ERF_EXCLUDE_FROM_TRIANGULATION | ERF_NODYNWATER)) { pe_params_foreign_data foreignData; m_pPhysEnt->GetParams(&foreignData); if (m_dwRndFlags & ERF_HIDABLE) foreignData.iForeignFlags |= PFF_HIDABLE; if (m_dwRndFlags & ERF_HIDABLE_SECONDARY) foreignData.iForeignFlags |= PFF_HIDABLE_SECONDARY; //[PETAR] new flag to exclude from triangulation if (m_dwRndFlags & ERF_EXCLUDE_FROM_TRIANGULATION) foreignData.iForeignFlags |= PFF_EXCLUDE_FROM_STATIC; if (m_dwRndFlags & ERF_NODYNWATER) foreignData.iForeignFlags |= PFF_OUTDOOR_AREA; m_pPhysEnt->SetParams(&foreignData); } pe_params_flags par_flags; par_flags.flagsOR = pef_never_affect_triggers | pef_log_state_changes; m_pPhysEnt->SetParams(&par_flags); pe_params_pos par_pos; par_pos.pos = m_Matrix.GetTranslation(); par_pos.q = Quat(Matrix33(m_Matrix) * Diag33(fScaleX, fScaleY, fScaleZ).invert()); par_pos.bEntGridUseOBB = 1; m_pPhysEnt->SetParams(&par_pos); pe_params_collision_class pcc; Get3DEngine()->GetCollisionClass(pcc.collisionClassOR, m_collisionClassIdx); m_pPhysEnt->SetParams(&pcc); if (m_pMaterial) UpdatePhysicalMaterials(); if (GetRndFlags() & ERF_NODYNWATER) { pe_params_part ppart; ppart.flagsAND = ~geom_floats; m_pPhysEnt->SetParams(&ppart); } } bool CBrush::PhysicalizeFoliage(bool bPhysicalize, int iSource, int nSlot) { if (nSlot < 0) { bool res = false; for (int i = 0; i < m_pStatObj->GetSubObjectCount(); i++) res = res || PhysicalizeFoliage(bPhysicalize, iSource, i); return res; } if (IStatObj::SSubObject* pSubObj = m_pStatObj->GetSubObject(nSlot)) if (bPhysicalize) { if (!pSubObj->pStatObj || !((CStatObj*)pSubObj->pStatObj)->m_nSpines) return false; if (!(m_pStatObj->GetFlags() & STATIC_OBJECT_CLONE)) { m_pStatObj = m_pStatObj->Clone(false, false, false); pSubObj = m_pStatObj->GetSubObject(nSlot); } Matrix34 mtx = m_Matrix * pSubObj->localTM; pSubObj->pStatObj->PhysicalizeFoliage(m_pPhysEnt, mtx, pSubObj->pFoliage, GetCVars()->e_FoliageBranchesTimeout, iSource); return pSubObj->pFoliage != 0; } else if (pSubObj->pFoliage) { pSubObj->pFoliage->Release(); return true; } return false; } IFoliage* CBrush::GetFoliage(int nSlot) { if (IStatObj::SSubObject* pSubObj = m_pStatObj->GetSubObject(nSlot)) return pSubObj->pFoliage; return 0; } ////////////////////////////////////////////////////////////////////////// void CBrush::UpdatePhysicalMaterials(int bThreadSafe) { if (!m_pPhysEnt) return; if ((GetRndFlags() & ERF_COLLISION_PROXY) && m_pPhysEnt) { pe_params_part ppart; ppart.flagsAND = 0; ppart.flagsOR = geom_colltype_player | geom_colltype_vehicle; m_pPhysEnt->SetParams(&ppart); } if ((GetRndFlags() & ERF_RAYCAST_PROXY) && m_pPhysEnt) { pe_params_part ppart; ppart.flagsAND = 0; ppart.flagsOR = geom_colltype_ray; m_pPhysEnt->SetParams(&ppart); } if (m_pMaterial) { // Assign custom material to physics. int surfaceTypesId[MAX_SUB_MATERIALS]; memset(surfaceTypesId, 0, sizeof(surfaceTypesId)); int i, numIds = m_pMaterial->FillSurfaceTypeIds(surfaceTypesId); ISurfaceTypeManager* pSurfaceTypeManager = Get3DEngine()->GetMaterialManager()->GetSurfaceTypeManager(); ISurfaceType* pMat; bool bBreakable = false; for (i = 0, m_bVehicleOnlyPhysics = false; i < numIds; i++) if (pMat = pSurfaceTypeManager->GetSurfaceType(surfaceTypesId[i])) { if (pMat->GetFlags() & SURFACE_TYPE_VEHICLE_ONLY_COLLISION) m_bVehicleOnlyPhysics = true; if (pMat->GetBreakability()) bBreakable = true; } if (bBreakable && m_pStatObj) { // mark the rendermesh as KepSysMesh so that it is kept in system memory if (m_pStatObj->GetRenderMesh()) m_pStatObj->GetRenderMesh()->KeepSysMesh(true); m_pStatObj->SetFlags(m_pStatObj->GetFlags() | STATIC_OBJECT_DYNAMIC); } pe_params_part ppart; ppart.nMats = numIds; ppart.pMatMapping = surfaceTypesId; if (m_bVehicleOnlyPhysics) ppart.flagsAND = geom_colltype_vehicle; if ((pMat = m_pMaterial->GetSurfaceType()) && pMat->GetPhyscalParams().collType >= 0) ppart.flagsAND = ~(geom_collides | geom_floats), ppart.flagsOR = pMat->GetPhyscalParams().collType; m_pPhysEnt->SetParams(&ppart, bThreadSafe); } else if (m_bVehicleOnlyPhysics) { m_bVehicleOnlyPhysics = false; if (!m_pStatObj->GetVehicleOnlyPhysics()) { pe_params_part ppart; ppart.flagsOR = geom_colltype_solid | geom_colltype_ray | geom_floats | geom_colltype_explosion; m_pPhysEnt->SetParams(&ppart, bThreadSafe); } } } void CBrush::Dephysicalize(bool bKeepIfReferenced) { AABB WSBBox = GetBBox(); // delete old physics if (m_pPhysEnt && 0 != GetSystem()->GetIPhysicalWorld()->DestroyPhysicalEntity(m_pPhysEnt, ((int)bKeepIfReferenced) * 4)) m_pPhysEnt = 0; if (!bKeepIfReferenced) { if (m_pDeform) { m_pDeform->CreateDeformableSubObject(false, GetMatrix(), NULL); } } } void CBrush::Dematerialize() { if (m_pMaterial) m_pMaterial = 0; UpdateExecuteAsPreProcessJobFlag(); } IPhysicalEntity* CBrush::GetPhysics() const { return m_pPhysEnt; } ////////////////////////////////////////////////////////////////////////// void CBrush::SetPhysics(IPhysicalEntity* pPhys) { m_pPhysEnt = pPhys; } ////////////////////////////////////////////////////////////////////////// bool CBrush::IsMatrixValid(const Matrix34& mat) { Vec3 vScaleTest = mat.TransformVector(Vec3(0, 0, 1)); float fDist = mat.GetTranslation().GetDistance(Vec3(0, 0, 0)); if (vScaleTest.GetLength() > 1000.f || vScaleTest.GetLength() < 0.01f || fDist > 256000 || !_finite(vScaleTest.x) || !_finite(vScaleTest.y) || !_finite(vScaleTest.z)) return false; return true; } ////////////////////////////////////////////////////////////////////////// void CBrush::SetMaterial(IMaterial* pMat) { m_pMaterial = pMat; bool bCollisionProxy = false; bool bRaycastProxy = false; if (pMat) { if (pMat->GetFlags() & MTL_FLAG_COLLISION_PROXY) bCollisionProxy = true; if (pMat->GetFlags() & MTL_FLAG_RAYCAST_PROXY) { bRaycastProxy = true; } } SetRndFlags(ERF_COLLISION_PROXY, bCollisionProxy); SetRndFlags(ERF_RAYCAST_PROXY, bRaycastProxy); UpdatePhysicalMaterials(); // register and get brush material id m_pMaterial = pMat; InvalidatePermanentRenderObject(); UpdateExecuteAsPreProcessJobFlag(); } void CBrush::UpdateExecuteAsPreProcessJobFlag() { IMaterial* pMat = GetMaterial(); m_bExecuteAsPreprocessJob = false; // check if this Brush needs to be executed as a preprocess job if (pMat) { SShaderItem& shaderItem = pMat->GetShaderItem(); if (shaderItem.m_pShader) { uint32 nFlags = shaderItem.m_pShader->GetFlags2(); m_bExecuteAsPreprocessJob = m_bExecuteAsPreprocessJob || ((nFlags & EF2_FORCE_WATERPASS) != 0); } // also check submaterials for (int i = 0, nNum = pMat->GetSubMtlCount(); i < nNum; ++i) { SShaderItem& subShaderItem = pMat->GetShaderItem(i); if (subShaderItem.m_pShader) { uint32 nFlags = subShaderItem.m_pShader->GetFlags2(); m_bExecuteAsPreprocessJob = m_bExecuteAsPreprocessJob || ((nFlags & EF2_FORCE_WATERPASS) != 0); } } #if defined(FEATURE_SVO_GI) if (pMat && (GetCVars()->e_svoTI_Active >= 0) && (gEnv->IsEditor() || GetCVars()->e_svoTI_Apply)) pMat->SetKeepLowResSysCopyForDiffTex(); #endif } } void CBrush::CheckPhysicalized() { if (!m_pPhysEnt) Physicalize(); } void CBrush::GetMemoryUsage(ICrySizer* pSizer) const { SIZER_COMPONENT_NAME(pSizer, "Brush"); pSizer->AddObject(this, sizeof(*this)); } void CBrush::SetEntityStatObj(unsigned int nSlot, IStatObj* pStatObj, const Matrix34A* pMatrix) { //assert(pStatObj); IStatObj* pPrevStatObj = m_pStatObj; m_pStatObj = (CStatObj*)pStatObj; if (pMatrix) SetMatrix(*pMatrix); // If object differ we must re-physicalize. if (pStatObj != pPrevStatObj) if (!pPrevStatObj || !pStatObj || (pStatObj->GetCloneSourceObject() != pPrevStatObj))// || //(pStatObj->GetFlags() & (STATIC_OBJECT_GENERATED|STATIC_OBJECT_CLONE))==STATIC_OBJECT_CLONE) Physicalize(); if (m_pTempData) Get3DEngine()->FreeRenderNodeTempData(&m_pTempData); assert(!m_pTempData); m_nInternalFlags |= UPDATE_DECALS; if (m_pStatObj && m_pStatObj->IsDeformable()) { if (!m_pDeform) m_pDeform = new CDeformableNode(m_nSID); m_pDeform->SetStatObj(static_cast<CStatObj*>(m_pStatObj.get())); m_pDeform->BakeDeform(GetMatrix()); } else { SAFE_DELETE(m_pDeform); } UpdateExecuteAsPreProcessJobFlag(); } void CBrush::SetStatObj(IStatObj* pStatObj) { m_pStatObj = pStatObj; if (m_pStatObj && m_pStatObj->IsDeformable()) { if (!m_pDeform) m_pDeform = new CDeformableNode(m_nSID); m_pDeform->SetStatObj(static_cast<CStatObj*>(m_pStatObj.get())); m_pDeform->BakeDeform(GetMatrix()); } else SAFE_DELETE(m_pDeform); UpdateExecuteAsPreProcessJobFlag(); InvalidatePermanentRenderObject(); } IRenderNode* CBrush::Clone() const { CBrush* pDestBrush = new CBrush(); //CBrush member vars // potential issues with Smart Pointers pDestBrush->m_Matrix = m_Matrix; pDestBrush->m_fMatrixScale = m_fMatrixScale; //pDestBrush->m_pPhysEnt //Don't want to copy the phys ent pointer pDestBrush->m_pMaterial = m_pMaterial; pDestBrush->m_pStatObj = m_pStatObj; pDestBrush->m_bVehicleOnlyPhysics = m_bVehicleOnlyPhysics; pDestBrush->m_bMerged = m_bMerged; pDestBrush->m_bDrawLast = m_bDrawLast; pDestBrush->m_WSBBox = m_WSBBox; //IRenderNode member vars // We cannot just copy over due to issues with the linked list of IRenderNode objects CopyIRenderNodeData(pDestBrush); pDestBrush->UpdateExecuteAsPreProcessJobFlag(); return pDestBrush; } IRenderMesh* CBrush::GetRenderMesh(int nLod) { IStatObj* pStatObj = m_pStatObj ? m_pStatObj->GetLodObject(nLod) : NULL; return pStatObj ? pStatObj->GetRenderMesh() : NULL; } void CBrush::OffsetPosition(const Vec3& delta) { if (m_pTempData) m_pTempData->OffsetPosition(delta); m_Matrix.SetTranslation(m_Matrix.GetTranslation() + delta); m_WSBBox.Move(delta); if (m_pPhysEnt) { pe_params_pos par_pos; par_pos.pos = m_Matrix.GetTranslation(); m_pPhysEnt->SetParams(&par_pos); } } bool CBrush::GetLodDistances(const SFrameLodInfo& frameLodInfo, float* distances) const { const float fEntityLodRatio = GetLodRatioNormalized(); if (fEntityLodRatio > 0.0f) { const float fDistMultiplier = 1.0f / (fEntityLodRatio * frameLodInfo.fTargetSize); const float lodDistance = m_pStatObj ? m_pStatObj->GetLodDistance() : FLT_MAX; for (uint i = 0; i < SMeshLodInfo::s_nMaxLodCount; ++i) { distances[i] = lodDistance * (i + 1) * fDistMultiplier; } } else { for (uint i = 0; i < SMeshLodInfo::s_nMaxLodCount; ++i) { distances[i] = FLT_MAX; } } return true; }
412
0.973244
1
0.973244
game-dev
MEDIA
0.416971
game-dev,graphics-rendering
0.994476
1
0.994476
jhs/build-couchdb
3,090
dependencies/icu4c-4_4/source/layout/loengine.cpp
/* * * (C) Copyright IBM Corp. 1998-2007 - All Rights Reserved * */ #include "LETypes.h" #include "loengine.h" #include "LayoutEngine.h" /** * \file * \brief C API for complex text layout. */ U_NAMESPACE_USE U_CAPI le_engine * U_EXPORT2 le_create(const le_font *font, le_int32 scriptCode, le_int32 languageCode, le_int32 typo_flags, LEErrorCode *success) { LEFontInstance *fontInstance = (LEFontInstance *) font; return (le_engine *) LayoutEngine::layoutEngineFactory(fontInstance, scriptCode, languageCode, typo_flags, *success); } U_CAPI void U_EXPORT2 le_close(le_engine *engine) { LayoutEngine *le = (LayoutEngine *) engine; delete le; } U_CAPI le_int32 U_EXPORT2 le_layoutChars(le_engine *engine, const LEUnicode chars[], le_int32 offset, le_int32 count, le_int32 max, le_bool rightToLeft, float x, float y, LEErrorCode *success) { LayoutEngine *le = (LayoutEngine *) engine; if (le == NULL) { *success = LE_ILLEGAL_ARGUMENT_ERROR; return -1; } return le->layoutChars(chars, offset, count, max, rightToLeft, x, y, *success); } U_CAPI le_int32 U_EXPORT2 le_getGlyphCount(le_engine *engine, LEErrorCode *success) { LayoutEngine *le = (LayoutEngine *) engine; if (le == NULL) { *success = LE_ILLEGAL_ARGUMENT_ERROR; return -1; } return le->getGlyphCount(); } U_CAPI void U_EXPORT2 le_getGlyphs(le_engine *engine, LEGlyphID glyphs[], LEErrorCode *success) { LayoutEngine *le = (LayoutEngine *) engine; if (le == NULL) { *success = LE_ILLEGAL_ARGUMENT_ERROR; return; } le->getGlyphs(glyphs, *success); } U_CAPI void U_EXPORT2 le_getCharIndices(le_engine *engine, le_int32 charIndices[], LEErrorCode *success) { LayoutEngine *le = (LayoutEngine *) engine; if (le == NULL) { *success = LE_ILLEGAL_ARGUMENT_ERROR; return; } le->getCharIndices(charIndices, *success); } U_CAPI void U_EXPORT2 le_getCharIndicesWithBase(le_engine *engine, le_int32 charIndices[], le_int32 indexBase, LEErrorCode *success) { LayoutEngine *le = (LayoutEngine *) engine; if (le == NULL) { *success = LE_ILLEGAL_ARGUMENT_ERROR; return; } le->getCharIndices(charIndices, indexBase, *success); } U_CAPI void U_EXPORT2 le_getGlyphPositions(le_engine *engine, float positions[], LEErrorCode *success) { LayoutEngine *le = (LayoutEngine *) engine; if (le == NULL) { *success = LE_ILLEGAL_ARGUMENT_ERROR; return; } le->getGlyphPositions(positions, *success); } U_CAPI void U_EXPORT2 le_getGlyphPosition(le_engine *engine, le_int32 glyphIndex, float *x, float *y, LEErrorCode *success) { LayoutEngine *le = (LayoutEngine *) engine; if (le == NULL) { *success = LE_ILLEGAL_ARGUMENT_ERROR; return; } le->getGlyphPosition(glyphIndex, *x, *y, *success); } U_CAPI void U_EXPORT2 le_reset(le_engine *engine, LEErrorCode *success) { LayoutEngine *le = (LayoutEngine *) engine; if (le == NULL) { *success = LE_ILLEGAL_ARGUMENT_ERROR; return; } le->reset(); }
412
0.863702
1
0.863702
game-dev
MEDIA
0.430512
game-dev
0.792392
1
0.792392
Breeze/breeze.sharp
4,945
Breeze.Sharp/StructuralType.cs
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using Breeze.Sharp.Core; using System.Diagnostics; namespace Breeze.Sharp { /// <summary> /// For internal use only. /// </summary> internal class StructuralTypeCollection : MapCollection<String, StructuralType> { protected override String GetKeyForItem(StructuralType item) { return item.ShortName + ":#" + item.Namespace; } } /// <summary> /// Base class for both <see cref="EntityType"/> and <see cref="ComplexType"/> classes. /// </summary> [DebuggerDisplay("{Name}")] public abstract class StructuralType { public StructuralType(MetadataStore metadataStore) { Warnings = new List<string>(); MetadataStore = metadataStore; } // TODO: will be needed later when we have complexType inheritance // public abstract StructuralType BaseStructuralType { get; } public MetadataStore MetadataStore { get; private set; } public String Name { get { return TypeNameInfo.ToStructuralTypeName(ShortName, Namespace); } internal set { var parts = TypeNameInfo.FromStructuralTypeName(value); ShortName = parts.ShortName; Namespace = parts.Namespace; _nameOnServer = parts.ToServer(MetadataStore).StructuralTypeName; } } public String NameOnServer { get { return _nameOnServer; } internal set { _nameOnServer = value; } } public Type ClrType { get { return _clrType; } internal set { _clrType = value; Name = TypeNameInfo.FromClrTypeName(_clrType.FullName).StructuralTypeName; } } internal abstract void UpdateFromJNode(JNode jNode, bool isFromServer); internal String GetPropertyNameFromJNode(JNode jn) { var dpName = jn.Get<String>("name"); if (dpName == null) { var dpNameOnServer = jn.Get<String>("nameOnServer"); dpName = MetadataStore.NamingConvention.ServerPropertyNameToClient(dpNameOnServer, this); } return dpName; } private Type _clrType; public String ShortName { get; private set; } public String Namespace { get; private set;} public dynamic Custom { get; set; } public bool IsAbstract { get; internal set; } // TODO: determine if this is still needed; public bool IsAnonymous { get; internal set; } public List<String> Warnings { get; internal set; } public abstract bool IsEntityType { get; } public virtual IEnumerable<StructuralProperty> Properties { get { return _dataProperties.Cast<StructuralProperty>(); } } public ICollection<DataProperty> DataProperties { get { return _dataProperties.ReadOnlyValues; } } public DataProperty GetDataProperty(String dpName) { return _dataProperties[dpName]; } public virtual StructuralProperty GetProperty(String propName) { return _dataProperties[propName]; } internal virtual DataProperty AddDataProperty(DataProperty dp) { dp.ParentType = this; _dataProperties.Add(dp); dp.UpdateClientServerNames(); return dp; } public ReadOnlyCollection<DataProperty> ComplexProperties { get { return _complexProperties.ReadOnlyValues; } } public ReadOnlyCollection<DataProperty> UnmappedProperties { get { return _unmappedProperties.ReadOnlyValues; } } public ICollection<Validator> Validators { get { return _validators; } } internal void UpdateComplexProperties(DataProperty dp) { UpdateCollection( _complexProperties, dp, dp.IsComplexProperty); } internal void UpdateUnmappedProperties(DataProperty dp) { UpdateCollection( _unmappedProperties, dp, dp.IsUnmapped); } internal String FormatDpName(String propertyName) { var typeLabel = this.IsEntityType ? "EntityType" : "ComplexType"; return String.Format("Data Property: '{0}' on the {1}: '{2}'", propertyName, typeLabel, this.Name); } internal String FormatNpName(String propertyName) { return String.Format("Navigation Property: '{0}' on the EntityType: '{1}'", propertyName, this.Name); } protected void UpdateCollection(SafeList<DataProperty> list, DataProperty dp, bool add) { var isSet = list.Contains(dp); if (add) { if (!isSet) { list.Add(dp); } } else { if (isSet) { list.Remove(dp); } } } private String _nameOnServer; internal readonly DataPropertyCollection _dataProperties = new DataPropertyCollection(); protected readonly SafeList<DataProperty> _complexProperties = new SafeList<DataProperty>(); protected readonly SafeList<DataProperty> _unmappedProperties = new SafeList<DataProperty>(); internal ValidatorCollection _validators = new ValidatorCollection(); } }
412
0.773392
1
0.773392
game-dev
MEDIA
0.271165
game-dev
0.729668
1
0.729668
ss14Starlight/space-station-14
2,183
Content.Client/Mech/MechSystem.cs
using Content.Shared.Mech; using Content.Shared.Mech.Components; using Content.Shared.Mech.EntitySystems; using Robust.Client.GameObjects; using DrawDepth = Content.Shared.DrawDepth.DrawDepth; namespace Content.Client.Mech; /// <inheritdoc/> public sealed class MechSystem : SharedMechSystem { [Dependency] private readonly SharedAppearanceSystem _appearance = default!; [Dependency] private readonly SpriteSystem _sprite = default!; /// <inheritdoc/> public override void Initialize() { base.Initialize(); SubscribeLocalEvent<MechComponent, AppearanceChangeEvent>(OnAppearanceChanged); } private void OnAppearanceChanged(EntityUid uid, MechComponent component, ref AppearanceChangeEvent args) { if (args.Sprite == null) return; if (!_sprite.LayerExists((uid, args.Sprite), MechVisualLayers.Base)) return; var state = component.BaseState; var drawDepth = DrawDepth.Mobs; if (component.BrokenState != null && _appearance.TryGetData<bool>(uid, MechVisuals.Broken, out var broken, args.Component) && broken) { state = component.BrokenState; drawDepth = DrawDepth.SmallMobs; } else if (component.OpenState != null && _appearance.TryGetData<bool>(uid, MechVisuals.Open, out var open, args.Component) && open) { state = component.OpenState; drawDepth = DrawDepth.SmallMobs; } if (args.Sprite.LayerMapTryGet(MechVisualLayers.Light, out var lightId) && args.Sprite.TryGetLayer(lightId, out var lightLayer) && _appearance.TryGetData<bool>(uid, MechVisuals.Light, out var light, args.Component)) lightLayer.Visible = light; if (args.Sprite.LayerMapTryGet(MechVisualLayers.Siren, out var sirenId) && args.Sprite.TryGetLayer(sirenId, out var sirenLayer) && _appearance.TryGetData<bool>(uid, MechVisuals.Siren, out var siren, args.Component)) sirenLayer.Visible = siren; _sprite.LayerSetRsiState((uid, args.Sprite), MechVisualLayers.Base, state); _sprite.SetDrawDepth((uid, args.Sprite), (int)drawDepth); } }
412
0.909094
1
0.909094
game-dev
MEDIA
0.937104
game-dev
0.947399
1
0.947399
MergHQ/CRYENGINE
5,367
Code/CryEngine/CryAction/GameVolumes/GameVolumesManager.cpp
// Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved. #include "StdAfx.h" #include "GameVolumesManager.h" //#pragma optimize("", off) //#pragma inline_depth(0) CGameVolumesManager::CGameVolumesManager() { } CGameVolumesManager::~CGameVolumesManager() { } IGameVolumesEdit* CGameVolumesManager::GetEditorInterface() { return gEnv->IsEditor() ? this : NULL; } bool CGameVolumesManager::GetVolumeInfoForEntity(EntityId entityId, IGameVolumes::VolumeInfo* pOutInfo) const { TEntityVolumes::const_iterator volumeIt = std::find(m_volumesData.begin(), m_volumesData.end(), entityId); if (volumeIt != m_volumesData.end() && !(*volumeIt).vertices.empty()) { const EntityVolume& entityVolume = *volumeIt; pOutInfo->volumeHeight = entityVolume.height; pOutInfo->closed = entityVolume.closed; pOutInfo->verticesCount = entityVolume.vertices.size(); pOutInfo->pVertices = &entityVolume.vertices[0]; return true; } return false; } void CGameVolumesManager::Load(const char* fileName) { ////////////////////////////////////////////////////////////////////////// /// Free any left data (it should be empty though...) Reset(); ////////////////////////////////////////////////////////////////////////// /// No need to load in editor /// The saved entities will restore the data inside the manager if (gEnv->IsEditor()) return; CCryFile file; if (false != file.Open(fileName, "rb")) { uint32 nFileVersion = GAME_VOLUMES_FILE_VERSION; file.ReadType(&nFileVersion); // Verify version... if ((nFileVersion >= 1) && (nFileVersion <= GAME_VOLUMES_FILE_VERSION)) { const uint32 maxVertices = 512; Vec3 readVertexBuffer[maxVertices]; // Read volumes uint32 nVolumeCount = 0; file.ReadType(&nVolumeCount); m_volumesData.resize(nVolumeCount); for (uint32 i = 0; i < nVolumeCount; ++i) { EntityVolume& volumeInfo = m_volumesData[i]; uint32 nVertexCount = 0; uint32 nEntityId = 0; f32 fHeight = 0; bool bClosed = false; file.ReadType(&nEntityId); file.ReadType(&fHeight); if (nFileVersion > 1) { file.ReadType(&bClosed); } file.ReadType(&nVertexCount); volumeInfo.entityId = (EntityId)nEntityId; volumeInfo.height = fHeight; volumeInfo.closed = bClosed; volumeInfo.vertices.resize(nVertexCount); if (nVertexCount > 0) { file.ReadType(&readVertexBuffer[0], nVertexCount); for (uint32 v = 0; v < nVertexCount; ++v) { volumeInfo.vertices[v] = readVertexBuffer[v]; } } } } else { GameWarning("GameVolumesManger:Load - Failed to load file '%s'. Version mis-match, try to re-export your level", fileName); } file.Close(); } } void CGameVolumesManager::Reset() { stl::free_container(m_volumesData); } void CGameVolumesManager::SetVolume(EntityId entityId, const IGameVolumes::VolumeInfo& volumeInfo) { bool inserted = false; TEntityVolumes::iterator volumeIt = std::find(m_volumesData.begin(), m_volumesData.end(), entityId); if (volumeIt == m_volumesData.end()) { m_volumesData.push_back(EntityVolume()); inserted = true; } EntityVolume& entityVolume = inserted ? m_volumesData.back() : *volumeIt; entityVolume.entityId = entityId; entityVolume.height = volumeInfo.volumeHeight; entityVolume.closed = volumeInfo.closed; entityVolume.vertices.resize(volumeInfo.verticesCount); for (uint32 i = 0; i < volumeInfo.verticesCount; ++i) { entityVolume.vertices[i] = volumeInfo.pVertices[i]; } } void CGameVolumesManager::DestroyVolume(EntityId entityId) { stl::find_and_erase(m_volumesData, entityId); } void CGameVolumesManager::RegisterEntityClass(const char* className) { IEntityClass* pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(className); if (pClass) { stl::push_back_unique(m_classes, pClass); } } size_t CGameVolumesManager::GetVolumeClassesCount() const { return m_classes.size(); } const char* CGameVolumesManager::GetVolumeClass(size_t index) const { if (index < m_classes.size()) { return m_classes[index]->GetName(); } return NULL; } void CGameVolumesManager::Export(const char* fileName) const { CCryFile file; if (false != file.Open(fileName, "wb")) { const uint32 maxVertices = 512; Vec3 writeVertexBuffer[maxVertices]; // File version uint32 nFileVersion = GAME_VOLUMES_FILE_VERSION; file.Write(&nFileVersion, sizeof(nFileVersion)); // Save volume info uint32 nVolumeCount = (uint32)m_volumesData.size(); file.Write(&nVolumeCount, sizeof(nVolumeCount)); for (uint32 i = 0; i < nVolumeCount; ++i) { const EntityVolume& volumeInfo = m_volumesData[i]; CRY_ASSERT(volumeInfo.vertices.size() < maxVertices); uint32 nVertexCount = min((uint32)volumeInfo.vertices.size(), maxVertices); uint32 nEntityId = volumeInfo.entityId; f32 fHeight = volumeInfo.height; bool bClosed = volumeInfo.closed; file.Write(&nEntityId, sizeof(nEntityId)); file.Write(&fHeight, sizeof(fHeight)); if (nFileVersion > 1) { file.Write(&bClosed, sizeof(bClosed)); } file.Write(&nVertexCount, sizeof(nVertexCount)); if (nVertexCount > 0) { for (uint32 v = 0; v < nVertexCount; ++v) { writeVertexBuffer[v] = volumeInfo.vertices[v]; } file.Write(&writeVertexBuffer[0], sizeof(writeVertexBuffer[0]) * nVertexCount); } } file.Close(); } }
412
0.947338
1
0.947338
game-dev
MEDIA
0.786536
game-dev
0.996931
1
0.996931
shxp3/CrossSine
1,309
src/main/java/net/ccbluex/liquidbounce/features/module/modules/movement/flights/rewinside/TeleportRewinsideFlight.kt
package net.ccbluex.liquidbounce.features.module.modules.movement.flights.rewinside import net.ccbluex.liquidbounce.event.UpdateEvent import net.ccbluex.liquidbounce.features.module.modules.movement.flights.FlightMode import net.minecraft.network.play.client.C03PacketPlayer.C04PacketPlayerPosition import net.minecraft.util.Vec3 import kotlin.math.cos import kotlin.math.sin class TeleportRewinsideFlight : FlightMode("TeleportRewinside") { override fun onUpdate(event: UpdateEvent) { val vectorStart = Vec3(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ) val yaw = -mc.thePlayer.rotationYaw val pitch = -mc.thePlayer.rotationPitch val length = 9.9 val vectorEnd = Vec3(sin(Math.toRadians(yaw.toDouble())) * cos(Math.toRadians(pitch.toDouble())) * length + vectorStart.xCoord, sin(Math.toRadians(pitch.toDouble())) * length + vectorStart.yCoord, cos(Math.toRadians(yaw.toDouble())) * cos(Math.toRadians(pitch.toDouble())) * length + vectorStart.zCoord) mc.netHandler.addToSendQueue(C04PacketPlayerPosition(vectorEnd.xCoord, mc.thePlayer.posY + 2, vectorEnd.zCoord, true)) mc.netHandler.addToSendQueue(C04PacketPlayerPosition(vectorStart.xCoord, mc.thePlayer.posY + 2, vectorStart.zCoord, true)) mc.thePlayer.motionY = 0.0 } }
412
0.52607
1
0.52607
game-dev
MEDIA
0.750748
game-dev
0.914331
1
0.914331
Dimbreath/AzurLaneData
1,150
ja-JP/view/activity/towerclimbinggame/towerclimbingcollectionmediator.lua
slot0 = class("TowerClimbingCollectionMediator", import("...base.ContextMediator")) slot0.ON_GET = "TowerClimbingCollectionMediator:ON_GET" function slot0.register(slot0) slot0:bind(uv0.ON_GET, function (slot0, slot1) uv0:sendNotification(GAME.SEND_MINI_GAME_OP, { hubid = 9, cmd = MiniGameOPCommand.CMD_SPECIAL_GAME, args1 = { MiniGameDataCreator.TowerClimbingGameID, 2, slot1 } }) end) slot0.viewComponent:SetData(getProxy(MiniGameProxy):GetMiniGameData(MiniGameDataCreator.TowerClimbingGameID):clone()) end function slot0.listNotificationInterests(slot0) return { GAME.SEND_MINI_GAME_OP_DONE } end function slot0.handleNotification(slot0, slot1) slot3 = slot1:getBody() if slot1:getName() == GAME.SEND_MINI_GAME_OP_DONE and slot3.hubid == 9 and slot3.cmd == MiniGameOPCommand.CMD_SPECIAL_GAME and slot3.argList[1] == MiniGameDataCreator.TowerClimbingGameID and slot3.argList[2] == 2 then slot0.viewComponent:SetData(getProxy(MiniGameProxy):GetMiniGameData(MiniGameDataCreator.TowerClimbingGameID)) slot0.viewComponent:OpenBook(slot3.argList[3]) slot0.viewComponent:UpdateTip() end end return slot0
412
0.604088
1
0.604088
game-dev
MEDIA
0.927785
game-dev
0.718154
1
0.718154
unresolved3169/Altay-Old
1,830
src/pocketmine/level/generator/populator/Pond.php
<?php /* * * ____ _ _ __ __ _ __ __ ____ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * @author PocketMine Team * @link http://www.pocketmine.net/ * * */ declare(strict_types=1); namespace pocketmine\level\generator\populator; use pocketmine\block\Block; use pocketmine\block\BlockFactory; use pocketmine\level\ChunkManager; use pocketmine\math\Vector3; use pocketmine\utils\Random; class Pond extends Populator{ private $waterOdd = 4; private $lavaOdd = 4; private $lavaSurfaceOdd = 4; public function populate(ChunkManager $level, int $chunkX, int $chunkZ, Random $random){ if($random->nextRange(0, $this->waterOdd) === 0){ $x = $random->nextRange($chunkX << 4, ($chunkX << 4) + 16); $y = $random->nextBoundedInt(128); $z = $random->nextRange($chunkZ << 4, ($chunkZ << 4) + 16); $pond = new \pocketmine\level\generator\object\Pond($random, BlockFactory::get(Block::WATER)); if($pond->canPlaceObject($level, $v = new Vector3($x, $y, $z))){ $pond->placeObject($level, $v); } } } public function setWaterOdd(int $waterOdd){ $this->waterOdd = $waterOdd; } public function setLavaOdd(int $lavaOdd){ $this->lavaOdd = $lavaOdd; } public function setLavaSurfaceOdd(int $lavaSurfaceOdd){ $this->lavaSurfaceOdd = $lavaSurfaceOdd; } }
412
0.811825
1
0.811825
game-dev
MEDIA
0.985739
game-dev
0.962784
1
0.962784
bmwcarit/ramses
1,978
src/framework/internal/Components/IResourceProviderComponent.h
// ------------------------------------------------------------------------- // Copyright (C) 2015 BMW Car IT GmbH // ------------------------------------------------------------------------- // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. // ------------------------------------------------------------------------- #pragma once #include "internal/Components/ResourceHashUsage.h" #include "internal/Components/InputStreamContainer.h" #include "internal/Components/SceneFileHandle.h" #include "ManagedResource.h" #include "internal/SceneGraph/Resource/ResourceInfo.h" namespace ramses::internal { class Guid; class ResourceTableOfContents; class IResourceProviderComponent { public: virtual ~IResourceProviderComponent() = default; virtual ManagedResource manageResource(const IResource& resource) = 0; virtual ManagedResource getResource(ResourceContentHash hash) = 0; virtual ManagedResource loadResource(const ResourceContentHash& hash) = 0; virtual ResourceHashUsage getResourceHashUsage(const ResourceContentHash& hash) = 0; virtual SceneFileHandle addResourceFile(InputStreamContainerSPtr resourceFileInputStream, const ResourceTableOfContents& toc) = 0; virtual void loadResourceFromFile(SceneFileHandle handle) = 0; virtual void removeResourceFile(SceneFileHandle handle) = 0; [[nodiscard]] virtual bool hasResourceFile(SceneFileHandle handle) const = 0; virtual void reserveResourceCount(uint32_t totalCount) = 0; virtual ManagedResourceVector resolveResources(ResourceContentHashVector& vec) = 0; virtual ResourceInfo const& getResourceInfo(ResourceContentHash const& hash) = 0; [[nodiscard]] virtual bool knowsResource(const ResourceContentHash& hash) const = 0; }; }
412
0.829067
1
0.829067
game-dev
MEDIA
0.483561
game-dev,graphics-rendering
0.793677
1
0.793677
HaydnTrigg/Liberty
1,936
Code/Common/Include/Damage.hpp
#pragma once #include "Enums.hpp" #include <FLHookCore.h> namespace Archetype { struct Explosion; } struct DamageEntry { enum class SubObjFate { Alive = 0, Destroyed = 1, Debris = 2, Disappear = 3, Loot = 4 }; COMMON_DEC DamageEntry(); COMMON_DEC DamageEntry& operator=(const DamageEntry&); COMMON_DEC bool operator==(const DamageEntry&) const; COMMON_DEC bool operator!=(const DamageEntry&) const; COMMON_DEC bool operator<(const DamageEntry&) const; COMMON_DEC bool operator>(const DamageEntry&) const; COMMON_DEC static const char* FateToString(SubObjFate); public: ushort subObj; float health; SubObjFate fate; }; struct ExplosionDamageEvent { uint victimId; uint attackerId; DamageCause dmgCause; FLHookCore::Vector explosionPosition; Archetype::Explosion* explosionArchetype; }; struct DamageList { COMMON_DEC DamageList(const DamageList&); COMMON_DEC DamageList(); COMMON_DEC ~DamageList(); COMMON_DEC DamageList& operator=(const DamageList&); COMMON_DEC static const char* DmgCauseToString(DamageCause); COMMON_DEC void add_damage_entry(unsigned short, float, DamageEntry::SubObjFate); COMMON_DEC DamageCause get_cause() const; COMMON_DEC float get_hit_pts_left(unsigned short) const; COMMON_DEC unsigned int get_inflictor_id() const; COMMON_DEC unsigned int get_inflictor_owner_player() const; COMMON_DEC bool is_destroyed() const; COMMON_DEC bool is_inflictor_a_player() const; COMMON_DEC void set_cause(DamageCause); COMMON_DEC void set_destroyed(bool); COMMON_DEC void set_inflictor_id(unsigned int); COMMON_DEC void set_inflictor_owner_player(unsigned int); public: st6::list<DamageEntry> damageEntries; bool isDestroyed; DamageCause damageCause; uint inflictorId; uint inflictorPlayerId; bool dunno; };
412
0.832587
1
0.832587
game-dev
MEDIA
0.697685
game-dev
0.544394
1
0.544394
hadashiA/VContainer
2,873
tests/VContainer.Benchmark/Library/PackageCache/com.svermeulen.extenject@9.2.0-stcf3/Source/Binding/Finalizers/ScopableBindingFinalizer.cs
using System; using System.Collections.Generic; using ModestTree; namespace Zenject { [NoReflectionBaking] public class ScopableBindingFinalizer : ProviderBindingFinalizer { readonly Func<DiContainer, Type, IProvider> _providerFactory; public ScopableBindingFinalizer( BindInfo bindInfo, Func<DiContainer, Type, IProvider> providerFactory) : base(bindInfo) { _providerFactory = providerFactory; } protected override void OnFinalizeBinding(DiContainer container) { if (BindInfo.ToChoice == ToChoices.Self) { Assert.IsEmpty(BindInfo.ToTypes); FinalizeBindingSelf(container); } else { FinalizeBindingConcrete(container, BindInfo.ToTypes); } } void FinalizeBindingConcrete(DiContainer container, List<Type> concreteTypes) { if (concreteTypes.Count == 0) { // This can be common when using convention based bindings return; } var scope = GetScope(); switch (scope) { case ScopeTypes.Transient: { RegisterProvidersForAllContractsPerConcreteType( container, concreteTypes, _providerFactory); break; } case ScopeTypes.Singleton: { RegisterProvidersForAllContractsPerConcreteType( container, concreteTypes, (_, concreteType) => BindingUtil.CreateCachedProvider( _providerFactory(container, concreteType))); break; } default: { throw Assert.CreateException(); } } } void FinalizeBindingSelf(DiContainer container) { var scope = GetScope(); switch (scope) { case ScopeTypes.Transient: { RegisterProviderPerContract(container, _providerFactory); break; } case ScopeTypes.Singleton: { RegisterProviderPerContract( container, (_, contractType) => BindingUtil.CreateCachedProvider( _providerFactory(container, contractType))); break; } default: { throw Assert.CreateException(); } } } } }
412
0.896119
1
0.896119
game-dev
MEDIA
0.245215
game-dev
0.940742
1
0.940742
Fulafu-ai/Godot4-Fake3D-Card-Game-UI-Demo
2,210
Demo 0.1/script/card_states/dragging.gd
extends CardState const DRAGGING_BUFFER_TIME = 0.2 var min_drag_time_elapsed := false func _on_buffer(): min_drag_time_elapsed = true func enter() -> void: if not card_UI: return Event.cards_dragging.append(card_UI) card_UI.selected = false card_UI.pivot_offset.y = card_UI.size.y * 0.65 #强制打断当前动画(即使interuptable = false) if card_UI.tween_rot and card_UI.tween_rot.is_running(): card_UI.tween_rot.kill() card_UI.to_rot(0.0, 180.0 * card_UI.flip_type) card_UI.to_rot_z(0.0, 0.5) if card_UI.tween_scale and card_UI.tween_scale.is_running(): card_UI.tween_scale.kill() card_UI.to_scale(Vector2(1.2, 1.2), 0.5) card_UI.call_deferred("move_to_front") card_UI.z_index = card_UI.target_UI_z_index + 2 min_drag_time_elapsed = false var buffer_timer = get_tree().create_timer(DRAGGING_BUFFER_TIME, false) buffer_timer.timeout.connect(_on_buffer) #reparent var main = get_tree().get_first_node_in_group("main") var dragging_cards = main.find_child("TableCards").find_child("DraggingCards") card_UI.reparent_requested.emit(dragging_cards) card_UI.to_pos(-card_UI.pivot_offset, 0.1, 0, false, false) func exit() -> void: Event.cards_dragging.erase(card_UI) card_UI.z_index = card_UI.target_UI_z_index min_drag_time_elapsed = false func physics_update(_delta: float) -> void: #card_UI.follow_mouse(_delta) pass func on_gui_input(event: InputEvent) -> void: #dragging卡牌本身不处理输入事件,只给出实现方案,交由card_event.gd调用 pass func on_mouse_entered() -> void: pass func on_mouse_exited() -> void: pass func left_click(event: InputEvent) -> void: if not min_drag_time_elapsed: return var follow_table = card_UI.follow_target.get_parent() if card_UI.follow_target else null if event.is_released(): #处理松开左键后进入follow状态的事件 if card_UI.card_table_overlapping(): if (not card_UI.card_table_overlapping().is_full) or (card_UI.card_table_overlapping() == follow_table): card_UI.follow_requested.emit(card_UI.card_table_overlapping().cards) return if card_UI.destroy_area_overlapping(): card_UI.destroy_requested.emit() return if follow_table: transition_requested.emit(self) follow_table.update_card_UIs() return transition_requested.emit(self)
412
0.600786
1
0.600786
game-dev
MEDIA
0.40508
game-dev,desktop-app
0.857312
1
0.857312
ProjectIgnis/CardScripts
2,836
unofficial/c511009616.lua
--Helixx Gothiclone --fixed by MLD local s,id=GetID() function s.initial_effect(c) --link summon Link.AddProcedure(c,aux.FilterBoolFunction(Card.IsSetCard,0x573),2,2) c:EnableReviveLimit() --atk local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(31919988,0)) e1:SetCategory(CATEGORY_ATKCHANGE) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e1:SetCode(EVENT_BATTLE_CONFIRM) e1:SetCondition(s.atkcon) e1:SetOperation(s.atkop) c:RegisterEffect(e1) --destroy replace local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_SINGLE) e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e2:SetCode(EFFECT_DESTROY_REPLACE) e2:SetRange(LOCATION_MZONE) e2:SetCountLimit(1) e2:SetTarget(s.reptg) c:RegisterEffect(e2) --damage local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(114932,0)) e3:SetCategory(CATEGORY_DAMAGE) e3:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e3:SetCode(EVENT_BATTLED) e3:SetCondition(s.damcon) e3:SetCost(s.damcost) e3:SetTarget(s.damtg) e3:SetOperation(s.damop) c:RegisterEffect(e3) end s.listed_series={0x573} function s.atkcon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local bc=c:GetBattleTarget() return c:IsRelateToBattle() and bc and bc:IsFaceup() and bc:IsRelateToBattle() and bc:IsControler(1-tp) end function s.atkop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local bc=c:GetBattleTarget() if c:IsFaceup() and c:IsRelateToBattle() and bc and bc:IsFaceup() and bc:IsRelateToBattle() then local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_SET_ATTACK_FINAL) e1:SetValue(bc:GetAttack()) e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END) c:RegisterEffect(e1) end end function s.reptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsReason(REASON_BATTLE) end e:GetHandler():RegisterFlagEffect(id,RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_DAMAGE,0,1) return true end function s.cfilter(c,g) return g:IsContains(c) end function s.damcon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():GetFlagEffect(id)~=0 end function s.damcost(e,tp,eg,ep,ev,re,r,rp,chk) local lg=e:GetHandler():GetLinkedGroup() if chk==0 then return Duel.CheckReleaseGroupCost(tp,s.cfilter,1,false,nil,nil,lg) end local g=Duel.SelectReleaseGroupCost(tp,s.cfilter,1,1,false,nil,nil,lg) local atk=g:GetFirst():GetAttack() Duel.Release(g,REASON_COST) e:SetLabel(atk) end function s.damtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetTargetPlayer(1-tp) Duel.SetTargetParam(e:GetLabel()) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,e:GetLabel()) end function s.damop(e,tp,eg,ep,ev,re,r,rp) local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) Duel.Damage(p,d,REASON_EFFECT) end
412
0.886227
1
0.886227
game-dev
MEDIA
0.982575
game-dev
0.962338
1
0.962338
huderlem/porymap
31,953
src/core/tileset.cpp
#include "tileset.h" #include "metatile.h" #include "project.h" #include "log.h" #include "config.h" #include "imageproviders.h" #include "validator.h" #include <QPainter> #include <QImage> #include <algorithm> Tileset::Tileset(const Tileset &other) : name(other.name), is_secondary(other.is_secondary), tiles_label(other.tiles_label), palettes_label(other.palettes_label), metatiles_label(other.metatiles_label), metatiles_path(other.metatiles_path), metatile_attrs_label(other.metatile_attrs_label), metatile_attrs_path(other.metatile_attrs_path), tilesImagePath(other.tilesImagePath), palettePaths(other.palettePaths), metatileLabels(other.metatileLabels), palettes(other.palettes), palettePreviews(other.palettePreviews), m_tilesImage(other.m_tilesImage.copy()), m_hasUnsavedTilesImage(other.m_hasUnsavedTilesImage) { for (auto tile : other.m_tiles) { m_tiles.append(tile.copy()); } for (auto *metatile : other.m_metatiles) { m_metatiles.append(new Metatile(*metatile)); } } Tileset &Tileset::operator=(const Tileset &other) { name = other.name; is_secondary = other.is_secondary; tiles_label = other.tiles_label; palettes_label = other.palettes_label; metatiles_label = other.metatiles_label; metatiles_path = other.metatiles_path; metatile_attrs_label = other.metatile_attrs_label; metatile_attrs_path = other.metatile_attrs_path; tilesImagePath = other.tilesImagePath; m_tilesImage = other.m_tilesImage.copy(); palettePaths = other.palettePaths; metatileLabels = other.metatileLabels; palettes = other.palettes; palettePreviews = other.palettePreviews; m_tiles.clear(); for (auto tile : other.m_tiles) { m_tiles.append(tile.copy()); } clearMetatiles(); for (auto *metatile : other.m_metatiles) { m_metatiles.append(new Metatile(*metatile)); } return *this; } Tileset::~Tileset() { clearMetatiles(); } void Tileset::clearMetatiles() { qDeleteAll(m_metatiles); m_metatiles.clear(); } void Tileset::setMetatiles(const QList<Metatile*> &metatiles) { clearMetatiles(); m_metatiles = metatiles; } void Tileset::addMetatile(Metatile* metatile) { m_metatiles.append(metatile); } void Tileset::resizeMetatiles(int newNumMetatiles) { if (newNumMetatiles < 0) newNumMetatiles = 0; while (m_metatiles.length() > newNumMetatiles) { delete m_metatiles.takeLast(); } const int numTiles = projectConfig.getNumTilesInMetatile(); while (m_metatiles.length() < newNumMetatiles) { m_metatiles.append(new Metatile(numTiles)); } } uint16_t Tileset::firstMetatileId() const { return this->is_secondary ? Project::getNumMetatilesPrimary() : 0; } uint16_t Tileset::lastMetatileId() const { return qMax(1, firstMetatileId() + m_metatiles.length()) - 1; } int Tileset::maxMetatiles() const { return this->is_secondary ? Project::getNumMetatilesSecondary() : Project::getNumMetatilesPrimary(); } uint16_t Tileset::firstTileId() const { return this->is_secondary ? Project::getNumTilesPrimary() : 0; } uint16_t Tileset::lastTileId() const { return qMax(1, firstMetatileId() + m_tiles.length()) - 1; } int Tileset::maxTiles() const { return this->is_secondary ? Project::getNumTilesSecondary() : Project::getNumTilesPrimary(); } Tileset* Tileset::getPaletteTileset(int paletteId, Tileset *primaryTileset, Tileset *secondaryTileset) { return const_cast<Tileset*>(getPaletteTileset(paletteId, static_cast<const Tileset*>(primaryTileset), static_cast<const Tileset*>(secondaryTileset))); } const Tileset* Tileset::getPaletteTileset(int paletteId, const Tileset *primaryTileset, const Tileset *secondaryTileset) { if (paletteId < Project::getNumPalettesPrimary()) { return primaryTileset; } else if (paletteId < Project::getNumPalettesTotal()) { return secondaryTileset; } else { return nullptr; } } Tileset* Tileset::getTileTileset(int tileId, Tileset *primaryTileset, Tileset *secondaryTileset) { return const_cast<Tileset*>(getTileTileset(tileId, static_cast<const Tileset*>(primaryTileset), static_cast<const Tileset*>(secondaryTileset))); } // Get the tileset *expected* to contain the given 'tileId'. Note that this does not mean the tile actually exists in that tileset. const Tileset* Tileset::getTileTileset(int tileId, const Tileset *primaryTileset, const Tileset *secondaryTileset) { if (tileId < Project::getNumTilesPrimary()) { return primaryTileset; } else if (tileId < Project::getNumTilesTotal()) { return secondaryTileset; } else { return nullptr; } } Tileset* Tileset::getMetatileTileset(int metatileId, Tileset *primaryTileset, Tileset *secondaryTileset) { return const_cast<Tileset*>(getMetatileTileset(metatileId, static_cast<const Tileset*>(primaryTileset), static_cast<const Tileset*>(secondaryTileset))); } // Get the tileset *expected* to contain the given 'metatileId'. Note that this does not mean the metatile actually exists in that tileset. const Tileset* Tileset::getMetatileTileset(int metatileId, const Tileset *primaryTileset, const Tileset *secondaryTileset) { if (metatileId < Project::getNumMetatilesPrimary()) { return primaryTileset; } else if (metatileId < Project::getNumMetatilesTotal()) { return secondaryTileset; } else { return nullptr; } } Metatile* Tileset::getMetatile(int metatileId, Tileset *primaryTileset, Tileset *secondaryTileset) { return const_cast<Metatile*>(getMetatile(metatileId, static_cast<const Tileset*>(primaryTileset), static_cast<const Tileset*>(secondaryTileset))); } const Metatile* Tileset::getMetatile(int metatileId, const Tileset *primaryTileset, const Tileset *secondaryTileset) { const Tileset *tileset = Tileset::getMetatileTileset(metatileId, primaryTileset, secondaryTileset); if (!tileset) { return nullptr; } int index = Metatile::getIndexInTileset(metatileId); return tileset->m_metatiles.value(index, nullptr); } // Metatile labels are stored per-tileset. When looking for a metatile label, first search in the tileset // that the metatile belongs to. If one isn't found, search in the other tileset. Labels coming from the // tileset that the metatile does not belong to are shared and cannot be edited via Porymap. Tileset* Tileset::getMetatileLabelTileset(int metatileId, Tileset *primaryTileset, Tileset *secondaryTileset) { Tileset *mainTileset = nullptr; Tileset *alternateTileset = nullptr; if (metatileId < Project::getNumMetatilesPrimary()) { mainTileset = primaryTileset; alternateTileset = secondaryTileset; } else if (metatileId < Project::getNumMetatilesTotal()) { mainTileset = secondaryTileset; alternateTileset = primaryTileset; } if (mainTileset && !mainTileset->metatileLabels.value(metatileId).isEmpty()) { return mainTileset; } else if (alternateTileset && !alternateTileset->metatileLabels.value(metatileId).isEmpty()) { return alternateTileset; } return nullptr; } // Return the pair of possible metatile labels for the specified metatile. // "owned" is the label for the tileset to which the metatile belongs. // "shared" is the label for the tileset to which the metatile does not belong. MetatileLabelPair Tileset::getMetatileLabelPair(int metatileId, Tileset *primaryTileset, Tileset *secondaryTileset) { MetatileLabelPair labels; QString primaryMetatileLabel = primaryTileset ? primaryTileset->metatileLabels.value(metatileId) : ""; QString secondaryMetatileLabel = secondaryTileset ? secondaryTileset->metatileLabels.value(metatileId) : ""; if (metatileId < Project::getNumMetatilesPrimary()) { labels.owned = primaryMetatileLabel; labels.shared = secondaryMetatileLabel; } else if (metatileId < Project::getNumMetatilesTotal()) { labels.owned = secondaryMetatileLabel; labels.shared = primaryMetatileLabel; } return labels; } // If the metatile has a label in the tileset it belongs to, return that label. // If it doesn't, and the metatile has a label in the other tileset, return that label. // Otherwise return an empty string. QString Tileset::getMetatileLabel(int metatileId, Tileset *primaryTileset, Tileset *secondaryTileset) { MetatileLabelPair labels = Tileset::getMetatileLabelPair(metatileId, primaryTileset, secondaryTileset); return !labels.owned.isEmpty() ? labels.owned : labels.shared; } // Just get the "owned" metatile label, i.e. the one for the tileset that the metatile belongs to. QString Tileset::getOwnedMetatileLabel(int metatileId, Tileset *primaryTileset, Tileset *secondaryTileset) { MetatileLabelPair labels = Tileset::getMetatileLabelPair(metatileId, primaryTileset, secondaryTileset); return labels.owned; } bool Tileset::setMetatileLabel(int metatileId, QString label, Tileset *primaryTileset, Tileset *secondaryTileset) { Tileset *tileset = Tileset::getMetatileTileset(metatileId, primaryTileset, secondaryTileset); if (!tileset) return false; if (!label.isEmpty()) { IdentifierValidator validator; if (!validator.isValid(label)) return false; } tileset->metatileLabels[metatileId] = label; return true; } QString Tileset::getMetatileLabelPrefix() { return Tileset::getMetatileLabelPrefix(this->name); } QString Tileset::getMetatileLabelPrefix(const QString &name) { // Default is "gTileset_Name" --> "METATILE_Name_" const QString labelPrefix = projectConfig.getIdentifier(ProjectIdentifier::define_metatile_label_prefix); return QString("%1%2_").arg(labelPrefix).arg(Tileset::stripPrefix(name)); } bool Tileset::metatileIsValid(uint16_t metatileId, const Tileset *primaryTileset, const Tileset *secondaryTileset) { return (primaryTileset && primaryTileset->containsMetatileId(metatileId)) || (secondaryTileset && secondaryTileset->containsMetatileId(metatileId)); } QList<QList<QRgb>> Tileset::getBlockPalettes(const Tileset *primaryTileset, const Tileset *secondaryTileset, bool useTruePalettes) { QList<QList<QRgb>> palettes; QList<QList<QRgb>> primaryPalettes; if (primaryTileset) { primaryPalettes = useTruePalettes ? primaryTileset->palettes : primaryTileset->palettePreviews; } for (int i = 0; i < Project::getNumPalettesPrimary(); i++) { palettes.append(primaryPalettes.value(i)); } QList<QList<QRgb>> secondaryPalettes; if (secondaryTileset) { secondaryPalettes = useTruePalettes ? secondaryTileset->palettes : secondaryTileset->palettePreviews; } for (int i = Project::getNumPalettesPrimary(); i < Project::getNumPalettesTotal(); i++) { palettes.append(secondaryPalettes.value(i)); } return palettes; } QList<QRgb> Tileset::getPalette(int paletteId, const Tileset *primaryTileset, const Tileset *secondaryTileset, bool useTruePalettes) { QList<QRgb> paletteTable; const Tileset *tileset = paletteId < Project::getNumPalettesPrimary() ? primaryTileset : secondaryTileset; if (!tileset) { return paletteTable; } auto palettes = useTruePalettes ? tileset->palettes : tileset->palettePreviews; if (paletteId < 0 || paletteId >= palettes.length()) { return paletteTable; } for (int i = 0; i < palettes.at(paletteId).length(); i++) { paletteTable.append(palettes.at(paletteId).at(i)); } return paletteTable; } bool Tileset::appendToHeaders(const QString &filepath, const QString &friendlyName, bool usingAsm) { QFile file(filepath); if (!file.open(QIODevice::WriteOnly | QIODevice::Append)) { logError(QString("Could not write to file \"%1\"").arg(filepath)); return false; } QString isSecondaryStr = this->is_secondary ? "TRUE" : "FALSE"; QString dataString = "\n"; if (usingAsm) { // Append to asm file dataString.append("\t.align 2\n"); dataString.append(QString("%1::\n").arg(this->name)); dataString.append("\t.byte TRUE @ is compressed\n"); dataString.append(QString("\t.byte %1 @ is secondary\n").arg(isSecondaryStr)); dataString.append("\t.2byte 0 @ padding\n"); dataString.append(QString("\t.4byte gTilesetTiles_%1\n").arg(friendlyName)); dataString.append(QString("\t.4byte gTilesetPalettes_%1\n").arg(friendlyName)); dataString.append(QString("\t.4byte gMetatiles_%1\n").arg(friendlyName)); if (projectConfig.baseGameVersion == BaseGameVersion::pokefirered) { dataString.append("\t.4byte NULL @ animation callback\n"); dataString.append(QString("\t.4byte gMetatileAttributes_%1\n").arg(friendlyName)); } else { dataString.append(QString("\t.4byte gMetatileAttributes_%1\n").arg(friendlyName)); dataString.append("\t.4byte NULL @ animation callback\n"); } } else { // Append to C file dataString.append(QString("const struct Tileset %1 =\n{\n").arg(this->name)); if (projectConfig.tilesetsHaveIsCompressed) dataString.append(" .isCompressed = TRUE,\n"); dataString.append(QString(" .isSecondary = %1,\n").arg(isSecondaryStr)); dataString.append(QString(" .tiles = gTilesetTiles_%1,\n").arg(friendlyName)); dataString.append(QString(" .palettes = gTilesetPalettes_%1,\n").arg(friendlyName)); dataString.append(QString(" .metatiles = gMetatiles_%1,\n").arg(friendlyName)); dataString.append(QString(" .metatileAttributes = gMetatileAttributes_%1,\n").arg(friendlyName)); if (projectConfig.tilesetsHaveCallback) dataString.append(" .callback = NULL,\n"); dataString.append("};\n"); } file.write(dataString.toUtf8()); file.flush(); file.close(); return true; } bool Tileset::appendToGraphics(const QString &filepath, const QString &friendlyName, bool usingAsm) { QFile file(filepath); if (!file.open(QIODevice::WriteOnly | QIODevice::Append)) { logError(QString("Could not write to file \"%1\"").arg(filepath)); return false; } const QString tilesetDir = this->getExpectedDir(); const QString tilesPath = QString("%1/tiles%2").arg(tilesetDir).arg(projectConfig.getIdentifier(ProjectIdentifier::tiles_output_extension)); const QString palettesPath = tilesetDir + "/palettes/"; const QString palettesExt = projectConfig.getIdentifier(ProjectIdentifier::pals_output_extension); QString dataString = "\n"; if (usingAsm) { // Append to asm file dataString.append("\t.align 2\n"); dataString.append(QString("gTilesetPalettes_%1::\n").arg(friendlyName)); for (int i = 0; i < Project::getNumPalettesTotal(); i++) dataString.append(QString("\t.incbin \"%1%2%3\"\n").arg(palettesPath).arg(i, 2, 10, QLatin1Char('0')).arg(palettesExt)); dataString.append("\n\t.align 2\n"); dataString.append(QString("gTilesetTiles_%1::\n").arg(friendlyName)); dataString.append(QString("\t.incbin \"%1\"\n").arg(tilesPath)); } else { // Append to C file dataString.append(QString("const u16 gTilesetPalettes_%1[][%2] =\n{\n").arg(friendlyName).arg(Tileset::numColorsPerPalette())); for (int i = 0; i < Project::getNumPalettesTotal(); i++) dataString.append(QString(" INCBIN_U16(\"%1%2%3\"),\n").arg(palettesPath).arg(i, 2, 10, QLatin1Char('0')).arg(palettesExt)); dataString.append("};\n"); dataString.append(QString("\nconst u32 gTilesetTiles_%1[] = INCBIN_U32(\"%2\");\n").arg(friendlyName, tilesPath)); } file.write(dataString.toUtf8()); file.flush(); file.close(); return true; } bool Tileset::appendToMetatiles(const QString &filepath, const QString &friendlyName, bool usingAsm) { QFile file(filepath); if (!file.open(QIODevice::WriteOnly | QIODevice::Append)) { logError(QString("Could not write to file \"%1\"").arg(filepath)); return false; } const QString tilesetDir = this->getExpectedDir(); const QString metatilesPath = tilesetDir + "/metatiles.bin"; const QString metatileAttrsPath = tilesetDir + "/metatile_attributes.bin"; QString dataString = "\n"; if (usingAsm) { // Append to asm file dataString.append("\t.align 1\n"); dataString.append(QString("gMetatiles_%1::\n").arg(friendlyName)); dataString.append(QString("\t.incbin \"%1\"\n").arg(metatilesPath)); dataString.append(QString("\n\t.align 1\n")); dataString.append(QString("gMetatileAttributes_%1::\n").arg(friendlyName)); dataString.append(QString("\t.incbin \"%1\"\n").arg(metatileAttrsPath)); } else { // Append to C file dataString.append(QString("const u16 gMetatiles_%1[] = INCBIN_U16(\"%2\");\n").arg(friendlyName, metatilesPath)); QString numBits = QString::number(projectConfig.metatileAttributesSize * 8); dataString.append(QString("const u%1 gMetatileAttributes_%2[] = INCBIN_U%1(\"%3\");\n").arg(numBits, friendlyName, metatileAttrsPath)); } file.write(dataString.toUtf8()); file.flush(); file.close(); return true; } // The path where Porymap expects a Tileset's graphics assets to be stored (but not necessarily where they actually are) // Example: for gTileset_DepartmentStore, returns "data/tilesets/secondary/department_store" QString Tileset::getExpectedDir() { return Tileset::getExpectedDir(this->name, this->is_secondary); } QString Tileset::getExpectedDir(QString tilesetName, bool isSecondary) { const QString basePath = isSecondary ? projectConfig.getFilePath(ProjectFilePath::data_secondary_tilesets_folders) : projectConfig.getFilePath(ProjectFilePath::data_primary_tilesets_folders); static const QRegularExpression re("([a-z])([A-Z0-9])"); return basePath + Tileset::stripPrefix(tilesetName).replace(re, "\\1_\\2").toLower(); } // Get the expected positions of the members in struct Tileset. // Used when parsing asm tileset data, or C tileset data that's missing initializers. QHash<int, QString> Tileset::getHeaderMemberMap(bool usingAsm) { // The asm header has a padding field that needs to be skipped int paddingOffset = usingAsm ? 1 : 0; // The position of metatileAttributes changes between games bool isPokefirered = (projectConfig.baseGameVersion == BaseGameVersion::pokefirered); int metatileAttrPosition = (isPokefirered ? 6 : 5) + paddingOffset; auto map = QHash<int, QString>(); map.insert(1, "isSecondary"); map.insert(2 + paddingOffset, "tiles"); map.insert(3 + paddingOffset, "palettes"); map.insert(4 + paddingOffset, "metatiles"); map.insert(metatileAttrPosition, "metatileAttributes"); return map; } bool Tileset::loadMetatiles() { clearMetatiles(); QFile file(this->metatiles_path); if (!file.open(QIODevice::ReadOnly)) { logError(QString("Could not open '%1' for reading: %2").arg(this->metatiles_path).arg(file.errorString())); return false; } QByteArray data = file.readAll(); int tilesPerMetatile = projectConfig.getNumTilesInMetatile(); int bytesPerMetatile = Tile::sizeInBytes() * tilesPerMetatile; int numMetatiles = data.length() / bytesPerMetatile; if (numMetatiles > maxMetatiles()) { logWarn(QString("%1 metatile count %2 exceeds limit of %3. Additional metatiles will be ignored.") .arg(this->name) .arg(numMetatiles) .arg(maxMetatiles())); numMetatiles = maxMetatiles(); } for (int i = 0; i < numMetatiles; i++) { auto metatile = new Metatile; int index = i * bytesPerMetatile; for (int j = 0; j < tilesPerMetatile; j++) { uint16_t tileRaw = static_cast<unsigned char>(data[index++]); tileRaw |= static_cast<unsigned char>(data[index++]) << 8; metatile->tiles.append(Tile(tileRaw)); } m_metatiles.append(metatile); } return true; } bool Tileset::saveMetatiles() { QFile file(this->metatiles_path); if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { logError(QString("Could not open '%1' for writing: %2").arg(this->metatiles_path).arg(file.errorString())); return false; } QByteArray data; int numTiles = projectConfig.getNumTilesInMetatile(); for (const auto &metatile : m_metatiles) { for (int i = 0; i < numTiles; i++) { uint16_t tile = metatile->tiles.value(i).rawValue(); data.append(static_cast<char>(tile)); data.append(static_cast<char>(tile >> 8)); } } file.write(data); return true; } bool Tileset::loadMetatileAttributes() { QFile file(this->metatile_attrs_path); if (!file.open(QIODevice::ReadOnly)) { logError(QString("Could not open '%1' for reading: %2").arg(this->metatile_attrs_path).arg(file.errorString())); return false; } QByteArray data = file.readAll(); int attrSize = projectConfig.metatileAttributesSize; int numMetatiles = m_metatiles.length(); int numMetatileAttrs = data.length() / attrSize; if (numMetatileAttrs > numMetatiles) { logWarn(QString("%1 metatile attributes count %2 exceeds metatile count of %3. Additional attributes will be ignored.") .arg(this->name) .arg(numMetatileAttrs) .arg(numMetatiles)); numMetatileAttrs = numMetatiles; } else if (numMetatileAttrs < numMetatiles) { logWarn(QString("%1 metatile attributes count %2 is fewer than the metatile count of %3. Missing attributes will default to 0.") .arg(this->name) .arg(numMetatileAttrs) .arg(numMetatiles)); } for (int i = 0; i < numMetatileAttrs; i++) { uint32_t attributes = 0; for (int j = 0; j < attrSize; j++) attributes |= static_cast<unsigned char>(data.at(i * attrSize + j)) << (8 * j); m_metatiles.at(i)->setAttributes(attributes); } return true; } bool Tileset::saveMetatileAttributes() { QFile file(this->metatile_attrs_path); if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { logError(QString("Could not open '%1' for writing: %2").arg(this->metatile_attrs_path).arg(file.errorString())); return false; } QByteArray data; for (const auto &metatile : m_metatiles) { uint32_t attributes = metatile->getAttributes(); for (int i = 0; i < projectConfig.metatileAttributesSize; i++) data.append(static_cast<char>(attributes >> (8 * i))); } file.write(data); return true; } bool Tileset::loadTilesImage(QImage *importedImage) { QImage image; bool imported = false; if (importedImage) { image = *importedImage; imported = true; } else if (QFile::exists(this->tilesImagePath)) { // No image provided, load from file path. image = QImage(this->tilesImagePath).convertToFormat(QImage::Format_Indexed8, Qt::ThresholdDither); } if (image.isNull()) { logWarn(QString("Failed to load tiles image for %1. Using default tiles image.").arg(this->name)); image = QImage(Tile::pixelWidth(), Tile::pixelHeight(), QImage::Format_Indexed8); image.fill(0); } // Validate image dimensions if (image.width() % Tile::pixelWidth() || image.height() % Tile::pixelHeight()) { logError(QString("%1 tiles image has invalid dimensions %2x%3. Dimensions must be a multiple of %4x%5.") .arg(this->name) .arg(image.width()) .arg(image.height()) .arg(Tile::pixelWidth()) .arg(Tile::pixelHeight())); return false; } // Validate the number of colors in the image. int colorCount = image.colorCount(); if (colorCount > Tileset::numColorsPerPalette()) { flattenTo4bppImage(&image); } else if (colorCount < Tileset::numColorsPerPalette()) { QVector<QRgb> colorTable = image.colorTable(); for (int i = colorTable.length(); i < Tileset::numColorsPerPalette(); i++) { colorTable.append(0); } image.setColorTable(colorTable); } m_tilesImage = image; // Cut up the full tiles image into individual tile images. m_tiles.clear(); for (int y = 0; y < image.height(); y += Tile::pixelHeight()) for (int x = 0; x < image.width(); x += Tile::pixelWidth()) { m_tiles.append(image.copy(x, y, Tile::pixelWidth(), Tile::pixelHeight())); } if (m_tiles.length() > maxTiles()) { logWarn(QString("%1 tile count of %2 exceeds limit of %3. Additional tiles will not be displayed.") .arg(this->name) .arg(m_tiles.length()) .arg(maxTiles())); // Just resize m_tiles so that numTiles() reports the correct tile count. // We'll leave m_tilesImage alone (it doesn't get displayed, and we don't want to delete the user's image data). m_tiles = m_tiles.mid(0, maxTiles()); } if (imported) { // Only set this flag once we've successfully loaded the tiles image. m_hasUnsavedTilesImage = true; } return true; } bool Tileset::saveTilesImage() { // Only write the tiles image if it was changed. // Porymap will only ever change an existing tiles image by importing a new one. if (!m_hasUnsavedTilesImage) return true; if (!m_tilesImage.save(this->tilesImagePath, "PNG")) { logError(QString("Failed to save tiles image '%1'").arg(this->tilesImagePath)); return false; } m_hasUnsavedTilesImage = false; return true; } bool Tileset::loadPalettes() { this->palettes.clear(); this->palettePreviews.clear(); for (int i = 0; i < Project::getNumPalettesTotal(); i++) { QList<QRgb> palette; QString path = this->palettePaths.value(i); if (!path.isEmpty()) { bool error = false; palette = PaletteUtil::parse(path, &error); if (error) palette.clear(); } if (palette.isEmpty()) { // Either the palette failed to load, or no palette exists. // We expect tilesets to have a certain number of palettes, // so fill this palette with dummy colors. for (int j = 0; j < Tileset::numColorsPerPalette(); j++) { int colorComponent = j * (256 / Tileset::numColorsPerPalette()); palette.append(qRgb(colorComponent, colorComponent, colorComponent)); } } this->palettes.append(palette); this->palettePreviews.append(palette); } return true; } bool Tileset::savePalettes() { bool success = true; int numPalettes = qMin(this->palettePaths.length(), this->palettes.length()); for (int i = 0; i < numPalettes; i++) { if (!PaletteUtil::writeJASC(this->palettePaths.at(i), this->palettes.at(i).toVector(), 0, Tileset::numColorsPerPalette())) success = false; } return success; } bool Tileset::load() { bool success = true; if (!loadPalettes()) success = false; if (!loadTilesImage()) success = false; if (!loadMetatiles()) success = false; if (!loadMetatileAttributes()) success = false; return success; } // Because metatile labels are global (and handled by the project) we don't save them here. bool Tileset::save() { bool success = true; if (!savePalettes()) success = false; if (!saveTilesImage()) success = false; if (!saveMetatiles()) success = false; if (!saveMetatileAttributes()) success = false; return success; } QString Tileset::stripPrefix(const QString &fullName) { return QString(fullName).replace(projectConfig.getIdentifier(ProjectIdentifier::symbol_tilesets_prefix), ""); } // Find which of the specified color IDs in 'searchColors' are not used by any of this tileset's metatiles. // The 'pairedTileset' may be used to get the tile images for any tiles that don't belong to this tileset. // If 'searchColors' is empty, it will for search for all unused colors. QSet<int> Tileset::getUnusedColorIds(int paletteId, const Tileset *pairedTileset, const QSet<int> &searchColors) const { QSet<int> unusedColors = searchColors; if (unusedColors.isEmpty()) { // Search for all colors for (int i = 0; i < Tileset::numColorsPerPalette(); i++) { unusedColors.insert(i); } } const Tileset *primaryTileset = this->is_secondary ? pairedTileset : this; const Tileset *secondaryTileset = this->is_secondary ? this : pairedTileset; QSet<uint16_t> seenTileIds; for (const auto &metatile : m_metatiles) for (const auto &tile : metatile->tiles) { if (tile.palette != paletteId) continue; // Save time by ignoring tiles we've already inspected. if (seenTileIds.contains(tile.tileId)) continue; seenTileIds.insert(tile.tileId); QImage image = getTileImage(tile.tileId, primaryTileset, secondaryTileset); if (image.isNull() || image.sizeInBytes() < Tile::numPixels()) continue; const uchar * pixels = image.constBits(); for (int i = 0; i < Tile::numPixels(); i++) { auto it = unusedColors.constFind(pixels[i]); if (it != unusedColors.constEnd()) { unusedColors.erase(it); if (unusedColors.isEmpty()) { return {}; } } } } return unusedColors; } // Returns the list of metatile IDs representing all the metatiles in this tileset that use the specified color ID. QList<uint16_t> Tileset::findMetatilesUsingColor(int paletteId, int colorId, const Tileset *pairedTileset) const { const Tileset *primaryTileset = this->is_secondary ? pairedTileset : this; const Tileset *secondaryTileset = this->is_secondary ? this : pairedTileset; QSet<uint16_t> metatileIdSet; QHash<uint16_t, bool> tileContainsColor; uint16_t metatileIdBase = firstMetatileId(); for (int i = 0; i < m_metatiles.length(); i++) { uint16_t metatileId = i + metatileIdBase; for (const auto &tile : m_metatiles.at(i)->tiles) { if (tile.palette != paletteId) continue; // Save time on tiles we've already inspected by getting the cached result. auto tileIt = tileContainsColor.constFind(tile.tileId); if (tileIt != tileContainsColor.constEnd()) { if (tileIt.value()) metatileIdSet.insert(metatileId); continue; } tileContainsColor[tile.tileId] = false; QImage image = getTileImage(tile.tileId, primaryTileset, secondaryTileset); if (image.isNull() || image.sizeInBytes() < Tile::numPixels()) continue; const uchar * pixels = image.constBits(); for (int j = 0; j < Tile::numPixels(); j++) { if (pixels[j] == colorId) { metatileIdSet.insert(metatileId); tileContainsColor[tile.tileId] = true; break; } } } } QList<uint16_t> metatileIds(metatileIdSet.constBegin(), metatileIdSet.constEnd()); std::sort(metatileIds.begin(), metatileIds.end()); return metatileIds; }
412
0.950788
1
0.950788
game-dev
MEDIA
0.596796
game-dev
0.881838
1
0.881838
ProjectIgnis/CardScripts
4,102
unofficial/c513000182.lua
--TG サイバー・マジシャン SC-01 (Anime) --T.G. Cyber Magician (Anime) local s,id=GetID() function s.initial_effect(c) --synchro custom local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e1:SetCode(EFFECT_HAND_SYNCHRO) e1:SetLabel(64910482) e1:SetValue(s.synval) c:RegisterEffect(e1) --Type Machine local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e2:SetCode(EFFECT_ADD_RACE) e2:SetRange(LOCATION_MZONE) e2:SetValue(RACE_MACHINE) c:RegisterEffect(e2) --Halve this card's ATK/DEF when it is targeted by your Spell/Trap cards local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(id,1)) e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_QUICK_O) e3:SetCode(EVENT_CHAINING) e3:SetRange(LOCATION_MZONE) e3:SetCondition(s.discon) e3:SetOperation(s.disop) c:RegisterEffect(e3) --Search 1 "T.G." monster local e4=Effect.CreateEffect(c) e4:SetDescription(aux.Stringid(id,1)) e4:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e4:SetCode(EVENT_TO_GRAVE) e4:SetCondition(s.scon) e4:SetTarget(s.stg) e4:SetOperation(s.sop) c:RegisterEffect(e4) end s.listed_series={SET_TG} function s.synval(e,c,sc) if c:IsNotTuner(sc,e:GetHandlerPlayer()) and c:IsLocation(LOCATION_HAND) then local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_HAND_SYNCHRO+EFFECT_SYNCHRO_CHECK) e1:SetLabel(64910482) e1:SetTarget(s.synchktg) c:RegisterEffect(e1) return true else return false end end function s.chk2(c) if not c:IsHasEffect(EFFECT_HAND_SYNCHRO) or c:IsHasEffect(EFFECT_HAND_SYNCHRO+EFFECT_SYNCHRO_CHECK) then return false end local te={c:GetCardEffect(EFFECT_HAND_SYNCHRO)} for i=1,#te do local e=te[i] if e:GetLabel()==64910482 then return true end end return false end function s.synchktg(e,c,sg,tg,ntg,tsg,ntsg) if c then local res=tg:IsExists(s.chk2,1,c) or ntg:IsExists(s.chk2,1,c) or sg:IsExists(s.chk2,1,c) return res,Group.CreateGroup(),Group.CreateGroup() else return true end end function s.discon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsStatus(STATUS_BATTLE_DESTROYED) then return false end if not re:IsHasType(EFFECT_TYPE_ACTIVATE) then return false end return rp==tp and re:IsHasProperty(EFFECT_FLAG_CARD_TARGET) and Duel.GetChainInfo(ev,CHAININFO_TARGET_CARDS):IsContains(c) end function s.disop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) and c:IsFaceup() then local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1:SetCode(EFFECT_SET_BASE_ATTACK) e1:SetReset(RESET_EVENT|RESETS_STANDARD) e1:SetValue(c:GetBaseAttack()/2) c:RegisterEffect(e1) local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e2:SetCode(EFFECT_SET_BASE_DEFENSE) e2:SetReset(RESET_EVENT|RESETS_STANDARD) e2:SetValue(c:GetBaseDefense()/2) c:RegisterEffect(e2) end end function s.scon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():IsPreviousLocation(LOCATION_ONFIELD) and e:GetHandler():IsReason(REASON_DESTROY) end function s.thfilter(c) return c:IsMonster() and c:IsSetCard(SET_TG) and c:IsAbleToHand() end function s.stg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(s.thfilter,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) end function s.sop(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,s.thfilter,tp,LOCATION_DECK,0,1,1,nil) if #g>0 then Duel.SendtoHand(g,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,g) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_FORBIDDEN) e1:SetRange(0xff) e1:SetTargetRange(0x7f,0x7f) e1:SetTarget(function(e,c) return c==e:GetHandler() end) e1:SetReset(RESET_EVENT|RESETS_STANDARD|RESET_PHASE|PHASE_END) g:GetFirst():RegisterEffect(e1) end end
412
0.860885
1
0.860885
game-dev
MEDIA
0.970694
game-dev
0.93934
1
0.93934
Fluorohydride/ygopro-scripts
1,014
c76986005.lua
--サイバー・ジラフ function c76986005.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(76986005,0)) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_MZONE) e1:SetCost(c76986005.cost) e1:SetOperation(c76986005.operation) c:RegisterEffect(e1) end function c76986005.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsReleasable() end Duel.Release(e:GetHandler(),REASON_COST) end function c76986005.operation(e,tp,eg,ep,ev,re,r,rp) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_CHANGE_DAMAGE) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetTargetRange(1,0) e1:SetValue(c76986005.damval) e1:SetReset(RESET_PHASE+PHASE_END) Duel.RegisterEffect(e1,tp) local e2=e1:Clone() e2:SetCode(EFFECT_NO_EFFECT_DAMAGE) e2:SetReset(RESET_PHASE+PHASE_END) Duel.RegisterEffect(e2,tp) end function c76986005.damval(e,re,val,r,rp,rc) if bit.band(r,REASON_EFFECT)~=0 then return 0 else return val end end
412
0.748179
1
0.748179
game-dev
MEDIA
0.964906
game-dev
0.779589
1
0.779589
mcMMO-Dev/mcMMO
2,622
src/main/java/com/gmail/nossr50/commands/party/PartyXpShareCommand.java
package com.gmail.nossr50.commands.party; import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.datatypes.party.PartyFeature; import com.gmail.nossr50.datatypes.party.ShareMode; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.text.StringUtils; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; public class PartyXpShareCommand implements CommandExecutor { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } Party party = UserManager.getPlayer((Player) sender).getParty(); if (party.getLevel() < mcMMO.p.getGeneralConfig() .getPartyFeatureUnlockLevel(PartyFeature.XP_SHARE)) { sender.sendMessage(LocaleLoader.getString("Party.Feature.Disabled.5")); return true; } if (args.length == 2) { if (args[1].equalsIgnoreCase("none") || CommandUtils.shouldDisableToggle(args[1])) { handleChangingShareMode(party, ShareMode.NONE); } else if (args[1].equalsIgnoreCase("equal") || args[1].equalsIgnoreCase("even") || CommandUtils.shouldEnableToggle(args[1])) { handleChangingShareMode(party, ShareMode.EQUAL); } else { sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "xpshare", "<NONE | EQUAL>")); } return true; } sender.sendMessage( LocaleLoader.getString("Commands.Usage.2", "party", "xpshare", "<NONE | EQUAL>")); return true; } private void handleChangingShareMode(Party party, ShareMode mode) { party.setXpShareMode(mode); String changeModeMessage = LocaleLoader.getString("Commands.Party.SetSharing", LocaleLoader.getString("Party.ShareType.Xp"), LocaleLoader.getString( "Party.ShareMode." + StringUtils.getCapitalized(mode.toString()))); for (Player member : party.getOnlineMembers()) { member.sendMessage(changeModeMessage); } } }
412
0.754295
1
0.754295
game-dev
MEDIA
0.783992
game-dev
0.755279
1
0.755279
GTNewHorizons/GT5-Unofficial
8,860
src/main/java/gtPlusPlus/xmod/gregtech/loaders/RecipeGenShapedCrafting.java
package gtPlusPlus.xmod.gregtech.loaders; import java.util.HashSet; import java.util.Set; import gregtech.api.util.GTModHandler; import gtPlusPlus.api.interfaces.RunnableWithInfo; import gtPlusPlus.api.objects.Logger; import gtPlusPlus.core.material.Material; import gtPlusPlus.core.material.MaterialGenerator; public class RecipeGenShapedCrafting extends RecipeGenBase { public static final Set<RunnableWithInfo<Material>> mRecipeGenMap = new HashSet<>(); static { MaterialGenerator.mRecipeMapsToGenerate.add(mRecipeGenMap); } public RecipeGenShapedCrafting(final Material M) { this.toGenerate = M; mRecipeGenMap.add(this); } @Override public void run() { generateRecipes(this.toGenerate); } private void generateRecipes(final Material material) { Logger.WARNING("Generating Shaped Crafting recipes for " + material.getLocalizedName()); // TODO // Single Plate Shaped/Shapeless if (material.getPlate(1) != null && material.getIngot(1) != null) if (material.getPlate(1) != null && material.getIngot(1) != null) GTModHandler.addCraftingRecipe( material.getPlate(1), GTModHandler.RecipeBits.DO_NOT_CHECK_FOR_COLLISIONS | GTModHandler.RecipeBits.BUFFERED, new Object[] { "h", "B", "I", 'I', material.getIngot(1), 'B', material.getIngot(1) }); // Double Plate Shaped/Shapeless if (material.getPlateDouble(1) != null && material.getPlate(1) != null) GTModHandler.addCraftingRecipe( material.getPlateDouble(1), GTModHandler.RecipeBits.DO_NOT_CHECK_FOR_COLLISIONS | GTModHandler.RecipeBits.BUFFERED, new Object[] { "I", "B", "h", 'I', material.getPlate(1), 'B', material.getPlate(1) }); // Ring Recipe if (!material.isRadioactive && material.getRing(1) != null && material.getRod(1) != null) { if (GTModHandler.addCraftingRecipe( material.getRing(1), GTModHandler.RecipeBits.DO_NOT_CHECK_FOR_COLLISIONS | GTModHandler.RecipeBits.BUFFERED, new Object[] { "h ", "fR", 'R', material.getRod(1) })) { Logger.WARNING("GT:NH Ring Recipe: " + material.getLocalizedName() + " - Success"); } else { Logger.WARNING("GT:NH Ring Recipe: " + material.getLocalizedName() + " - Failed"); } } // Framebox Recipe if (!material.isRadioactive && material.getFrameBox(1) != null && material.getRod(1) != null) { if (GTModHandler.addCraftingRecipe( material.getFrameBox(2), GTModHandler.RecipeBits.DO_NOT_CHECK_FOR_COLLISIONS | GTModHandler.RecipeBits.BUFFERED, new Object[] { "RRR", "RwR", "RRR", 'R', material.getRod(1) })) { Logger.WARNING("Framebox Recipe: " + material.getLocalizedName() + " - Success"); } else { Logger.WARNING("Framebox Recipe: " + material.getLocalizedName() + " - Failed"); } } // Shaped Recipe - Bolts if (!material.isRadioactive && material.getBolt(1) != null && material.getRod(1) != null) { if (GTModHandler.addCraftingRecipe( material.getBolt(2), GTModHandler.RecipeBits.DO_NOT_CHECK_FOR_COLLISIONS | GTModHandler.RecipeBits.BUFFERED, new Object[] { "s ", " R", 'R', material.getRod(1) })) { Logger.WARNING("Bolt Recipe: " + material.getLocalizedName() + " - Success"); } else { Logger.WARNING("Bolt Recipe: " + material.getLocalizedName() + " - Failed"); } } // Shaped Recipe - Fine Wire if (!material.isRadioactive && material.getFoil(1) != null && material.getFineWire(1) != null) { if (GTModHandler.addCraftingRecipe( material.getFineWire(1), GTModHandler.RecipeBits.DO_NOT_CHECK_FOR_COLLISIONS | GTModHandler.RecipeBits.BUFFERED, new Object[] { "Fx", 'F', material.getFoil(1) })) { Logger.WARNING("Fine Wire Recipe: " + material.getLocalizedName() + " - Success"); } else { Logger.WARNING("Fine Wire Recipe: " + material.getLocalizedName() + " - Failed"); } } // Shaped Recipe - Foil if (material.getFoil(1) != null && material.getPlate(1) != null) { if (GTModHandler.addCraftingRecipe( material.getFoil(2), GTModHandler.RecipeBits.DO_NOT_CHECK_FOR_COLLISIONS | GTModHandler.RecipeBits.BUFFERED, new Object[] { "hP", 'P', material.getPlate(1) })) { Logger.WARNING("Foil Recipe: " + material.getLocalizedName() + " - Success"); } else { Logger.WARNING("Foil Recipe: " + material.getLocalizedName() + " - Failed"); } } // Shaped Recipe - Ingot to Rod if (material.getRod(1) != null && material.getIngot(1) != null) if (GTModHandler.addCraftingRecipe( material.getRod(1), GTModHandler.RecipeBits.DO_NOT_CHECK_FOR_COLLISIONS | GTModHandler.RecipeBits.BUFFERED, new Object[] { "f ", " I", 'I', material.getIngot(1) })) { Logger.WARNING("Rod Recipe: " + material.getLocalizedName() + " - Success"); } else { Logger.WARNING("Rod Recipe: " + material.getLocalizedName() + " - Failed"); } // Shaped Recipe - Long Rod to two smalls if (material.getRod(1) != null && material.getLongRod(1) != null) if (GTModHandler.addCraftingRecipe( material.getRod(2), GTModHandler.RecipeBits.DO_NOT_CHECK_FOR_COLLISIONS | GTModHandler.RecipeBits.BUFFERED, new Object[] { "s", "L", 'L', material.getLongRod(1) })) { Logger.WARNING("Rod Recipe: " + material.getLocalizedName() + " - Success"); } else { Logger.WARNING("Rod Recipe: " + material.getLocalizedName() + " - Failed"); } // Two small to long rod if (material.getLongRod(1) != null && material.getRod(1) != null) if (GTModHandler.addCraftingRecipe( material.getLongRod(1), GTModHandler.RecipeBits.DO_NOT_CHECK_FOR_COLLISIONS | GTModHandler.RecipeBits.BUFFERED, new Object[] { "RhR", 'R', material.getRod(1) })) { Logger.WARNING("Long Rod Recipe: " + material.getLocalizedName() + " - Success"); } else { Logger.WARNING("Long Rod Recipe: " + material.getLocalizedName() + " - Failed"); } // Rotor Recipe if (!material.isRadioactive && material.getRotor(1) != null && material.getRing(1) != null && !material.isRadioactive && material.getPlate(1) != null && material.getScrew(1) != null) { if (GTModHandler.addCraftingRecipe( material.getRotor(1), GTModHandler.RecipeBits.DO_NOT_CHECK_FOR_COLLISIONS | GTModHandler.RecipeBits.BUFFERED, new Object[] { "PhP", "SRf", "PdP", 'P', material.getPlate(1), 'S', material.getScrew(1), 'R', material.getRing(1), })) { Logger.WARNING("Rotor Recipe: " + material.getLocalizedName() + " - Success"); } else { Logger.WARNING("Rotor Recipe: " + material.getLocalizedName() + " - Failed"); } } // Gear Recipe if (!material.isRadioactive && material.getGear(1) != null && material.getPlate(1) != null && material.getRod(1) != null) { if (GTModHandler.addCraftingRecipe( material.getGear(1), GTModHandler.RecipeBits.DO_NOT_CHECK_FOR_COLLISIONS | GTModHandler.RecipeBits.BUFFERED, new Object[] { "RPR", "PwP", "RPR", 'P', material.getPlate(1), 'R', material.getRod(1), })) { Logger.WARNING("Gear Recipe: " + material.getLocalizedName() + " - Success"); } else { Logger.WARNING("Gear Recipe: " + material.getLocalizedName() + " - Failed"); } } // Screws if (!material.isRadioactive && material.getScrew(1) != null && material.getBolt(1) != null) { if (GTModHandler.addCraftingRecipe( material.getScrew(1), GTModHandler.RecipeBits.DO_NOT_CHECK_FOR_COLLISIONS | GTModHandler.RecipeBits.BUFFERED, new Object[] { "fB", "B ", 'B', material.getBolt(1), })) { Logger.WARNING("Screw Recipe: " + material.getLocalizedName() + " - Success"); } else { Logger.WARNING("Screw Recipe: " + material.getLocalizedName() + " - Failed"); } } } }
412
0.915155
1
0.915155
game-dev
MEDIA
0.945661
game-dev
0.899391
1
0.899391
frc1678/C2025-Public
16,810
src/main/java/frc/robot/controlboard/ControlBoard.java
package frc.robot.controlboard; import com.ctre.phoenix6.swerve.SwerveRequest; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.units.Units; import edu.wpi.first.units.measure.Time; import edu.wpi.first.wpilibj.GenericHID.RumbleType; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.Command.InterruptionBehavior; import edu.wpi.first.wpilibj2.command.Commands; import edu.wpi.first.wpilibj2.command.InstantCommand; import edu.wpi.first.wpilibj2.command.SequentialCommandGroup; import edu.wpi.first.wpilibj2.command.SubsystemBase; import edu.wpi.first.wpilibj2.command.button.CommandXboxController; import edu.wpi.first.wpilibj2.command.button.Trigger; import edu.wpi.first.wpilibj2.command.sysid.SysIdRoutine.Direction; import frc.lib.util.FieldLayout.Level; import frc.robot.subsystems.algaedeploy.AlgaeDeploy; import frc.robot.subsystems.algaedeploy.AlgaeDeployConstants; import frc.robot.subsystems.climber.Climber; import frc.robot.subsystems.climberrollers.ClimberRollers; import frc.robot.subsystems.coralrollers.CoralRollers; import frc.robot.subsystems.detection.Detection; import frc.robot.subsystems.detection.DetectionConstants; import frc.robot.subsystems.drive.Drive; import frc.robot.subsystems.drive.DriveConstants; import frc.robot.subsystems.elevator.Elevator; import frc.robot.subsystems.endeffector.EndEffector; import frc.robot.subsystems.pivot.Pivot; import frc.robot.subsystems.superstructure.Superstructure; import java.util.function.Supplier; public class ControlBoard extends SubsystemBase { public static final ControlBoard mInstance = new ControlBoard(); private CommandXboxController driver = ControlBoardConstants.mDriverController; private CommandXboxController operator = ControlBoardConstants.mOperatorController; private final SwerveRequest.SwerveDriveBrake brake = new SwerveRequest.SwerveDriveBrake(); private final SwerveRequest.PointWheelsAt point = new SwerveRequest.PointWheelsAt(); private final Trigger overrideTrigger = driver.rightTrigger(0.1); private OverrideBehavior overrideBehavior = OverrideBehavior.CORAL_SCORE_L4; private Trigger rightBumper = driver.rightBumper(); private Trigger endEffectorTrigger; public static enum OverrideBehavior { NET_SCORE(() -> Superstructure.mInstance.netScore().andThen(Superstructure.mInstance.tuck())), PROCESSOR_SCORE( () -> Superstructure.mInstance.processorScore().andThen(Superstructure.mInstance.tuckAfterProcessor())), ALGAE_HOLD(() -> Superstructure.mInstance.algaeStow()), CORAL_SCORE_L1(() -> Superstructure.mInstance.softCoralScore()), CORAL_SCORE_L2(() -> Superstructure.mInstance.coralScore(Level.L2)), CORAL_SCORE_L3(() -> Superstructure.mInstance.coralScore(Level.L3)), CORAL_SCORE_L4(() -> Superstructure.mInstance.coralScore(Level.L4)), TUCK(() -> Superstructure.mInstance.tuck()), NONE(() -> Commands.none()); public final Supplier<Command> action; private OverrideBehavior(Supplier<Command> overrideAction) { action = overrideAction; } } public Command setOverrideBehavior(OverrideBehavior behavior) { return Commands.runOnce(() -> overrideBehavior = behavior); } public boolean getCoralMode() { return !rightBumper.getAsBoolean() && !Superstructure.mInstance.getHasAlgae(); } public void configureBindings() { Drive.mInstance.setDefaultCommand(Drive.mInstance.followSwerveRequestCommand( DriveConstants.teleopRequest, DriveConstants.teleopRequestUpdater)); driver.back() .onTrue(Commands.runOnce( () -> Drive.mInstance.getGeneratedDrive().seedFieldCentric(), Drive.mInstance) .ignoringDisable(true)); driverControls(); debugControls(); } public OverrideBehavior getOverrideBehavior() { return overrideBehavior; } public void bringupControls() { operator.a().onTrue(Commands.runOnce(() -> Detection.mInstance.setPipeline(DetectionConstants.kAutoPipeline))); operator.b().onTrue(Commands.runOnce(() -> Detection.mInstance.setPipeline(DetectionConstants.kTelePipeline))); } public void driverControls() { Superstructure s = Superstructure.mInstance; // MISC ############################################################################### endEffectorTrigger = new Trigger(() -> s.getEndEffectorCoralBreak()); endEffectorTrigger.onTrue(rumbleCommand(Units.Seconds.of(0.2))); driver.start().onTrue(s.stationIntakeToHold()); driver.a().onTrue(s.spit().onlyWhile(driver.a())); driver.y().onTrue(s.prepClimb()); driver.b().onTrue(s.stowClimb()); driver.leftBumper().onTrue(s.tuckOrHold()); overrideTrigger.onFalse(Commands.deferredProxy(() -> overrideBehavior.action.get())); // INTAKING ############################################################################### driver.leftTrigger(0.1) .onTrue(Commands.either( s.coralIntakeToHold() .asProxy() .beforeStarting(Commands.runOnce(() -> s.setForceGulp(false))), Commands.either( s.coralIntaketoIndexer(), s.algaeIntakeToHold() .asProxy() .beforeStarting(setOverrideBehavior(OverrideBehavior.ALGAE_HOLD)), () -> Superstructure.mInstance.getHasAlgae()), () -> getCoralMode()) .withName("Either Coral Intake or Algae Intake")); // CORAL MODE ############################################################################### // Top Left Paddle bindCoralAutoScore(Level.L1, driver.povRight()); // Top Right Paddle bindCoralAutoScore(Level.L2, driver.povUp()); // Bottom Left Paddle bindCoralAutoScore(Level.L3, driver.povLeft()); // Bottom Right Paddle bindCoralAutoScore(Level.L4, driver.povDown()); // ALGAE MODE ############################################################################### // Top Left Paddle driver.povRight() .and(() -> !getCoralMode()) .onTrue(Superstructure.mInstance.processorPrep()) .onTrue(setOverrideBehavior(OverrideBehavior.PROCESSOR_SCORE)); // Bottom Left Paddle bindAlgaeReefIntake(driver.povLeft()); // Bottom Right Paddle bindNetAlignAndScore(driver.povDown()); } public void bindCoralAutoScore(Level level, Trigger button) { Command scoreCommand = switch (level) { case L1 -> Superstructure.mInstance.L1Score(); case L2 -> Superstructure.mInstance.L2Score(); case L3 -> Superstructure.mInstance.L3Score(); case L4 -> Superstructure.mInstance.L4Score(); default -> Commands.none(); }; Command tuckCommand = level == Level.L1 ? Superstructure.mInstance.tuckAfterL1() : Superstructure.mInstance.tuckAfterScoring(); OverrideBehavior coralOverrideBehavior = switch (level) { case L1 -> OverrideBehavior.CORAL_SCORE_L1; case L2 -> OverrideBehavior.CORAL_SCORE_L2; case L3 -> OverrideBehavior.CORAL_SCORE_L3; case L4 -> OverrideBehavior.CORAL_SCORE_L4; default -> OverrideBehavior.CORAL_SCORE_L4; }; button.onTrue(Commands.either( Commands.sequence( Superstructure.mInstance .waitToStartScoreSequence() .onlyWhile(button) .until(overrideTrigger), scoreCommand .asProxy() .onlyWhile((button.or(overrideTrigger))) .onlyIf(button.or(overrideTrigger)) .andThen(Commands.either( Commands.parallel( reefIntakeSuperstructure(driver.rightBumper()), reefIntakeDrive(driver.rightBumper()), reefIntakeSetOverrideBehavior(driver.rightBumper())), (tuckCommand) .asProxy() .onlyIf(button.and( () -> EndEffector.mInstance.getCurrentCommand() == null)), driver.rightBumper())) .asProxy() .withInterruptBehavior(InterruptionBehavior.kCancelIncoming) .withName("Auto Score " + level.toString())), Commands.none(), () -> getCoralMode()) .withName("Either Auto Score " + level.toString())) .onTrue(Commands.either( Superstructure.mInstance .goToScoringPose(level) .asProxy() .until(overrideTrigger) .unless(overrideTrigger) .onlyWhile(button) .withName("Auto Align " + level.toString()), Commands.none(), () -> getCoralMode()) .withName("Either Auto Align " + level.toString())) .onTrue(Commands.either( setOverrideBehavior(coralOverrideBehavior), Commands.none(), () -> getCoralMode())); } public void bindNetAlignAndScore(Trigger button) { button.onTrue(Commands.either( Commands.sequence( Superstructure.mInstance .waitUnitlSlowEnoughToRaiseNet() .onlyWhile(button) .until(overrideTrigger), Superstructure.mInstance .netPrep() .asProxy() .onlyWhile((button.or(overrideTrigger))) .onlyIf(button.or(overrideTrigger)) .asProxy() .withInterruptBehavior(InterruptionBehavior.kCancelIncoming) .withName("Auto Score Net")), Commands.none(), () -> !getCoralMode()) .withName("Either Auto Score Net Or None ")) .onTrue(Commands.either( Superstructure.mInstance .alignToNet() .asProxy() .withInterruptBehavior(InterruptionBehavior.kCancelIncoming) .until(overrideTrigger) .unless(overrideTrigger) .onlyWhile(button) .withName("Auto Align Net Drive"), Commands.none(), () -> !getCoralMode()) .withName("Either Auto Align Net Drive")) .onTrue(Commands.either( setOverrideBehavior(OverrideBehavior.NET_SCORE), Commands.none(), () -> !getCoralMode())); } public void bindAlgaeReefIntake(Trigger button) { button.onTrue(Commands.either(reefIntakeSuperstructure(button), Commands.none(), () -> !getCoralMode())) .onTrue(Commands.either(reefIntakeDrive(button), Commands.none(), () -> !getCoralMode())) .onTrue(Commands.either(reefIntakeSetOverrideBehavior(button), Commands.none(), () -> !getCoralMode())); } public Command reefIntakeSetOverrideBehavior(Trigger button) { return setOverrideBehavior(OverrideBehavior.ALGAE_HOLD) .onlyWhile(button) .until(overrideTrigger); } public Command reefIntakeSuperstructure(Trigger button) { return Commands.sequence( Superstructure.mInstance .reefIntakeAtRightLevel() .withInterruptBehavior(InterruptionBehavior.kCancelIncoming) .onlyIf(button.or(overrideTrigger).and(() -> !getCoralMode())), Superstructure.mInstance.stowAlgaeWhenReady()) .asProxy() .withName("Either Algae Reef Intake SS"); } public Command reefIntakeDrive(Trigger button) { return Superstructure.mInstance .goToReefIntakeReadyPose() .withDeadline(Superstructure.mInstance.elevatorAtRightPointForAlgaeIntakeFromReef()) .andThen(Superstructure.mInstance.goToReefIntakePose()) .asProxy() .until(overrideTrigger) .unless(overrideTrigger) .onlyWhile(button) .withName("Either Algae Reef Intake Drive"); } public void bindProcessorAutoScore(Trigger button) { button.onTrue(Commands.either( new SequentialCommandGroup( Superstructure.mInstance .processorPrep() .onlyWhile(button.or(overrideTrigger)), Superstructure.mInstance .processorScoreWhenReady() .onlyWhile((button.or(overrideTrigger))) .onlyIf((button.or(overrideTrigger))) .andThen(Superstructure.mInstance .tuckAfterProcessor() .onlyIf(button.or(overrideTrigger)))) .asProxy() .withName("Auto Processor Score"), Commands.none(), () -> !getCoralMode()) .withName("Either Auto Processor Score")) .onTrue(Commands.either( Superstructure.mInstance .goToProcessorScoringPose() .until(overrideTrigger) .unless(overrideTrigger) .onlyWhile(button) .asProxy() .withName("Auto Align to Processor"), Commands.none(), () -> !getCoralMode()) .withName("Either Auto Align to Processor")) .onTrue(Commands.either( setOverrideBehavior(OverrideBehavior.PROCESSOR_SCORE), Commands.none(), () -> !getCoralMode())); } private void debugControls() { Superstructure s = Superstructure.mInstance; operator.y().onTrue(s.stationIntakeToHold()); operator.a() .onTrue(CoralRollers.mInstance.setpointCommand(CoralRollers.START)) .onFalse(CoralRollers.mInstance.setpointCommand(CoralRollers.IDLE)); operator.b() .onTrue(Climber.mInstance .setpointCommand(Climber.JOG_UP) .andThen(() -> Climber.mInstance.useSoftLimits(false))) .onFalse(Climber.mInstance .setpointCommand(Climber.HOLD) .andThen(() -> Climber.mInstance.useSoftLimits(true))); operator.x() .onTrue(Climber.mInstance .setpointCommand(Climber.JOG_DOWN) .andThen(() -> Climber.mInstance.useSoftLimits(false))) .onFalse(Climber.mInstance .setpointCommand(Climber.HOLD) .andThen(() -> Climber.mInstance.useSoftLimits(true))); operator.rightBumper() .onTrue(Elevator.mInstance .setpointCommand(Elevator.JOG_UP) .andThen(() -> Elevator.mInstance.useSoftLimits(false))) .onFalse(Elevator.mInstance .setpointCommand(Elevator.HOLD_UP) .andThen(() -> Elevator.mInstance.useSoftLimits(true))); operator.rightTrigger(0.1) .onTrue(Elevator.mInstance .setpointCommand(Elevator.JOG_DOWN) .andThen(() -> Elevator.mInstance.useSoftLimits(false))) .onFalse(Elevator.mInstance .setpointCommand(Elevator.HOLD_UP) .andThen(() -> Elevator.mInstance.useSoftLimits(true))); operator.povUp().onTrue(ClimberRollers.mInstance.setpointCommand(ClimberRollers.INTAKE)); operator.povDown().onTrue(ClimberRollers.mInstance.setpointCommand(ClimberRollers.IDLE)); operator.leftBumper() .onTrue(new InstantCommand(() -> Pivot.mInstance.setCurrentPosition( Pivot.mInstance.directCancoder.getPosition().getValue())) .ignoringDisable(true)); operator.leftTrigger(0.1).onTrue(Elevator.mInstance.setpointCommand(Elevator.CLEAR_HIGH_HEIGHT)); operator.back() .onTrue(Commands.sequence( Commands.either( Commands.none(), AlgaeDeploy.mInstance.setpointCommand(AlgaeDeploy.FAR_CLEAR), () -> AlgaeDeploy.mInstance .getPosition() .isNear(AlgaeDeployConstants.kFarClearPosition, 0.1)), Pivot.mInstance.setpointCommand(Pivot.JOG_POSITIVE))) .onFalse(Pivot.mInstance.setpointCommand(Pivot.HOLD)); operator.start() .onTrue(Commands.sequence( Commands.either( Commands.none(), AlgaeDeploy.mInstance.setpointCommand(AlgaeDeploy.FAR_CLEAR), () -> AlgaeDeploy.mInstance .getPosition() .isNear(AlgaeDeployConstants.kFarClearPosition, 0.1)), Pivot.mInstance.setpointCommand(Pivot.JOG_NEGATIVE))) .onFalse(Pivot.mInstance.setpointCommand(Pivot.HOLD)); } public Command rumbleCommand(Time duration) { return Commands.sequence( Commands.runOnce(() -> { setRumble(true); }), Commands.waitSeconds(duration.in(Units.Seconds)), Commands.runOnce(() -> { setRumble(false); })) .handleInterrupt(() -> { setRumble(false); ; }); } public void setRumble(boolean on) { ControlBoardConstants.mDriverController.getHID().setRumble(RumbleType.kBothRumble, on ? 1.0 : 0.0); } public void configureSysIDTests() { // Run SysId routines when holding back/start and X/Y. // Note that each routine should be run exactly once in a single log. driver.back() .and(driver.y()) .whileTrue(Drive.mInstance.getGeneratedDrive().sysIdDynamic(Direction.kForward)); driver.back() .and(driver.x()) .whileTrue(Drive.mInstance.getGeneratedDrive().sysIdDynamic(Direction.kReverse)); driver.start() .and(driver.y()) .whileTrue(Drive.mInstance.getGeneratedDrive().sysIdQuasistatic(Direction.kForward)); driver.start() .and(driver.x()) .whileTrue(Drive.mInstance.getGeneratedDrive().sysIdQuasistatic(Direction.kReverse)); // Reset the field-centric heading on left bumper press driver.leftBumper().onTrue(Drive.mInstance.getGeneratedDrive().runOnce(() -> Drive.mInstance .getGeneratedDrive() .seedFieldCentric())); } public void configureModulePointing() { driver.a().whileTrue(Drive.mInstance.getGeneratedDrive().applyRequest(() -> brake)); driver.b() .whileTrue(Drive.mInstance .getGeneratedDrive() .applyRequest(() -> point.withModuleDirection(new Rotation2d(-driver.getLeftY(), -driver.getLeftX())))); } }
412
0.951577
1
0.951577
game-dev
MEDIA
0.559708
game-dev,desktop-app
0.826271
1
0.826271
etorth/mir2x
8,079
client/src/buttonbase.cpp
#include <functional> #include "sdldevice.hpp" #include "buttonbase.hpp" #include "sdldevice.hpp" #include "soundeffectdb.hpp" extern SDLDevice *g_sdlDevice; extern SoundEffectDB *g_seffDB; ButtonBase::ButtonBase( Widget::VarDir argDir, Widget::VarOff argX, Widget::VarOff argY, Widget::VarSize argW, Widget::VarSize argH, std::function<void(Widget * )> fnOnOverIn, std::function<void(Widget * )> fnOnOverOut, std::function<void(Widget *, bool)> fnOnClick, std::function<void(Widget * )> fnOnTrigger, std::optional<uint32_t> seffIDOnOverIn, std::optional<uint32_t> seffIDOnOverOut, std::optional<uint32_t> seffIDOnClick, int offXOnOver, int offYOnOver, int offXOnClick, int offYOnClick, bool onClickDone, bool radioMode, Widget *widgetPtr, bool autoFree) : Widget { std::move(argDir), std::move(argX), std::move(argY), std::move(argW), std::move(argH), {}, widgetPtr, autoFree, } , m_onClickDone(onClickDone) , m_radioMode(radioMode) , m_seffID { seffIDOnOverIn, seffIDOnOverOut, seffIDOnClick, } , m_offset { {0 , 0 }, {offXOnOver , offYOnOver }, {offXOnClick , offYOnClick}, } , m_onOverIn (std::move(fnOnOverIn )) , m_onOverOut(std::move(fnOnOverOut)) , m_onClick (std::move(fnOnClick )) , m_onTrigger(std::move(fnOnTrigger)) {} bool ButtonBase::processEventDefault(const SDL_Event &event, bool valid) { if(!valid){ if(m_radioMode){ if(getState() == BEVENT_ON){ setState(BEVENT_OFF); onOverOut(); } } else{ if(getState() != BEVENT_OFF){ setState(BEVENT_OFF); onOverOut(); } } return consumeFocus(false); } if(!active()){ if(m_radioMode){ if(getState() == BEVENT_ON){ setState(BEVENT_OFF); } } else{ if(getState() != BEVENT_OFF){ setState(BEVENT_OFF); } } return consumeFocus(false); } switch(event.type){ case SDL_MOUSEBUTTONUP: { if(in(event.button.x, event.button.y)){ switch(getState()){ case BEVENT_OFF: { setState(BEVENT_ON); onBadEvent(); break; } case BEVENT_DOWN: { if(m_radioMode){ // keep pressed } else{ setState(BEVENT_ON); onClick(true); if(m_onClickDone){ onTrigger(); } } break; } default: { break; } } return consumeFocus(true); } else if(m_radioMode){ return consumeFocus(false); } else{ if(getState() != BEVENT_OFF){ setState(BEVENT_OFF); onOverOut(); } return consumeFocus(false); } } case SDL_MOUSEBUTTONDOWN: { if(in(event.button.x, event.button.y)){ switch(getState()){ case BEVENT_OFF: { setState(BEVENT_DOWN); onBadEvent(); break; } case BEVENT_ON: { setState(BEVENT_DOWN); onClick(false); if(!m_onClickDone){ onTrigger(); } break; } default: { break; } } return consumeFocus(true); } else if(m_radioMode){ return consumeFocus(false); } else{ if(getState() != BEVENT_OFF){ setState(BEVENT_OFF); onOverOut(); } return consumeFocus(false); } } case SDL_MOUSEMOTION: { if(in(event.motion.x, event.motion.y)){ switch(getState()){ case BEVENT_OFF: { setState(BEVENT_ON); onOverIn(); break; } case BEVENT_DOWN: { if(event.motion.state & SDL_BUTTON_LMASK){ // hold the button and moving // don't trigger } else if(m_radioMode){ // keep pressed } else{ setState(BEVENT_ON); onBadEvent(); } break; } default: { break; } } return consumeFocus(true); } else if(m_radioMode){ if(getState() == BEVENT_ON){ setState(BEVENT_OFF); onOverOut(); } return consumeFocus(false); } else{ if(getState() != BEVENT_OFF){ setState(BEVENT_OFF); onOverOut(); } return consumeFocus(false); } } default: { return consumeFocus(false); } } } void ButtonBase::onOverIn() { if(m_onOverIn){ m_onOverIn(this); } if(m_seffID[0].has_value()){ g_sdlDevice->playSoundEffect(g_seffDB->retrieve((m_seffID[0].value()))); } } void ButtonBase::onOverOut() { if(m_onOverOut){ m_onOverOut(this); } if(m_seffID[1].has_value()){ g_sdlDevice->playSoundEffect(g_seffDB->retrieve((m_seffID[1].value()))); } } void ButtonBase::onClick(bool clickDone) { if(m_onClick){ m_onClick(this, clickDone); } if(clickDone){ // press button } else{ if(m_seffID[2].has_value()){ g_sdlDevice->playSoundEffect(g_seffDB->retrieve((m_seffID[2].value()))); } } } void ButtonBase::onTrigger() { if(m_onTrigger){ m_onTrigger(this); } } void ButtonBase::onBadEvent() { }
412
0.969545
1
0.969545
game-dev
MEDIA
0.775843
game-dev
0.992985
1
0.992985
evroon/bracket
2,994
backend/bracket/models/db/stage_item_inputs.py
from decimal import Decimal from pydantic import BaseModel, Field from bracket.models.db.shared import BaseModelORM from bracket.models.db.team import Team from bracket.utils.id_types import StageItemId, StageItemInputId, TeamId, TournamentId class StageItemInputBase(BaseModelORM): id: StageItemInputId slot: int tournament_id: TournamentId stage_item_id: StageItemId | None = None class StageItemInputGeneric(BaseModel): team_id: TeamId | None = None winner_from_stage_item_id: StageItemId | None = None winner_position: int | None = None points: Decimal = Decimal("0.0") wins: int = 0 draws: int = 0 losses: int = 0 @property def elo(self) -> Decimal: """ For now, ELO is saved as points. """ return self.points def __hash__(self) -> int: return ( self.team_id, self.winner_from_stage_item_id, self.winner_position, ).__hash__() class StageItemInputTentative(StageItemInputBase, StageItemInputGeneric): team_id: None = None winner_from_stage_item_id: StageItemId winner_position: int = Field(ge=1) def get_lookup_key(self) -> tuple[StageItemId, int]: return self.winner_from_stage_item_id, self.winner_position class StageItemInputFinal(StageItemInputBase, StageItemInputGeneric): team_id: TeamId team: Team class StageItemInputEmpty(StageItemInputBase, StageItemInputGeneric): team_id: None = None winner_from_stage_item_id: None = None winner_position: None = None StageItemInput = StageItemInputTentative | StageItemInputFinal | StageItemInputEmpty class StageItemInputCreateBodyTentative(BaseModel): slot: int winner_from_stage_item_id: StageItemId winner_position: int = Field(ge=1) class StageItemInputCreateBodyFinal(BaseModel): slot: int team_id: TeamId class StageItemInputCreateBodyEmpty(BaseModel): slot: int StageItemInputCreateBody = ( StageItemInputCreateBodyTentative | StageItemInputCreateBodyFinal | StageItemInputCreateBodyEmpty ) class StageItemInputUpdateBodyTentative(BaseModelORM): winner_from_stage_item_id: StageItemId winner_position: int = Field(ge=1) class StageItemInputUpdateBodyFinal(BaseModelORM): team_id: TeamId class StageItemInputUpdateBodyEmpty(BaseModelORM): team_id: None = None winner_from_stage_item_id: None = None winner_position: None = None StageItemInputUpdateBody = ( StageItemInputUpdateBodyTentative | StageItemInputUpdateBodyFinal | StageItemInputUpdateBodyEmpty ) class StageItemInputInsertable(BaseModel): slot: int team_id: TeamId | None = None tournament_id: TournamentId stage_item_id: StageItemId class StageItemInputOptionFinal(BaseModel): team_id: TeamId already_taken: bool class StageItemInputOptionTentative(BaseModel): winner_from_stage_item_id: StageItemId winner_position: int already_taken: bool
412
0.628926
1
0.628926
game-dev
MEDIA
0.366957
game-dev
0.856151
1
0.856151
JaylyDev/ScriptAPI
1,682
scripts/vector3-polyfill/tests.ts
import { Location, BlockAreaSize, BlockLocation, Vector, Vector3 } from './index'; const location = new Location(0, 0, 0); location.equals(location); location.isNear(location, 4); const blockAreaSize = new BlockAreaSize(0, 0, 0); blockAreaSize.equals(blockAreaSize); const blockLocation = new BlockLocation(0, 0, 0); blockLocation.above(); blockLocation.blocksBetween(new BlockLocation(10, 20, 30)); blockLocation.equals(blockLocation); blockLocation.offset(10, 20, 30); const vector = new Vector(0, 0, 0); vector.equals(new Vector(10, 20, 30)); vector.length(); vector.lengthSquared(); vector.normalized(); const back = Vector3.back; const down = Vector3.down; const forward = Vector3.forward; const left = Vector3.left; const one = Vector3.one; const right = Vector3.right; const up = Vector3.up; const zero = Vector3.zero; const add = Vector3.add(Vector3.left, Vector3.right); const cross = Vector3.cross(new Vector3(6, 4, 8), new Vector3(7, 5, -3)); const distance = Vector3.distance(new Vector3(3, 4, 5), new Vector3(6, 7, 8)); const divide = Vector3.divide(new Vector3(5, 5, 5), new Vector3(2, 3, 4)); const divide2 = Vector3.divide(new Vector3(5, 5, 5), 4);3 const lerp = Vector3.lerp(new Vector3(5, 5, 5), new Vector3(5, 5, 15), 1); const max = Vector3.max(new Vector3(5, 5, 5), new Vector3(4, 5, 5)); const min = Vector3.min(new Vector3(4, 5, 5), new Vector3(5, 5, 5)); const multiply = Vector3.multiply(new Vector3(5, 5, 5), new Vector3(2, 3, 4)); const multiply2 = Vector3.multiply(new Vector3(5, 5, 5), 5);3 const slerp = Vector3.slerp(new Vector3(1, 0, 0), new Vector3(0, 1, 1), 0.5); const subtract = Vector3.subtract(new Vector3(5, 5, 5), new Vector3(5, 5, 5));
412
0.677
1
0.677
game-dev
MEDIA
0.742173
game-dev
0.696778
1
0.696778
Community-Toolkit-for-Fluent-UI-Blazor/fluentui-blazor-community-extensions
4,254
tests/FluentUI.Blazor.Community.Components.Tests/Components/Animations/AnimationGroupTests.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Bunit; using FluentUI.Blazor.Community.Animations; using Microsoft.FluentUI.AspNetCore.Components.Tests; using Moq; namespace FluentUI.Blazor.Community.Components.Tests.Components.Animations; public class AnimationGroupTests : TestBase { public AnimationGroupTests() { JSInterop.Mode = JSRuntimeMode.Loose; } [Fact] public void AddElement_ShouldAddAnimatedElement() { var cut = RenderComponent<AnimationGroup>(p => { p.AddChildContent<AnimationItem>(); }); Assert.Single(cut.Instance.AnimatedElementGroup.AnimatedElements); } [Fact] public void RemoveElement_ShouldRemoveAnimatedElement() { var cut = RenderComponent<AnimationGroup>(p => { p.AddChildContent<AnimationItem>(); }); var item = cut.FindComponent<AnimationItem>(); item.Instance.Dispose(); Assert.Empty(cut.Instance.AnimatedElementGroup.AnimatedElements); } [Fact] public void RemoveLayout_ShouldSetLayoutStrategyToNull() { var group = new AnimationGroup(); var layoutMock = new Mock<ILayoutStrategy>(); group.SetLayout(layoutMock.Object); group.RemoveLayout(); Assert.Null(group.AnimatedElementGroup.LayoutStrategy); } [Fact] public void SetLayout_ShouldSetLayoutStrategy() { var group = new AnimationGroup(); var layoutMock = new Mock<ILayoutStrategy>(); group.SetLayout(layoutMock.Object); Assert.Equal(layoutMock.Object, group.AnimatedElementGroup.LayoutStrategy); } [Fact] public void ApplyLayout_ShouldCallApplyLayoutOnGroup() { var cut = RenderComponent<AnimationGroup>(p => { }); var newLayout = new StackedRotatingLayout(); cut.Instance.ApplyLayout(newLayout); Assert.Equal(newLayout, cut.Instance.AnimatedElementGroup.LayoutStrategy); } [Fact] public void ApplyLayout_DoesNothingOnGroup_WhenGroupHasLayout() { var cut = RenderComponent<AnimationGroup>(p => { p.Add(x=>x.Layout, builder => { builder.OpenComponent(0, typeof(StackedRotatingLayout)); builder.CloseComponent(); }); }); var newLayout = new BindStackLayout(); cut.Instance.ApplyLayout(newLayout); Assert.NotNull(cut.Instance.AnimatedElementGroup.LayoutStrategy); Assert.Equal(typeof(StackedRotatingLayout), cut.Instance.AnimatedElementGroup.LayoutStrategy.GetType()); } [Fact] public void ApplyStartTime_ShouldCallApplyStartTimeOnLayoutStrategy() { var group = new AnimationGroup(); var layoutMock = new Mock<ILayoutStrategy>(); group.SetLayout(layoutMock.Object); var now = DateTime.Now; group.ApplyStartTime(now); layoutMock.Verify(l => l.ApplyStartTime(now), Times.Once); } [Fact] public void SetMaxDisplayedItems_ShouldSetMaxDisplayedItemsOnGroup() { var cut = RenderComponent<AnimationGroup>(p => { p.Add(x => x.MaxDisplayedItems, 5); }); cut.Instance.SetMaxDisplayedItems(10); Assert.Equal(5, cut.Instance.MaxDisplayedItems); } [Fact] public async Task Dispose_ShouldCallParentRemoveGroup_AndSuppressFinalize() { var cut = RenderComponent<FluentCxAnimation>( p => p.AddChildContent<AnimationGroup>() ); var group = cut.FindComponent<AnimationGroup>(); Assert.NotNull(group); group.Instance.Dispose(); var fieldInstance = typeof(FluentCxAnimation).GetField("_animationEngine", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance) .GetValue(cut.Instance) as AnimationEngine; var groupsField = typeof(AnimationEngine).GetField("_groups", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var groups = groupsField.GetValue(fieldInstance) as List<AnimatedElementGroup>; Assert.Empty(groups); } }
412
0.630896
1
0.630896
game-dev
MEDIA
0.648729
game-dev
0.804846
1
0.804846
Simply-Love/Simply-Love-SM5
1,957
BGAnimations/ScreenCRTTestPatterns underlay/default.lua
local patterns = { {name=Screen.String("SMPTEColorBars"), file="smpte-color-bars.gif"}, {name=Screen.String("Convergence"), file="convergence.gif"}, {name=Screen.String("Gamma"), file="gamma.jpg"}, {name=Screen.String("AspectRatio"), file="aspect-ratio.jpg"}, } local idx = 1 local function InputHandler(event) if event.type == "InputEventType_FirstPress" then if event.GameButton == "Back" or event.GameButton == "Start" then SCREENMAN:GetTopScreen():Cancel() elseif event.GameButton == "MenuLeft" then idx = (idx-2) % #patterns + 1 SCREENMAN:GetTopScreen():queuecommand("IndexChanged") elseif event.GameButton == "MenuRight" then idx = (idx % #patterns) + 1 SCREENMAN:GetTopScreen():queuecommand("IndexChanged") end end end return Def.ActorFrame{ OnCommand=function(self) SCREENMAN:GetTopScreen():AddInputCallback(InputHandler) self:queuecommand("IndexChanged") end, Def.Sprite { InitCommand=function(self) self:FullScreen() end, IndexChangedCommand=function(self) self:Load(THEME:GetPathB("ScreenCRTTestPatterns", "underlay/patterns/"..patterns[idx].file)) self:FullScreen() end, }, Def.ActorFrame{ InitCommand=function(self) self:diffusealpha(0) end, IndexChangedCommand=function(self) self:finishtweening() self:linear(0.15):diffusealpha(1) self:sleep(2):linear(0.15):diffusealpha(0) end, Def.Quad{ InitCommand=function(self) self:xy(_screen.cx, _screen.cy) self:zoomto(_screen.w, 100) self:diffuse(Color.Black):diffusealpha(0.8) end }, LoadFont("Common Bold")..{ InitCommand=function(self) self:diffuse(Color.White) self:xy(_screen.cx, _screen.cy - 15) end, IndexChangedCommand=function(self) self:settext(patterns[idx].name) end, }, LoadFont("Common Normal")..{ Text=Screen.String("Usage"), InitCommand=function(self) self:diffuse(Color.White) self:xy(_screen.cx, _screen.cy + 25) end, }, }, }
412
0.720302
1
0.720302
game-dev
MEDIA
0.625818
game-dev,desktop-app
0.905217
1
0.905217
kierstone/Buff-In-TopDownShooter
6,914
Library/PackageCache/com.unity.timeline@1.4.8/Editor/Window/TimelineMarkerHeaderGUI.cs
using System; using System.Linq; using UnityEditor.Timeline.Actions; using UnityEngine; using UnityEngine.Timeline; using Object = UnityEngine.Object; namespace UnityEditor.Timeline { class TimelineMarkerHeaderGUI : IRowGUI, ILayerable { int m_TrackHash; TimelineAsset timeline { get; } WindowState state { get; } MarkersLayer m_Layer; LayerZOrder m_ZOrder = new LayerZOrder(Layer.MarkerHeaderTrack, 0); struct DrawData { public Rect headerRect; public Rect contentRect; public GUIStyle trackHeaderFont; public Color colorTrackFont; public bool showLockButton; public bool showMuteButton; } public TimelineMarkerHeaderGUI(TimelineAsset asset, WindowState state) { m_TrackHash = -1; timeline = asset; this.state = state; } public TrackAsset asset { get { return timeline.markerTrack; } } public Rect boundingRect { get; private set; } public bool locked { get { return !state.showMarkerHeader; } } public bool showMarkers { get { return state.showMarkerHeader; } } public bool muted { get { return timeline.markerTrack != null && timeline.markerTrack.muted; } } Rect IRowGUI.ToWindowSpace(Rect rect) { //header gui is already in global coordinates return rect; } public void Draw(Rect markerHeaderRect, Rect markerContentRect, WindowState state) { boundingRect = markerContentRect; var data = new DrawData() { headerRect = markerHeaderRect, contentRect = markerContentRect, trackHeaderFont = DirectorStyles.Instance.trackHeaderFont, colorTrackFont = DirectorStyles.Instance.customSkin.colorTrackFont, showLockButton = locked, showMuteButton = muted }; if (state.showMarkerHeader) { DrawMarkerDrawer(data, state); if (Event.current.type == EventType.Repaint) state.spacePartitioner.AddBounds(this, boundingRect); } if (asset != null && Hash() != m_TrackHash) Rebuild(); var rect = state.showMarkerHeader ? markerContentRect : state.timeAreaRect; using (new GUIViewportScope(rect)) { if (m_Layer != null) m_Layer.Draw(rect, state); HandleDragAndDrop(); } } public void Rebuild() { if (asset == null) return; m_Layer = new MarkersLayer(Layer.MarkersOnHeader, this); m_TrackHash = Hash(); } void HandleDragAndDrop() { if (TimelineWindow.instance.state.editSequence.isReadOnly) return; if (Event.current == null || Event.current.type != EventType.DragUpdated && Event.current.type != EventType.DragPerform && Event.current.type != EventType.DragExited) return; timeline.CreateMarkerTrack(); // Ensure Marker track is created. var objectsBeingDropped = DragAndDrop.objectReferences.OfType<Object>(); var candidateTime = TimelineHelpers.GetCandidateTime(Event.current.mousePosition); var perform = Event.current.type == EventType.DragPerform; var director = state.editSequence != null ? state.editSequence.director : null; DragAndDrop.visualMode = TimelineDragging.HandleClipPaneObjectDragAndDrop(objectsBeingDropped, timeline.markerTrack, perform, timeline, null, director, candidateTime, TimelineDragging.ResolveType); if (perform && DragAndDrop.visualMode == DragAndDropVisualMode.Copy) { DragAndDrop.AcceptDrag(); } } int Hash() { return timeline.markerTrack == null ? 0 : timeline.markerTrack.Hash(); } static void DrawMarkerDrawer(DrawData data, WindowState state) { DrawMarkerDrawerHeaderBackground(data); DrawMarkerDrawerHeader(data, state); DrawMarkerDrawerContentBackground(data); } static void DrawMarkerDrawerHeaderBackground(DrawData data) { var backgroundColor = DirectorStyles.Instance.customSkin.markerHeaderDrawerBackgroundColor; var bgRect = data.headerRect; EditorGUI.DrawRect(bgRect, backgroundColor); } static void DrawMarkerDrawerHeader(DrawData data, WindowState state) { var textStyle = data.trackHeaderFont; textStyle.normal.textColor = data.colorTrackFont; var labelRect = data.headerRect; labelRect.x += DirectorStyles.kBaseIndent; EditorGUI.LabelField(labelRect, DirectorStyles.timelineMarkerTrackHeader); const float buttonSize = WindowConstants.trackHeaderButtonSize; const float padding = WindowConstants.trackHeaderButtonPadding; var x = data.headerRect.xMax - buttonSize - padding - 2f; var y = data.headerRect.y + (data.headerRect.height - buttonSize) / 2.0f; var buttonRect = new Rect(x, y, buttonSize, buttonSize); DrawTrackDropDownMenu(buttonRect, state); buttonRect.x -= 16.0f; if (data.showMuteButton) { DrawMuteButton(buttonRect); buttonRect.x -= 16.0f; } if (data.showLockButton) { DrawLockButton(buttonRect); } } static void DrawMarkerDrawerContentBackground(DrawData data) { var trackBackgroundColor = DirectorStyles.Instance.customSkin.markerDrawerBackgroundColor; EditorGUI.DrawRect(data.contentRect, trackBackgroundColor); } static void DrawLockButton(Rect rect) { if (GUI.Button(rect, GUIContent.none, TimelineWindow.styles.trackLockButton)) Invoker.InvokeWithSelected<ToggleShowMarkersOnTimeline>(); } static void DrawTrackDropDownMenu(Rect rect, WindowState state) { if (GUI.Button(rect, GUIContent.none, DirectorStyles.Instance.trackOptions)) SequencerContextMenu.ShowMarkerHeaderContextMenu(null, state); } static void DrawMuteButton(Rect rect) { if (GUI.Button(rect, GUIContent.none, TimelineWindow.styles.markerHeaderMuteButton)) Invoker.InvokeWithSelected<ToggleMuteMarkersOnTimeline>(); } public LayerZOrder zOrder => m_ZOrder; } }
412
0.915685
1
0.915685
game-dev
MEDIA
0.494475
game-dev
0.985331
1
0.985331
v3921358/MapleRoot
2,475
MapleRoot/scripts/event/GuardianNex.js
var minPlayers = 1; var timeLimit = 15; //15 minutes var eventTimer = 1000 * 60 * timeLimit; var exitMap = 240070000; var eventMap = 240070010; var eventBossIds = [7120100, 7120101, 7120102, 8120100, 8120101, 8140510]; function init() {} function setup(difficulty, lobbyId) { var eim = em.newInstance("Nex_" + lobbyId); eim.setIntProperty("nex", lobbyId); eim.getInstanceMap(eventMap + 10 * lobbyId).resetFully(); eim.getInstanceMap(eventMap + 10 * lobbyId).allowSummonState(false); respawn(eim); eim.startEventTimer(eventTimer); return eim; } function afterSetup(eim) {} function respawn(eim) {} function playerEntry(eim, player) { var cave = eim.getMapInstance(eventMap + 10 * eim.getIntProperty("nex")); player.changeMap(cave, 1); } function scheduledTimeout(eim) { var party = eim.getPlayers(); for (var i = 0; i < party.size(); i++) { playerExit(eim, party.get(i)); } eim.dispose(); } function playerRevive(eim, player) { player.respawn(eim, exitMap); return false; } function playerDead(eim, player) {} function playerDisconnected(eim, player) { if (eim.isEventTeamLackingNow(true, minPlayers, player)) { eim.unregisterPlayer(player); end(eim); } else { eim.unregisterPlayer(player); } } function monsterValue(eim, mobId) { return -1; } function end(eim) { var party = eim.getPlayers(); for (var i = 0; i < party.size(); i++) { playerExit(eim, party.get(i)); } eim.dispose(); } function leftParty(eim, player) {} function disbandParty(eim) {} function playerUnregistered(eim, player) {} function playerExit(eim, player) { eim.unregisterPlayer(player); player.changeMap(exitMap); } function changedMap(eim, player, mapid) { if (mapid != (eventMap + 10 * eim.getIntProperty("nex"))) { if (eim.isEventTeamLackingNow(true, minPlayers, player)) { eim.unregisterPlayer(player); end(eim); } else { eim.unregisterPlayer(player); } } } function cancelSchedule() {} function dispose() {} function clearPQ(eim) { eim.stopEventTimer(); eim.setEventCleared(); } function monsterKilled(mob, eim) { if (mob.getId() == eventBossIds[eim.getIntProperty("nex")]) { eim.showClearEffect(); eim.clearPQ(); } } function allMonstersDead(eim) {} // ---------- FILLER FUNCTIONS ---------- function changedLeader(eim, leader) {}
412
0.653916
1
0.653916
game-dev
MEDIA
0.962031
game-dev
0.925932
1
0.925932
kitodo/kitodo-production
2,528
Kitodo/src/main/java/org/kitodo/production/helper/metadata/legacytypeimplementations/LegacyFileSetDocStructHelper.java
/* * (c) Kitodo. Key to digital objects e. V. <contact@kitodo.org> * * This file is part of the Kitodo project. * * It is licensed under GNU General Public License version 3 or later. * * For the full copyright and license information, please read the * GPL3-License.txt file that was distributed with this source code. */ package org.kitodo.production.helper.metadata.legacytypeimplementations; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.kitodo.api.dataformat.PhysicalDivision; /** * Connects a legacy file set its corresponding doc struct to a physical divisions * list. This is a soldering class to keep legacy code operational which is * about to be removed. Do not use this class. */ public class LegacyFileSetDocStructHelper implements LegacyDocStructHelperInterface { /** * The physical divisions list accessed via this soldering class. */ private List<PhysicalDivision> physicalDivisions; @Deprecated public LegacyFileSetDocStructHelper(List<PhysicalDivision> physicalDivisions) { this.physicalDivisions = physicalDivisions; } @Override @Deprecated public void addMetadata(LegacyMetadataHelper metadata) { /* * Legacy code tries to add (empty) metadata entries here. I guess this * is a bug. */ } @Override @Deprecated public List<LegacyDocStructHelperInterface> getAllChildren() { List<LegacyDocStructHelperInterface> allChildren = new ArrayList<>(physicalDivisions.size()); for (PhysicalDivision physicalDivision : physicalDivisions) { allChildren.add(new LegacyInnerPhysicalDocStructHelper(physicalDivision)); } return allChildren; } @Override @Deprecated public List<LegacyDocStructHelperInterface> getAllChildrenByTypeAndMetadataType(String page, String asterisk) { List<LegacyDocStructHelperInterface> allChildren = new ArrayList<>(physicalDivisions.size()); for (PhysicalDivision physicalDivision : physicalDivisions) { allChildren.add(new LegacyInnerPhysicalDocStructHelper(physicalDivision)); } return allChildren; } @Override @Deprecated public List<LegacyMetadataHelper> getAllMetadata() { return Collections.emptyList(); } @Override @Deprecated public List<LegacyMetadataHelper> getAllMetadataByType(LegacyMetadataTypeHelper metadataType) { return Collections.emptyList(); } }
412
0.633244
1
0.633244
game-dev
MEDIA
0.514271
game-dev
0.804543
1
0.804543
Ravenbrook/mlworks
4,050
app_tests/lego/lambda/full/drop.l
(* * Copyright 2013 Ravenbrook Limited <http://www.ravenbrook.com/>. * 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. * * 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. * * $Log: drop.l,v $ * Revision 1.1 1998/08/06 10:36:11 jont * new unit * Lego test application * * *) Forget deb_occurs; (* new stuff *) (* A function to say if a debruijn occurs *) Goal {e:exp}{n:NN}BB; Refine exp_elim([e:exp]{n:NN}BB)([el:explist]{n:NN}BB); intros;Refine ff; intros n m; Refine neq n m; intros;Refine orr (f_ih n) (arg_ih n); intros;Refine body_ih(S n); intros;[newlen = add (el_length fl) n]; Refine orr (fl_ih (S newlen)) (body_ih newlen); intros;Refine arg_ih n; intros;Refine vl_ih n; intros;Refine ff; intros;Refine orr (car_ih n) (cdr_ih n); Save deb_occurs; Goal {e:exp}{n:NN}exp; Refine exp_elim ([_:exp]{n:NN}exp) ([_:explist]{n:NN}explist); intros;Refine num n; intros;Refine tt_or_ff (lt v n); intros;Refine var v; intros;Refine var (pred v); intros;Refine app (f_ih n) (arg_ih n); intros;Refine fn (body_ih (S n)); intros;[newlen = add (el_length fl) n]; Refine letrec (fl_ih (S newlen)) (body_ih newlen); intros;Refine bopapp b (arg_ih n); intros;Refine mktuple (vl_ih n); intros;Refine expnil; intros;Refine expcons (car_ih n) (cdr_ih n); Save drop; Goal {l,m|NN}(is_tt (lt m l)) -> Q (drop (var m) l) (var m); Intros ___;Normal;Intros;Qrepl H;Refine Q_refl; Save drop_thm_lt; Goal {l,m|NN}(is_ff (lt m l)) -> Q (drop (var m) l) (var (pred m)); Intros ___;Normal;Intros;Qrepl H;Refine Q_refl; Save drop_thm_ge; [liftaux_drop_thm : {e:exp}{n:NN} (is_ff (deb_occurs e n)) -> Q (liftaux one (drop e n) n) e]; [drop_liftaux_thm : {e:exp}{n:NN} Q (drop (liftaux one e n) n) e]; Goal {e|exp} (is_ff (deb_occurs e Z)) -> {x:val} {ve1,ve2|val_env}(ve_equiv ve1 ve2)-> {s1,s2|state}(state_equiv s1 s2)-> {a,a':val}{s1',s2':state} (sem ve1 s1 (drop e Z) a s1') -> (sem (extend_ve x ve2) s2 e a' s2')-> and (equiv a a')(state_equiv s1' s2'); intros _____________; Qrepl (Q_sym (liftaux_drop_thm e Z H)); Qrepl drop_liftaux_thm (drop e Z) Z; intros; Refine lift_lemma H1 H2 (extend_ve x empty_ve) a a' s1' s2' H3 H4; Save drop_thm; Goal {ve:val_env}{s:state}{e1,e2:exp}{esafe:safe_no_update e2 ve} {nocc:is_ff (deb_occurs e1 Z)} {v1,v2:val}{s1,s2:state} {eval1: sem ve s (drop e1 Z) v1 s1} {eval2: sem ve s (app (fn e1) e2) v2 s2} and (equiv v1 v2)(state_equiv s1 s2); intros; Refine extract_app eval2;intros ____;Refine and3_elim;intros _; Refine extract_fn H;intros __; Qrepl H1;Qrepl H2;intros; Refine cut (apply_thm H4);intros; Refine drop_thm; Refine e1;Refine nocc;Refine s3;Refine ve;Refine ve;Refine ve_equiv_eq; Refine s;Refine s;Refine state_equiv_eq;Refine Q_refl; Refine eval1; Qrepl esafe H3; Refine H5; Save unused_elim_thm;
412
0.656414
1
0.656414
game-dev
MEDIA
0.199078
game-dev
0.654226
1
0.654226
MartinTheDragon/Nuclear-Tech-Mod-Remake
3,010
src/main/kotlin/at/martinthedragon/nucleartech/entity/NuclearCreeper.kt
package at.martinthedragon.nucleartech.entity import at.martinthedragon.nucleartech.api.explosion.Explosion import at.martinthedragon.nucleartech.api.explosion.NuclearExplosionMk4Params import at.martinthedragon.nucleartech.api.explosion.SmallNukeExplosionParams import at.martinthedragon.nucleartech.explosion.SmallNukeExplosion import at.martinthedragon.nucleartech.hazard.EntityContaminationEffects import at.martinthedragon.nucleartech.world.DamageSources import net.minecraft.world.damagesource.DamageSource import net.minecraft.world.entity.EntitySelector import net.minecraft.world.entity.EntityType import net.minecraft.world.entity.LivingEntity import net.minecraft.world.entity.ai.attributes.AttributeSupplier import net.minecraft.world.entity.ai.attributes.Attributes import net.minecraft.world.entity.monster.Creeper import net.minecraft.world.entity.monster.Monster import net.minecraft.world.level.Level import net.minecraft.world.phys.AABB import net.minecraftforge.event.ForgeEventFactory class NuclearCreeper( entityType: EntityType<out NuclearCreeper>, level: Level ) : Creeper(entityType, level) { // TODO achievement init { maxSwell = 75 } override fun tick() { for (entity in level.getEntities(this, AABB(blockPosition()).inflate(5.0), EntitySelector.LIVING_ENTITY_STILL_ALIVE)) { entity as LivingEntity EntityContaminationEffects.contaminate(entity, EntityContaminationEffects.HazardType.Radiation, EntityContaminationEffects.ContaminationType.Creative, 0.25F) } super.tick() if (health < maxHealth && tickCount % 10 == 0) { heal(1F) } } override fun hurt(source: DamageSource, amount: Float): Boolean { if (source == DamageSources.radiation) { // TODO mud also heals heal(amount) return false } return super.hurt(source, amount) } override fun explodeCreeper() { if (!level.isClientSide) { discard() val grief = ForgeEventFactory.getMobGriefingEvent(level, this) if (isPowered) { SmallNukeExplosion.createAndStart(level, position(), 0F, SmallNukeExplosionParams( damageRadius = if (grief) 0 else 100, shrapnel = false, actualExplosion = { level, pos, _, _ -> if (grief) NukeExplosion.create(level, pos, 100F, NuclearExplosionMk4Params(muted = true)) else Explosion { false } } // TODO strength config )) } else { SmallNukeExplosion.createAndStart(level, position(), 0F, if (grief) SmallNukeExplosion.MEDIUM else SmallNukeExplosion.SAFE) } } } override fun canDropMobsSkull() = false companion object { fun createAttributes(): AttributeSupplier = Monster.createMobAttributes() .add(Attributes.MAX_HEALTH, 50.0) .add(Attributes.MOVEMENT_SPEED, .3) .build() } }
412
0.888363
1
0.888363
game-dev
MEDIA
0.992015
game-dev
0.892291
1
0.892291
google/filament
4,179
third_party/dawn/third_party/dxc/tools/clang/test/DXC/dumpPSV_CS.hlsl
// REQUIRES: dxil-1-8 // RUN: %dxc -E main -T cs_6_8 %s -Fo %t // RUN: %dxa %t -dumppsv | FileCheck %s // CHECK: DxilPipelineStateValidation: // CHECK-NEXT: PSVRuntimeInfo: // CHECK-NEXT: Compute Shader // CHECK-NEXT: NumThreads=(128,1,1) // CHECK-NEXT: MinimumExpectedWaveLaneCount: 0 // CHECK-NEXT: MaximumExpectedWaveLaneCount: 4294967295 // CHECK-NEXT: UsesViewID: false // CHECK-NEXT: SigInputElements: 0 // CHECK-NEXT: SigOutputElements: 0 // CHECK-NEXT: SigPatchConstOrPrimElements: 0 // CHECK-NEXT: SigInputVectors: 0 // CHECK-NEXT: SigOutputVectors[0]: 0 // CHECK-NEXT: SigOutputVectors[1]: 0 // CHECK-NEXT: SigOutputVectors[2]: 0 // CHECK-NEXT: SigOutputVectors[3]: 0 // CHECK-NEXT: EntryFunctionName: main // CHECK-NEXT: ResourceCount : 3 // CHECK-NEXT: PSVResourceBindInfo: // CHECK-NEXT: Space: 0 // CHECK-NEXT: LowerBound: 0 // CHECK-NEXT: UpperBound: 0 // CHECK-NEXT: ResType: CBV // CHECK-NEXT: ResKind: CBuffer // CHECK-NEXT: ResFlags: None // CHECK-NEXT: PSVResourceBindInfo: // CHECK-NEXT: Space: 0 // CHECK-NEXT: LowerBound: 0 // CHECK-NEXT: UpperBound: 0 // CHECK-NEXT: ResType: SRVStructured // CHECK-NEXT: ResKind: StructuredBuffer // CHECK-NEXT: ResFlags: None // CHECK-NEXT: PSVResourceBindInfo: // CHECK-NEXT: Space: 0 // CHECK-NEXT: LowerBound: 0 // CHECK-NEXT: UpperBound: 0 // CHECK-NEXT: ResType: UAVStructured // CHECK-NEXT: ResKind: StructuredBuffer // CHECK-NEXT: ResFlags: None static float softeningSquared = 0.0012500000f * 0.0012500000f; static float g_fG = 6.67300e-11f * 10000.0f; static float g_fParticleMass = g_fG * 10000.0f * 10000.0f; #define blocksize 128 groupshared float4 sharedPos[blocksize]; void bodyBodyInteraction(inout float3 ai, float4 bj, float4 bi, float mass, int particles) { float3 r = bj.xyz - bi.xyz; float distSqr = dot(r, r); distSqr += softeningSquared; float invDist = 1.0f / sqrt(distSqr); float invDistCube = invDist * invDist * invDist; float s = mass * invDistCube * particles; ai += r * s; } cbuffer cbCS : register(b0) { uint4 g_param; // param[0] = MAX_PARTICLES; // param[1] = dimx; float4 g_paramf; // paramf[0] = 0.1f; // paramf[1] = 1; }; struct PosVelo { float4 pos; float4 velo; }; StructuredBuffer<PosVelo> oldPosVelo : register(t0); // SRV RWStructuredBuffer<PosVelo> newPosVelo : register(u0); // UAV [numthreads(blocksize, 1, 1)] void main(uint3 Gid : SV_GroupID, uint3 DTid : SV_DispatchThreadID, uint3 GTid : SV_GroupThreadID, uint GI : SV_GroupIndex) { // Each thread of the CS updates one of the particles. float4 pos = oldPosVelo[DTid.x].pos; float4 vel = oldPosVelo[DTid.x].velo; float3 accel = 0; float mass = g_fParticleMass; // Update current particle using all other particles. [loop] for (uint tile = 0; tile < g_param.y; tile++) { // Cache a tile of particles unto shared memory to increase IO efficiency. sharedPos[GI] = oldPosVelo[tile * blocksize + GI].pos; GroupMemoryBarrierWithGroupSync(); [unroll] for (uint counter = 0; counter < blocksize; counter += 8 ) { bodyBodyInteraction(accel, sharedPos[counter], pos, mass, 1); bodyBodyInteraction(accel, sharedPos[counter+1], pos, mass, 1); bodyBodyInteraction(accel, sharedPos[counter+2], pos, mass, 1); bodyBodyInteraction(accel, sharedPos[counter+3], pos, mass, 1); bodyBodyInteraction(accel, sharedPos[counter+4], pos, mass, 1); bodyBodyInteraction(accel, sharedPos[counter+5], pos, mass, 1); bodyBodyInteraction(accel, sharedPos[counter+6], pos, mass, 1); bodyBodyInteraction(accel, sharedPos[counter+7], pos, mass, 1); } GroupMemoryBarrierWithGroupSync(); } const int tooManyParticles = g_param.y * blocksize - g_param.x; bodyBodyInteraction(accel, float4(0, 0, 0, 0), pos, mass, -tooManyParticles); // Update the velocity and position of current particle using the // acceleration computed above. vel.xyz += accel.xyz * g_paramf.x; //deltaTime; vel.xyz *= g_paramf.y; //damping; pos.xyz += vel.xyz * g_paramf.x; //deltaTime; if (DTid.x < g_param.x) { newPosVelo[DTid.x].pos = pos; newPosVelo[DTid.x].velo = float4(vel.xyz, length(accel)); } }
412
0.828165
1
0.828165
game-dev
MEDIA
0.40173
game-dev
0.879789
1
0.879789
paulevsGitch/BetterNether
1,988
src/main/java/paulevs/betternether/world/structures/plants/StructureWall.java
package paulevs.betternether.world.structures.plants; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.level.ServerLevelAccessor; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.HorizontalDirectionalBlock; import net.minecraft.world.level.block.state.BlockState; import paulevs.betternether.BlocksHelper; import paulevs.betternether.world.structures.IStructure; import paulevs.betternether.world.structures.StructureGeneratorThreadContext; import java.util.Random; public class StructureWall implements IStructure { private static final Direction[] DIRECTIONS = HorizontalDirectionalBlock.FACING.getPossibleValues().toArray(new Direction[] {}); private static final Direction[] SHUFFLED = new Direction[DIRECTIONS.length]; private final Block plantBlock; public StructureWall(Block plantBlock) { this.plantBlock = plantBlock; } @Override public void generate(ServerLevelAccessor world, BlockPos pos, Random random, final int MAX_HEIGHT, StructureGeneratorThreadContext context) { if (world.isEmptyBlock(pos)) { BlockState state = getPlacementState(world, pos, random); if (state != null) BlocksHelper.setWithoutUpdate(world, pos, state); } } private BlockState getPlacementState(ServerLevelAccessor world, BlockPos pos, Random random) { BlockState blockState = plantBlock.defaultBlockState(); shuffle(random); for (int i = 0; i < 4; i++) { Direction direction = SHUFFLED[i]; Direction direction2 = direction.getOpposite(); blockState = blockState.setValue(HorizontalDirectionalBlock.FACING, direction2); if (blockState.canSurvive(world, pos)) { return blockState; } } return null; } private void shuffle(Random random) { for (int i = 0; i < 4; i++) SHUFFLED[i] = DIRECTIONS[i]; for (int i = 0; i < 4; i++) { int i2 = random.nextInt(4); Direction d = SHUFFLED[i2]; SHUFFLED[i2] = SHUFFLED[i]; SHUFFLED[i] = d; } } }
412
0.817604
1
0.817604
game-dev
MEDIA
0.992108
game-dev
0.919524
1
0.919524
magefree/mage
1,634
Mage/src/main/java/mage/abilities/effects/common/ReturnToHandFromBattlefieldAllEffect.java
package mage.abilities.effects.common; import java.util.HashSet; import java.util.Set; import mage.abilities.Ability; import mage.abilities.effects.OneShotEffect; import mage.cards.Card; import mage.constants.Outcome; import mage.constants.Zone; import mage.filter.FilterPermanent; import mage.game.Game; import mage.game.permanent.Permanent; import mage.players.Player; /** * @author Plopman */ public class ReturnToHandFromBattlefieldAllEffect extends OneShotEffect { private final FilterPermanent filter; public ReturnToHandFromBattlefieldAllEffect(FilterPermanent filter) { super(Outcome.ReturnToHand); this.filter = filter; staticText = "return all " + filter.getMessage() + " to their owners' hands"; } protected ReturnToHandFromBattlefieldAllEffect(final ReturnToHandFromBattlefieldAllEffect effect) { super(effect); this.filter = effect.filter; } @Override public boolean apply(Game game, Ability source) { Player controller = game.getPlayer(source.getControllerId()); if (controller != null) { Set<Card> permanentsToHand = new HashSet<>(); for (Permanent permanent : game.getBattlefield().getActivePermanents(filter, source.getControllerId(), source, game)) { permanentsToHand.add(permanent); } controller.moveCards(permanentsToHand, Zone.HAND, source, game); return true; } return false; } @Override public ReturnToHandFromBattlefieldAllEffect copy() { return new ReturnToHandFromBattlefieldAllEffect(this); } }
412
0.930899
1
0.930899
game-dev
MEDIA
0.900624
game-dev
0.98307
1
0.98307
ImLegiitXD/Dream-Advanced
3,710
dll/back/1.8.9/net/minecraft/block/BlockOre.java
package net.minecraft.block; import java.util.Random; import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.EnumDyeColor; import net.minecraft.item.Item; import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.world.World; public class BlockOre extends Block { public BlockOre() { this(Material.rock.getMaterialMapColor()); } public BlockOre(MapColor p_i46390_1_) { super(Material.rock, p_i46390_1_); this.setCreativeTab(CreativeTabs.tabBlock); } /** * Get the Item that this Block should drop when harvested. */ public Item getItemDropped(IBlockState state, Random rand, int fortune) { return this == Blocks.coal_ore ? Items.coal : (this == Blocks.diamond_ore ? Items.diamond : (this == Blocks.lapis_ore ? Items.dye : (this == Blocks.emerald_ore ? Items.emerald : (this == Blocks.quartz_ore ? Items.quartz : Item.getItemFromBlock(this))))); } /** * Returns the quantity of items to drop on block destruction. */ public int quantityDropped(Random random) { return this == Blocks.lapis_ore ? 4 + random.nextInt(5) : 1; } /** * Get the quantity dropped based on the given fortune level */ public int quantityDroppedWithBonus(int fortune, Random random) { if (fortune > 0 && Item.getItemFromBlock(this) != this.getItemDropped((IBlockState)this.getBlockState().getValidStates().iterator().next(), random, fortune)) { int i = random.nextInt(fortune + 2) - 1; if (i < 0) { i = 0; } return this.quantityDropped(random) * (i + 1); } else { return this.quantityDropped(random); } } /** * Spawns this Block's drops into the World as EntityItems. */ public void dropBlockAsItemWithChance(World worldIn, BlockPos pos, IBlockState state, float chance, int fortune) { super.dropBlockAsItemWithChance(worldIn, pos, state, chance, fortune); if (this.getItemDropped(state, worldIn.rand, fortune) != Item.getItemFromBlock(this)) { int i = 0; if (this == Blocks.coal_ore) { i = MathHelper.getRandomIntegerInRange(worldIn.rand, 0, 2); } else if (this == Blocks.diamond_ore) { i = MathHelper.getRandomIntegerInRange(worldIn.rand, 3, 7); } else if (this == Blocks.emerald_ore) { i = MathHelper.getRandomIntegerInRange(worldIn.rand, 3, 7); } else if (this == Blocks.lapis_ore) { i = MathHelper.getRandomIntegerInRange(worldIn.rand, 2, 5); } else if (this == Blocks.quartz_ore) { i = MathHelper.getRandomIntegerInRange(worldIn.rand, 2, 5); } this.dropXpOnBlockBreak(worldIn, pos, i); } } public int getDamageValue(World worldIn, BlockPos pos) { return 0; } /** * Gets the metadata of the item this Block can drop. This method is called when the block gets destroyed. It * returns the metadata of the dropped item based on the old metadata of the block. */ public int damageDropped(IBlockState state) { return this == Blocks.lapis_ore ? EnumDyeColor.BLUE.getDyeDamage() : 0; } }
412
0.786405
1
0.786405
game-dev
MEDIA
0.998509
game-dev
0.957776
1
0.957776
pablushaa/AllahClientRecode
5,609
net/minecraft/entity/ai/EntityAIFollowOwner.java
package net.minecraft.entity.ai; import net.minecraft.block.state.BlockFaceShape; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.passive.EntityTameable; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.pathfinding.PathNavigate; import net.minecraft.pathfinding.PathNavigateFlying; import net.minecraft.pathfinding.PathNavigateGround; import net.minecraft.pathfinding.PathNodeType; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.world.World; public class EntityAIFollowOwner extends EntityAIBase { private final EntityTameable thePet; private EntityLivingBase theOwner; World theWorld; private final double followSpeed; private final PathNavigate petPathfinder; private int timeToRecalcPath; float maxDist; float minDist; private float oldWaterCost; public EntityAIFollowOwner(EntityTameable thePetIn, double followSpeedIn, float minDistIn, float maxDistIn) { this.thePet = thePetIn; this.theWorld = thePetIn.world; this.followSpeed = followSpeedIn; this.petPathfinder = thePetIn.getNavigator(); this.minDist = minDistIn; this.maxDist = maxDistIn; this.setMutexBits(3); if (!(thePetIn.getNavigator() instanceof PathNavigateGround) && !(thePetIn.getNavigator() instanceof PathNavigateFlying)) { throw new IllegalArgumentException("Unsupported mob type for FollowOwnerGoal"); } } /** * Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { EntityLivingBase entitylivingbase = this.thePet.getOwner(); if (entitylivingbase == null) { return false; } else if (entitylivingbase instanceof EntityPlayer && ((EntityPlayer)entitylivingbase).isSpectator()) { return false; } else if (this.thePet.isSitting()) { return false; } else if (this.thePet.getDistanceSqToEntity(entitylivingbase) < (double)(this.minDist * this.minDist)) { return false; } else { this.theOwner = entitylivingbase; return true; } } /** * Returns whether an in-progress EntityAIBase should continue executing */ public boolean continueExecuting() { return !this.petPathfinder.noPath() && this.thePet.getDistanceSqToEntity(this.theOwner) > (double)(this.maxDist * this.maxDist) && !this.thePet.isSitting(); } /** * Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.timeToRecalcPath = 0; this.oldWaterCost = this.thePet.getPathPriority(PathNodeType.WATER); this.thePet.setPathPriority(PathNodeType.WATER, 0.0F); } /** * Resets the task */ public void resetTask() { this.theOwner = null; this.petPathfinder.clearPathEntity(); this.thePet.setPathPriority(PathNodeType.WATER, this.oldWaterCost); } /** * Updates the task */ public void updateTask() { this.thePet.getLookHelper().setLookPositionWithEntity(this.theOwner, 10.0F, (float)this.thePet.getVerticalFaceSpeed()); if (!this.thePet.isSitting()) { if (--this.timeToRecalcPath <= 0) { this.timeToRecalcPath = 10; if (!this.petPathfinder.tryMoveToEntityLiving(this.theOwner, this.followSpeed)) { if (!this.thePet.getLeashed() && !this.thePet.isRiding()) { if (this.thePet.getDistanceSqToEntity(this.theOwner) >= 144.0D) { int i = MathHelper.floor(this.theOwner.posX) - 2; int j = MathHelper.floor(this.theOwner.posZ) - 2; int k = MathHelper.floor(this.theOwner.getEntityBoundingBox().minY); for (int l = 0; l <= 4; ++l) { for (int i1 = 0; i1 <= 4; ++i1) { if ((l < 1 || i1 < 1 || l > 3 || i1 > 3) && this.func_192381_a(i, j, k, l, i1)) { this.thePet.setLocationAndAngles((double)((float)(i + l) + 0.5F), (double)k, (double)((float)(j + i1) + 0.5F), this.thePet.rotationYaw, this.thePet.rotationPitch); this.petPathfinder.clearPathEntity(); return; } } } } } } } } } protected boolean func_192381_a(int p_192381_1_, int p_192381_2_, int p_192381_3_, int p_192381_4_, int p_192381_5_) { BlockPos blockpos = new BlockPos(p_192381_1_ + p_192381_4_, p_192381_3_ - 1, p_192381_2_ + p_192381_5_); IBlockState iblockstate = this.theWorld.getBlockState(blockpos); return iblockstate.func_193401_d(this.theWorld, blockpos, EnumFacing.DOWN) == BlockFaceShape.SOLID && iblockstate.canEntitySpawn(this.thePet) && this.theWorld.isAirBlock(blockpos.up()) && this.theWorld.isAirBlock(blockpos.up(2)); } }
412
0.77651
1
0.77651
game-dev
MEDIA
0.970077
game-dev
0.934765
1
0.934765
FlameskyDexive/Legends-Of-Heroes
3,648
Unity/Assets/Scripts/Model/Generate/ClientServer/Config/BuffConfig.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 Bright.Serialization; using System.Collections.Generic; using System.Collections.Concurrent; using System; namespace ET { public sealed partial class BuffConfig: Bright.Config.BeanBase { public BuffConfig(ByteBuf _buf) { Id = _buf.ReadInt(); Name = _buf.ReadString(); Desc = _buf.ReadString(); {int n0 = System.Math.Min(_buf.ReadSize(), _buf.Size);StartEvents = new System.Collections.Generic.List<int>(n0);for(var i0 = 0 ; i0 < n0 ; i0++) { int _e0; _e0 = _buf.ReadInt(); StartEvents.Add(_e0);}} {int n0 = System.Math.Min(_buf.ReadSize(), _buf.Size);EndEvents = new System.Collections.Generic.List<int>(n0);for(var i0 = 0 ; i0 < n0 ; i0++) { int _e0; _e0 = _buf.ReadInt(); EndEvents.Add(_e0);}} Duration = _buf.ReadInt(); TriggerInterval = _buf.ReadInt(); {int n0 = System.Math.Min(_buf.ReadSize(), _buf.Size);TriggerEvents = new System.Collections.Generic.List<int>(n0);for(var i0 = 0 ; i0 < n0 ; i0++) { int _e0; _e0 = _buf.ReadInt(); TriggerEvents.Add(_e0);}} MaxLayer = _buf.ReadInt(); Goup = _buf.ReadInt(); PostInit(); } public static BuffConfig DeserializeBuffConfig(ByteBuf _buf) { return new BuffConfig(_buf); } /// <summary> /// buffID /// </summary> public int Id { get; private set; } /// <summary> /// 名称 /// </summary> public string Name { get; private set; } /// <summary> /// 备注 /// </summary> public string Desc { get; private set; } /// <summary> /// 开始事件 /// </summary> public System.Collections.Generic.List<int> StartEvents { get; private set; } /// <summary> /// 结束事件 /// </summary> public System.Collections.Generic.List<int> EndEvents { get; private set; } /// <summary> /// 持续时间 /// </summary> public int Duration { get; private set; } /// <summary> /// 触发间隔 /// </summary> public int TriggerInterval { get; private set; } /// <summary> /// 触发事件id /// </summary> public System.Collections.Generic.List<int> TriggerEvents { get; private set; } /// <summary> /// 最大叠加层数 /// </summary> public int MaxLayer { get; private set; } /// <summary> /// 分组 /// </summary> public int Goup { get; private set; } public const int __ID__ = -1370631787; public override int GetTypeId() => __ID__; public void Resolve(ConcurrentDictionary<Type, IConfigSingleton> _tables) { PostResolve(); } public void TranslateText(System.Func<string, string, string> translator) { } public override string ToString() { return "{ " + "Id:" + Id + "," + "Name:" + Name + "," + "Desc:" + Desc + "," + "StartEvents:" + Bright.Common.StringUtil.CollectionToString(StartEvents) + "," + "EndEvents:" + Bright.Common.StringUtil.CollectionToString(EndEvents) + "," + "Duration:" + Duration + "," + "TriggerInterval:" + TriggerInterval + "," + "TriggerEvents:" + Bright.Common.StringUtil.CollectionToString(TriggerEvents) + "," + "MaxLayer:" + MaxLayer + "," + "Goup:" + Goup + "," + "}"; } partial void PostInit(); partial void PostResolve(); } }
412
0.80161
1
0.80161
game-dev
MEDIA
0.756575
game-dev
0.792721
1
0.792721
2youyou2/physics-example
2,226
assets/cases/demo/one-side-platform.js
// http://www.iforce2d.net/b2dtut/one-way-walls cc.Class({ extends: cc.Component, properties: { }, onLoad: function () { this.pointVelPlatform = cc.v2(); this.pointVelOther = cc.v2(); this.relativeVel = cc.v2(); this.relativePoint = cc.v2(); }, onBeginContact: function (contact, selfCollider, otherCollider) { let cache = this._pointsCache; let otherBody = otherCollider.body; let platformBody = selfCollider.body; let worldManifold = contact.getWorldManifold(); let points = worldManifold.points; let pointVelPlatform = this.pointVelPlatform; let pointVelOther = this.pointVelOther; let relativeVel = this.relativeVel; let relativePoint = this.relativePoint; //check if contact points are moving into platform for (let i = 0; i < points.length; i++) { platformBody.getLinearVelocityFromWorldPoint( points[i], pointVelPlatform ); otherBody.getLinearVelocityFromWorldPoint( points[i], pointVelOther ); platformBody.getLocalVector( pointVelOther.subSelf(pointVelPlatform), relativeVel ); if ( relativeVel.y < -32 ) //if moving down faster than 32 pixel/s (1m/s), handle as before return; //point is moving into platform, leave contact solid and exit else if ( relativeVel.y < 32 ) { //if moving slower than 32 pixel/s (1m/s) //borderline case, moving only slightly out of platform platformBody.getLocalPoint( points[i], relativePoint ); let platformFaceY = selfCollider.getAABB().height / 2; //front of platform, should only used on a box collider if ( relativePoint.y > platformFaceY - 0.1*32 ) return; //contact point is less than 3.2pixel (10cm) inside front face of platfrom } else { //moving up faster than 1 m/s } } // store disabled state to contact contact.disabled = true; }, // called every frame, uncomment this function to activate update callback // update: function (dt) { // }, });
412
0.888782
1
0.888782
game-dev
MEDIA
0.629689
game-dev
0.754288
1
0.754288
auQuiksilver/Apex-Framework
4,672
Apex_framework.terrain/code/functions/fn_clientInteractCamoNet.sqf
/*/ File: fn_clientInteractCamoNet.sqf Author: Quiksilver Last Modified: 3/03/2018 A3 1.80 by Quiksilver Description: Vehicle Camo Nets _____________________________________________________________/*/ params ['_actionTarget','_actionCaller','_actionID','_actionArguments']; _actionArguments params ['_vehicle','_newPhase','_animationSources']; private _exitArmor = FALSE; _armor_anims = ['showslathull','showslatturret']; private _armor_vAnims = _vehicle getVariable ['QS_vehicle_slatarmorAnims',[]]; if (_armor_vAnims isEqualTo []) then { private _array = []; private _armorAnimationSources = (configOf _vehicle) >> 'animationSources'; private _animationSource = configNull; private _i = 0; for '_i' from 0 to ((count _armorAnimationSources) - 1) step 1 do { _animationSource = _armorAnimationSources select _i; if (((toLowerANSI (configName _animationSource)) in _armor_anims) || {(['showslat',(configName _animationSource),FALSE] call (missionNamespace getVariable 'QS_fnc_inString'))}) then { 0 = _array pushBack (toLowerANSI (configName _animationSource)); }; }; { if (_x isEqualType '') then { if (!((toLowerANSI _x) in _array)) then { if (((toLowerANSI _x) in _armor_anims) || {(['showslat',_x,FALSE] call (missionNamespace getVariable 'QS_fnc_inString'))}) then { _array pushBack (toLowerANSI _x); }; }; }; } forEach (getArray ((configOf _vehicle) >> 'animationList')); _vehicle setVariable ['QS_vehicle_slatarmorAnims',_array,FALSE]; _armor_vAnims = _array; }; if (_armor_vAnims isNotEqualTo []) then { if ((_armor_vAnims findIf {((_vehicle animationSourcePhase _x) isEqualTo 1)}) isNotEqualTo -1) then { _exitArmor = TRUE; }; }; if (_exitArmor) exitWith { 50 cutText [localize 'STR_QS_Text_082','PLAIN DOWN',0.5]; }; _onCancelled = { params ['_t','_position']; private _c = FALSE; if (!alive player) then {_c = TRUE;}; if (player isNotEqualTo (vehicle player)) then {_c = TRUE;}; if (!alive _t) then {_c = TRUE;}; if (!((vehicle player) isKindOf 'CAManBase')) then {_c = TRUE;}; if (!(_t in [cursorObject,cursorTarget])) then {_c = TRUE;}; if (((getPosATL player) distance2D _position) > 5) then {_c = TRUE;}; if (_c) then { missionNamespace setVariable ['QS_repairing_vehicle',FALSE,FALSE]; }; _c; }; _onCompleted = { params ['_actionTarget','_actionCaller','_actionID','_actionArguments']; _actionArguments params ['_vehicle','_newPhase','_animationSources']; private _exitArmor = FALSE; _armor_anims = ['showslathull','showslatturret']; private _armor_vAnims = _vehicle getVariable ['QS_vehicle_slatarmorAnims',[]]; if (_armor_vAnims isEqualTo []) then { private _array = []; private _armorAnimationSources = (configOf _vehicle) >> 'animationSources'; private _animationSource = configNull; private _i = 0; for '_i' from 0 to ((count _armorAnimationSources) - 1) step 1 do { _animationSource = _armorAnimationSources select _i; if (((toLowerANSI (configName _animationSource)) in _armor_anims) || {(['showslat',(configName _animationSource),FALSE] call (missionNamespace getVariable 'QS_fnc_inString'))}) then { 0 = _array pushBack (toLowerANSI (configName _animationSource)); }; }; { if (_x isEqualType '') then { if (!((toLowerANSI _x) in _array)) then { if (((toLowerANSI _x) in _armor_anims) || {(['showslat',_x,FALSE] call (missionNamespace getVariable 'QS_fnc_inString'))}) then { _array pushBack (toLowerANSI _x); }; }; }; } forEach (getArray ((configOf _vehicle) >> 'animationList')); _vehicle setVariable ['QS_vehicle_slatarmorAnims',_array,FALSE]; _armor_vAnims = _array; }; if (_armor_vAnims isNotEqualTo []) then { if ((_armor_vAnims findIf {((_vehicle animationSourcePhase _x) isEqualTo 1)}) isNotEqualTo -1) then { _exitArmor = TRUE; }; }; if (_exitArmor) exitWith { 50 cutText [localize 'STR_QS_Text_082','PLAIN DOWN',0.5]; }; { _vehicle animateSource [_x,_newPhase,TRUE]; } forEach _animationSources; if (_newPhase isEqualTo 1) then { 50 cutText [localize 'STR_QS_Text_083','PLAIN DOWN',0.333]; } else { 50 cutText [localize 'STR_QS_Text_084','PLAIN DOWN',0.333]; }; missionNamespace setVariable ['QS_repairing_vehicle',FALSE,FALSE]; }; missionNamespace setVariable ['QS_repairing_vehicle',TRUE,FALSE]; private _text = ''; if (_newPhase isEqualTo 1) then { _text = localize 'STR_QS_Menu_165'; } else { _text = localize 'STR_QS_Menu_166'; }; private _duration = 5; [ _text, _duration, 0, [[_vehicle],{FALSE}], [[_vehicle,(getPosATL _vehicle)],_onCancelled], [_this,_onCompleted], [[],{FALSE}] ] spawn (missionNamespace getVariable 'QS_fnc_clientProgressVisualization');
412
0.942133
1
0.942133
game-dev
MEDIA
0.991484
game-dev
0.956724
1
0.956724
MohistMC/Youer
3,398
patches/net/minecraft/world/level/block/piston/PistonStructureResolver.java.patch
--- a/net/minecraft/world/level/block/piston/PistonStructureResolver.java +++ b/net/minecraft/world/level/block/piston/PistonStructureResolver.java @@ -50,7 +_,7 @@ } else { for (int i = 0; i < this.toPush.size(); i++) { BlockPos blockpos = this.toPush.get(i); - if (isSticky(this.level.getBlockState(blockpos)) && !this.addBranchingBlocks(blockpos)) { + if (this.level.getBlockState(blockpos).isStickyBlock() && !this.addBranchingBlocks(blockpos)) { return false; } } @@ -59,18 +_,6 @@ } } - private static boolean isSticky(BlockState p_155938_) { - return p_155938_.is(Blocks.SLIME_BLOCK) || p_155938_.is(Blocks.HONEY_BLOCK); - } - - private static boolean canStickToEachOther(BlockState p_155940_, BlockState p_155941_) { - if (p_155940_.is(Blocks.HONEY_BLOCK) && p_155941_.is(Blocks.SLIME_BLOCK)) { - return false; - } else { - return p_155940_.is(Blocks.SLIME_BLOCK) && p_155941_.is(Blocks.HONEY_BLOCK) ? false : isSticky(p_155940_) || isSticky(p_155941_); - } - } - private boolean addBlockLine(BlockPos p_60434_, Direction p_60435_) { BlockState blockstate = this.level.getBlockState(p_60434_); if (blockstate.isAir()) { @@ -86,12 +_,13 @@ if (i + this.toPush.size() > 12) { return false; } else { - while (isSticky(blockstate)) { + BlockState oldState; + while(blockstate.isStickyBlock()) { BlockPos blockpos = p_60434_.relative(this.pushDirection.getOpposite(), i); - BlockState blockstate1 = blockstate; + oldState = blockstate; blockstate = this.level.getBlockState(blockpos); if (blockstate.isAir() - || !canStickToEachOther(blockstate1, blockstate) + || !(oldState.canStickTo(blockstate) && blockstate.canStickTo(oldState)) || !PistonBaseBlock.isPushable(blockstate, this.level, blockpos, this.pushDirection, false, this.pushDirection.getOpposite()) || blockpos.equals(this.pistonPos)) { break; @@ -119,7 +_,7 @@ for (int k = 0; k <= j + l; k++) { BlockPos blockpos2 = this.toPush.get(k); - if (isSticky(this.level.getBlockState(blockpos2)) && !this.addBranchingBlocks(blockpos2)) { + if (this.level.getBlockState(blockpos2).isStickyBlock() && !this.addBranchingBlocks(blockpos2)) { return false; } } @@ -174,7 +_,7 @@ if (direction.getAxis() != this.pushDirection.getAxis()) { BlockPos blockpos = p_60432_.relative(direction); BlockState blockstate1 = this.level.getBlockState(blockpos); - if (canStickToEachOther(blockstate1, blockstate) && !this.addBlockLine(blockpos, direction)) { + if (blockstate1.canStickTo(blockstate) && blockstate.canStickTo(blockstate1) && !this.addBlockLine(blockpos, direction)) { return false; } }
412
0.963751
1
0.963751
game-dev
MEDIA
0.87491
game-dev
0.966649
1
0.966649
dengzibiao/moba
5,689
Assets/Script/UI_Major/UIMoba/FlopPanel.cs
using UnityEngine; using UnityEngine.SceneManagement; using System.Collections.Generic; public class FlopPanel : MonoBehaviour { public GUISingleButton BtnFlopAll; public GUISingleButton BtnFightAgain; public GUISingleButton BtnOK; public UILabel AllPrice; public UILabel LaCoin; public UILabel LaMyDiamond; public UIGrid GdCards; public GameObject TitleEffect; FlopCardItem[] flopCardItems; List<FlopItem> flopItems = new List<FlopItem>(); public const int MAX_FLOP = 5; bool flopAnimPlaying; bool flopNoShow; long playerDiamond; int currentFlopCount = 1; FlopCardItem cardToFlop; void Start () { GameObject cardPrefab = Resources.Load<GameObject>(GameLibrary.PATH_UIPrefab + "FlopCardItem"); for(int k = 0; k < MAX_FLOP; k++) { NGUITools.AddChild(GdCards.gameObject, cardPrefab); } GdCards.Reposition(); flopCardItems = GetComponentsInChildren<FlopCardItem>(); for(int i = 0; i < flopCardItems.Length; i++) { flopCardItems[i].OnFlop += Flop; flopCardItems[i].OnFlopped += ( f ) => flopAnimPlaying = false; flopCardItems[i].RefreshPrice(0); } } public void Show( Dictionary<string, object> dict, string coinNum) { foreach(string k in dict.Keys) { Dictionary<string, object> itemData = (Dictionary<string, object>)dict[k]; FlopItem flopItem = new FlopItem(); flopItem.index = int.Parse(k); flopItem.itemId = int.Parse(itemData["id"].ToString()); flopItem.cost = int.Parse(itemData["cs"].ToString()); flopItem.num = int.Parse(itemData["at"].ToString()); flopItems.Add(flopItem); } flopItems.Sort((a,b)=> { return a.index - b.index; }); gameObject.SetActive(true); LaCoin.text = coinNum; BtnFlopAll.onClick = FlopAll; BtnOK.onClick = backScene; BtnFightAgain.onClick = backScene; TitleEffect.gameObject.SetActive(true); AllPrice.text = "" + GetAllCost(); playerDiamond = playerData.GetInstance().baginfo.diamond; LaMyDiamond.text = "" + playerDiamond; } void backScene() { if(currentFlopCount == 1) { flopNoShow = true; ClientSendDataMgr.GetSingle().GetMobaSend().SendFlopResult(new int[] { currentFlopCount }); } if (GameLibrary.isMoba) GameLibrary.isMoba = false; gameObject.SetActive(false); Time.timeScale = 1; GameLibrary.LastScene = SceneManager.GetActiveScene().name;//记录前一个场景名 StartLandingShuJu.GetInstance().GetLoadingData(GameLibrary.UI_Major, 3); SceneManager.LoadScene("Loding"); } public void Flopped ( int[] dn ) { if(flopNoShow) return; if(dn.Length > 1 || currentFlopCount == MAX_FLOP) { for(int j = 0; j < flopCardItems.Length; j++) { if(!flopCardItems[j].flopped) { DoFlop(flopCardItems[j]); } } } else { DoFlop(cardToFlop); } LaMyDiamond.text = "" + playerDiamond; if(currentFlopCount <= MAX_FLOP) { for(int i = 0; i < flopCardItems.Length; i++) { if(!flopCardItems[i].flopped) flopCardItems[i].RefreshPrice(flopItems[currentFlopCount - 1].cost); } AllPrice.text = "" + GetAllCost(); } else { BtnFlopAll.SetState(GUISingleButton.State.Disabled); AllPrice.text = "0"; } } void DoFlop (FlopCardItem card) { card.DoFlop(flopItems[currentFlopCount - 1]); playerDiamond -= flopItems[currentFlopCount - 1].cost; currentFlopCount++; } int GetAllCost () { int ret = 0; for(int i = currentFlopCount - 1; i<MAX_FLOP; i++) { ret += flopItems[i].cost; } return ret; } void Flop ( FlopCardItem flopCardItem ) { if(currentFlopCount <= MAX_FLOP) { if(playerDiamond < flopItems[currentFlopCount - 1].cost) { //UIPromptBox.Instance.ShowLabel("您的钻石不足"); Control.ShowGUI(UIPanleID.UIPromptBox, EnumOpenUIType.DefaultUIOrSecond, false, "您的钻石不足请充值"); } else { if(!flopAnimPlaying) flopAnimPlaying = true; else return; cardToFlop = flopCardItem; ClientSendDataMgr.GetSingle().GetMobaSend().SendFlopResult(new int[] { currentFlopCount }); } } } void FlopAll () { if(currentFlopCount <= MAX_FLOP) { if(playerDiamond < GetAllCost()) { //UIPromptBox.Instance.ShowLabel("您的钻石不足"); Control.ShowGUI(UIPanleID.UIPromptBox, EnumOpenUIType.DefaultUIOrSecond, false, "您的钻石不足请充值"); } else { if(!flopAnimPlaying) flopAnimPlaying = true; else return; int[] dn = new int[MAX_FLOP - currentFlopCount + 1]; for(int i = currentFlopCount; i <= MAX_FLOP; i++) { dn[i - currentFlopCount] = i; } ClientSendDataMgr.GetSingle().GetMobaSend().SendFlopResult(dn); } } } }
412
0.858288
1
0.858288
game-dev
MEDIA
0.868454
game-dev
0.967953
1
0.967953
CoatiSoftware/Sourcetrail
1,517
src/lib/utility/messaging/type/activation/MessageActivateTrail.h
#ifndef MESSAGE_ACTIVATE_TRAIL_H #define MESSAGE_ACTIVATE_TRAIL_H #include "Message.h" #include "MessageActivateBase.h" #include "NodeType.h" #include "TabId.h" #include "types.h" class MessageActivateTrail : public Message<MessageActivateTrail> , public MessageActivateBase { public: MessageActivateTrail( Id originId, Id targetId, Edge::TypeMask edgeTypes, size_t depth, bool horizontalLayout) : originId(originId) , targetId(targetId) , nodeTypes(0) , edgeTypes(edgeTypes) , nodeNonIndexed(false) , depth(depth) , horizontalLayout(horizontalLayout) , custom(false) { setSchedulerId(TabId::currentTab()); } MessageActivateTrail( Id originId, Id targetId, NodeKindMask nodeTypes, Edge::TypeMask edgeTypes, bool nodeNonIndexed, size_t depth, bool horizontalLayout) : originId(originId) , targetId(targetId) , nodeTypes(nodeTypes) , edgeTypes(edgeTypes) , nodeNonIndexed(nodeNonIndexed) , depth(depth) , horizontalLayout(horizontalLayout) , custom(true) { setSchedulerId(TabId::currentTab()); } static const std::string getStaticType() { return "MessageActivateTrail"; } std::vector<SearchMatch> getSearchMatches() const override { return searchMatches; } std::vector<SearchMatch> searchMatches; const Id originId; const Id targetId; const NodeKindMask nodeTypes; const Edge::TypeMask edgeTypes; const bool nodeNonIndexed; const size_t depth; const bool horizontalLayout; const bool custom; }; #endif // MESSAGE_ACTIVATE_TRAIL_H
412
0.94019
1
0.94019
game-dev
MEDIA
0.343423
game-dev
0.632067
1
0.632067
schuttejoe/Selas
6,398
Source/Core/ContainersLib/CArray.h
#pragma once //================================================================================================================================= // Joe Schutte //================================================================================================================================= #include "IoLib/Serializer.h" #include "SystemLib/MemoryAllocation.h" #include "SystemLib/Memory.h" #include "SystemLib/JsAssert.h" namespace Selas { enum ArrayFlags { eReadOnly = 0x01, eAttached = 0x02 }; template <typename Type_> class CArray { public: CArray(void); ~CArray(void); void Shutdown(void); void Clear(void); void Reserve(uint64 capacity); void Resize(uint64 length); const Type_* DataPointer(void) const { return _data; } Type_* DataPointer(void) { return _data; } inline Type_& operator[] (uint index) { return _data[index]; } inline const Type_& operator[] (uint index) const { return _data[index]; } inline uint64 Count(void) const { return _count; } inline uint64 Capacity(void) const { return _capacity; } inline uint64 DataSize(void) const { return _count * sizeof(Type_); } Type_& Add(void); uint64 Add(const Type_& element); template <typename OtherType_> void Append(const OtherType_& addend); bool Remove(const Type_& item); void RemoveFast(uint index); void Serialize(CSerializer* serializer); private: void ReallocateArray(uint64 newLength, uint64 newCapacity); void GrowArray(void); private: uint32 _flags; uint32 _padding; uint64 _count; uint64 _capacity; Type_* _data; }; template<typename Type_> CArray<Type_>::CArray(void) : _flags(0) , _padding(0) , _count(0) , _capacity(0) , _data(nullptr) { } template<typename Type_> CArray<Type_>::~CArray(void) { Shutdown(); } template<typename Type_> void CArray<Type_>::Shutdown(void) { if(((_flags & eAttached) == 0) && _data) { Free_(_data); } _data = nullptr; _count = 0; _capacity = 0; _flags = 0; } template<typename Type_> void CArray<Type_>::Clear(void) { _count = 0; } template<typename Type_> void CArray<Type_>::Reserve(uint64 capacity) { Assert_((_flags & eReadOnly) == 0); if(capacity > _capacity) { ReallocateArray(_count, capacity); } } template<typename Type_> void CArray<Type_>::Resize(uint64 length) { Assert_((_flags & eReadOnly) == 0); if(length > _capacity) { ReallocateArray(length, length); } else { _count = length; } } template<typename Type_> Type_& CArray<Type_>::Add(void) { Assert_((_flags & eReadOnly) == 0); if(_count == _capacity) { GrowArray(); } Assert_(_count < _capacity); uint64 index = _count++; return _data[index]; } template<typename Type_> uint64 CArray<Type_>::Add(const Type_& element) { Assert_((_flags & eReadOnly) == 0); if(_count == _capacity) { GrowArray(); } Assert_(_count < _capacity); _data[_count] = element; return _count++; } template<typename Type_> template<typename OtherType_> void CArray<Type_>::Append(const OtherType_& addend) { Assert_((_flags & eReadOnly) == 0); uint64 newLength = _count + addend.Count(); if(_capacity < newLength) ReallocateArray(_count, newLength); Memory::Copy(static_cast<Type_*>(_data) + _count, addend.DataPointer(), addend.DataSize()); _count = newLength; } template<typename Type_> bool CArray<Type_>::Remove(const Type_& item) { Assert_((_flags & eReadOnly) == 0); uint64 index = 0; for(; index < _count; ++index) { if(_data[index] == item) { break; } } if(index == _count) { return false; } for(; index < _count; ++index) { _data[index] = _data[index + 1]; } --_count; return true; } template<typename Type_> void CArray<Type_>::RemoveFast(uint index) { Assert_((_flags & eReadOnly) == 0); Assert_(index >= 0); Assert_(index < _count); _data[index] = _data[_count - 1]; _count--; } template<typename Type_> void CArray<Type_>::ReallocateArray(uint64 newLength, uint64 newCapacity) { Assert_((_flags & eReadOnly) == 0); Type_* newList = AllocArray_(Type_, newCapacity); if(_data) { uint64 lengthToCopy = (_count < newLength) ? _count : newLength; if(lengthToCopy > 0) { Memory::Copy(newList, _data, lengthToCopy * sizeof(Type_)); } Free_(_data); } _data = newList; _count = newLength; _capacity = newCapacity; } template<typename Type_> void CArray<Type_>::GrowArray(void) { Assert_((_flags & eReadOnly) == 0); // Idea from old BHG code; seems very sensible. if(_capacity < 64) { ReallocateArray(_count, _capacity + 16); } else if(_capacity < 256) { ReallocateArray(_count, _capacity + 32); } else { ReallocateArray(_count, _capacity + 128); } } template<typename Type_> void CArray<Type_>::Serialize(CSerializer* serializer) { serializer->Serialize(&_flags, sizeof(_flags)); serializer->Serialize(&_padding, sizeof(_padding)); serializer->Serialize(&_count, sizeof(_count)); serializer->Serialize(&_capacity, sizeof(_capacity)); serializer->SerializePtr((void*&)_data, DataSize(), 0); if(serializer->Flags() & eSerializerAttaching) { _flags = eReadOnly | eAttached; } } template<typename Type_> void Serialize(CSerializer* serializer, CArray<Type_>& data) { data.Serialize(serializer); } }
412
0.985929
1
0.985929
game-dev
MEDIA
0.265476
game-dev
0.983921
1
0.983921