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
d12/bricksvr-game
3,163
Assets/Scripts/ModularBrickObjects.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ModularBrickObjects : MonoBehaviour { private static ModularBrickObjects _instance; public static ModularBrickObjects GetInstance() { if (_instance == null) _instance = FindObjectOfType<ModularBrickObjects>(); return _instance; } private const int HollowBrick = 0; private const string HollowBrickNameInModel = "Body"; private const int SolidBrick = 1; private const string SolidBrickNameInModel = "FlatBody"; private const string StudNameInModel = "Studs"; private readonly Dictionary<string, GameObject> _namesToModularModels = new Dictionary<string, GameObject>(); private readonly Dictionary<(string, int), Mesh> _namesAndHollowToMesh = new Dictionary<(string, int), Mesh>(); private readonly Dictionary<string, Mesh> _namesToStudMeshes = new Dictionary<string, Mesh>(); private readonly Dictionary<(string, string), Vector3> _namesAndStudNamesToStudOffset = new Dictionary<(string, string), Vector3>(); public GameObject GetModularModel(string brickName) { if (!_namesToModularModels.ContainsKey(brickName)) _namesToModularModels.Add(brickName, transform.Find(brickName).gameObject); return _namesToModularModels[brickName]; } public Mesh GetHollowMesh(string brickName) { if (!_namesAndHollowToMesh.ContainsKey((brickName, HollowBrick))) { _namesAndHollowToMesh[(brickName, HollowBrick)] = GetModularModel(brickName).transform .Find(HollowBrickNameInModel).GetComponentInChildren<MeshFilter>().sharedMesh; } return _namesAndHollowToMesh[(brickName, HollowBrick)]; } public Mesh GetSolidMesh(string brickName) { if (!_namesAndHollowToMesh.ContainsKey((brickName, SolidBrick))) { _namesAndHollowToMesh[(brickName, SolidBrick)] = GetModularModel(brickName).transform.Find(SolidBrickNameInModel).GetComponentInChildren<MeshFilter>().sharedMesh; } return _namesAndHollowToMesh[(brickName, SolidBrick)]; } public Mesh GetStudMesh(string brickName) { if (!_namesToStudMeshes.ContainsKey(brickName)) { _namesToStudMeshes[brickName] = GetModularModel(brickName).transform .Find(StudNameInModel)?.GetComponentInChildren<MeshFilter>().sharedMesh; } return _namesToStudMeshes[brickName]; } public Vector3 GetStudOffsetFromCenter(string brickName, string studName) { if (!_namesAndStudNamesToStudOffset.ContainsKey((brickName, studName))) { Transform modularModel = GetModularModel(brickName).transform; Vector3 rootPos = modularModel.position; Vector3 studPos = _namesAndStudNamesToStudOffset[(brickName, studName)] = modularModel .Find(StudNameInModel).Find(studName).position; _namesAndStudNamesToStudOffset[(brickName, studName)] = rootPos - studPos; } return _namesAndStudNamesToStudOffset[(brickName, studName)]; } }
411
0.64844
1
0.64844
game-dev
MEDIA
0.828023
game-dev
0.756054
1
0.756054
ShokoAnime/ShokoServer
1,531
Shoko.Server/Filters/Info/HasTvDBLinkExpression.cs
using Shoko.Server.Filters.Interfaces; namespace Shoko.Server.Filters.Info; // TODO: REMOVE THIS FILTER EXPRESSION SOMETIME IN THE FUTURE AFTER THE LEGACY FILTERS ARE REMOVED!!1! public class HasTvDBLinkExpression : FilterExpression<bool> { public override bool TimeDependent => false; public override bool UserDependent => false; public override string Name => "Has TvDB Link"; public override string HelpDescription => "This condition passes if any of the anime have a TvDB link"; public override bool Deprecated => true; public override bool Evaluate(IFilterable filterable, IFilterableUserInfo userInfo) { return false; } protected bool Equals(HasTvDBLinkExpression other) { return base.Equals(other); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != this.GetType()) { return false; } return Equals((HasTvDBLinkExpression)obj); } public override int GetHashCode() { return GetType().FullName!.GetHashCode(); } public static bool operator ==(HasTvDBLinkExpression left, HasTvDBLinkExpression right) { return Equals(left, right); } public static bool operator !=(HasTvDBLinkExpression left, HasTvDBLinkExpression right) { return !Equals(left, right); } }
411
0.785058
1
0.785058
game-dev
MEDIA
0.197122
game-dev
0.683871
1
0.683871
jcs090218/JCSUnity
3,998
Assets/_Project/Scripts/Scripts/npc/npc2100.cs
/** * $File: npc2100.cs $ * $Date: $ * $Revision: $ * $Creator: Jen-Chieh Shen $ * $Notice: See LICENSE.txt for modification and distribution information * Copyright (c) 2016 by Shen, Jen-Chieh $ */ using UnityEngine; using MyBox; namespace JCSUnity { /// <summary> /// Example dialogue script. /// /// Here show the basic usage of the dialogue script system. /// </summary> [CreateAssetMenu(fileName = "npc2100", menuName = "Scriptable Objects/npc2100")] public class npc2100 : JCS_DialogueScript { /* Variables */ [Separator("Runtime Variables (npc2100)")] [Tooltip("Sprite visualize at the center.")] [SerializeField] private Sprite mCenterSprite = null; [Tooltip("Sprite visualize at the left.")] [SerializeField] private Sprite mLeftSprite = null; [Tooltip("Sprite visualize at the right.")] [SerializeField] private Sprite mRightSprite = null; /* Setter & Getter */ public Sprite CenterSprite { get { return this.mCenterSprite; } } public Sprite LeftSprite { get { return this.mLeftSprite; } } public Sprite RightSprite { get { return this.mRightSprite; } } /* Functions */ public override void Action(int mode, int type, int selection) { // if quest complete if (mode == -1) ds.Dispose(); if (Status == -1) { ds.SendNext("Hello World"); ds.SendNameTag("Name 01"); ds.SendLeftImage(LeftSprite); } else if (Status == 0) { /* For Mouse. */ { ds.SendNextPrev("Make a selection..."); } /* For Gamepad/Controller/Joystick. */ { //ds.SendEmpty("Make a selection..."); } //ds.SendChoice(0, "Selection 01"); ds.SendChoice(1, "Selection 02"); ds.SendChoice(2, "Selection 03"); ds.SendChoice(3, "Selection 04"); ds.SendChoice(4, "Selection 05"); ds.SendChoice(5, "Selection 06"); ds.SendNameTag("Name 02"); ds.SendRightImage(RightSprite); } else if (Status == 1) { string msg = "Error text..."; switch (selection) { case 1: msg = "You made selection 02."; break; case 2: msg = "You made selection 03."; break; case 3: msg = "You made selection 04."; break; case 4: msg = "You made selection 05."; break; case 5: msg = "You made selection 06."; break; default: // make selection 0 default msg = "You made selection 01."; break; } ds.SendNextPrev(msg); } else if (Status == 2) { ds.SendYesNo("..."); } else if (Status == 3) { string msg = "Default text"; switch (selection) { // Yes button clicked! case 1: msg = "You press Yes button!!! n(^O^)n"; break; // No button clicked~ case 0: msg = "You press No button!!! n(_ _)n"; break; } ds.SendOk(msg); } } } }
411
0.648585
1
0.648585
game-dev
MEDIA
0.365131
game-dev
0.720954
1
0.720954
jmorton06/Lumos
3,380
Lumos/External/box2d/src/shape.h
// SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "array.h" #include "box2d/types.h" typedef struct b2BroadPhase b2BroadPhase; typedef struct b2World b2World; typedef struct b2Shape { int id; int bodyId; int prevShapeId; int nextShapeId; int sensorIndex; b2ShapeType type; float density; float friction; float restitution; float rollingResistance; float tangentSpeed; int userMaterialId; b2AABB aabb; b2AABB fatAABB; b2Vec2 localCentroid; int proxyKey; b2Filter filter; void* userData; uint32_t customColor; union { b2Capsule capsule; b2Circle circle; b2Polygon polygon; b2Segment segment; b2ChainSegment chainSegment; }; uint16_t generation; bool enableSensorEvents; bool enableContactEvents; bool enableHitEvents; bool enablePreSolveEvents; bool enlargedAABB; } b2Shape; typedef struct b2ChainShape { int id; int bodyId; int nextChainId; int count; int materialCount; int* shapeIndices; b2SurfaceMaterial* materials; uint16_t generation; } b2ChainShape; typedef struct b2ShapeExtent { float minExtent; float maxExtent; } b2ShapeExtent; // Sensors are shapes that live in the broad-phase but never have contacts. // At the end of the time step all sensors are queried for overlap with any other shapes. // Sensors ignore body type and sleeping. // Sensors generate events when there is a new overlap or and overlap disappears. // The sensor overlaps don't get cleared until the next time step regardless of the overlapped // shapes being destroyed. // When a sensor is destroyed. typedef struct { b2IntArray overlaps; } b2SensorOverlaps; void b2CreateShapeProxy( b2Shape* shape, b2BroadPhase* bp, b2BodyType type, b2Transform transform, bool forcePairCreation ); void b2DestroyShapeProxy( b2Shape* shape, b2BroadPhase* bp ); void b2FreeChainData( b2ChainShape* chain ); b2MassData b2ComputeShapeMass( const b2Shape* shape ); b2ShapeExtent b2ComputeShapeExtent( const b2Shape* shape, b2Vec2 localCenter ); b2AABB b2ComputeShapeAABB( const b2Shape* shape, b2Transform transform ); b2Vec2 b2GetShapeCentroid( const b2Shape* shape ); float b2GetShapePerimeter( const b2Shape* shape ); float b2GetShapeProjectedPerimeter( const b2Shape* shape, b2Vec2 line ); b2ShapeProxy b2MakeShapeDistanceProxy( const b2Shape* shape ); b2CastOutput b2RayCastShape( const b2RayCastInput* input, const b2Shape* shape, b2Transform transform ); b2CastOutput b2ShapeCastShape( const b2ShapeCastInput* input, const b2Shape* shape, b2Transform transform ); b2PlaneResult b2CollideMoverAndCircle( const b2Circle* shape, const b2Capsule* mover ); b2PlaneResult b2CollideMoverAndCapsule( const b2Capsule* shape, const b2Capsule* mover ); b2PlaneResult b2CollideMoverAndPolygon( const b2Polygon* shape, const b2Capsule* mover ); b2PlaneResult b2CollideMoverAndSegment( const b2Segment* shape, const b2Capsule* mover ); b2PlaneResult b2CollideMover( const b2Shape* shape, b2Transform transform, const b2Capsule* mover ); static inline float b2GetShapeRadius( const b2Shape* shape ) { switch ( shape->type ) { case b2_capsuleShape: return shape->capsule.radius; case b2_circleShape: return shape->circle.radius; case b2_polygonShape: return shape->polygon.radius; default: return 0.0f; } } B2_ARRAY_INLINE( b2ChainShape, b2ChainShape ) B2_ARRAY_INLINE( b2Shape, b2Shape )
411
0.935034
1
0.935034
game-dev
MEDIA
0.961993
game-dev
0.864504
1
0.864504
libgdx/gdx-particle-editor
5,856
core/src/main/java/com/ray3k/gdxparticleeditor/widgets/Carousel.java
package com.ray3k.gdxparticleeditor.widgets; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.actions.Actions; import com.badlogic.gdx.scenes.scene2d.ui.Button; import com.badlogic.gdx.scenes.scene2d.ui.ButtonGroup; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener.ChangeEvent; import com.badlogic.gdx.utils.Array; import static com.ray3k.gdxparticleeditor.Core.skin; /** * A widget that allows the user to flip through its children, displaying only one at a time. It transitions between * each widget with a smoother Interpolation horizontally. Buttons to go to the next and previous screens are provided, * as well as radio buttons for every page. */ public class Carousel extends Table { public CardGroup cardGroup; public TextButton previousButton; public TextButton nextButton; public Table buttonTable; public ButtonGroup<Button> buttonGroup; private int shownIndex; private float buttonSpacing = 5f; public static final Vector2 temp = new Vector2(); private Interpolation interpolation = Interpolation.smoother; private float transitionDuration = .5f; private boolean transitioning; private final Array<Button> queuedButtons = new Array<>(); public Carousel(Actor... actors) { initialize(actors); } private void initialize(Actor... actors) { queuedButtons.clear(); cardGroup = new CardGroup(actors); add(cardGroup).grow(); row(); buttonTable = new Table(); buttonTable.defaults().space(buttonSpacing); add(buttonTable).growX(); previousButton = new TextButton("Previous", skin, "small"); buttonTable.add(previousButton).uniformX().fill(); previousButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { if (transitioning) queuedButtons.add(previousButton); else showIndex(shownIndex - 1); event.cancel(); } }); buttonGroup = new ButtonGroup<>(); if (actors.length > 0) { for (int i = 0; i < actors.length; i++) { final int newIndex = i; var button = new Button(skin, "pager-dot"); button.setProgrammaticChangeEvents(false); buttonTable.add(button); buttonGroup.add(button); button.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { if (transitioning) queuedButtons.add(button); else showIndex(newIndex); event.cancel(); } }); } buttonGroup.getButtons().get(shownIndex).setChecked(true); } nextButton = new TextButton("Next", skin, "small"); buttonTable.add(nextButton).uniformX().fill(); nextButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { if (transitioning) queuedButtons.add(nextButton); else showIndex(shownIndex + 1); event.cancel(); } }); } public void showIndex(int shownIndex) { showIndex(shownIndex, true); } public void showIndex(int index, boolean showTransition) { var size = cardGroup.actors.size - 1; if (index < 0) index = 0; if (index > size) index = size; if (shownIndex == index) { queuedButtons.clear(); return; } if (!showTransition) { shownIndex = index; cardGroup.showIndex(shownIndex); buttonGroup.getButtons().get(shownIndex).setChecked(true); } else { boolean goLeft = index < shownIndex; var currentActor = cardGroup.actors.get(shownIndex); var nextActor = cardGroup.actors.get(index); shownIndex = index; setClip(true); transitioning = true; buttonGroup.getButtons().get(shownIndex).setChecked(true); currentActor.addAction(Actions.sequence( Actions.moveBy((goLeft ? 1 : -1) * currentActor.getWidth(), 0, transitionDuration, interpolation))); temp.set(0, 0); currentActor.localToActorCoordinates(this, temp); addActor(nextActor); nextActor.setBounds(temp.x + (goLeft ? -1 : 1) * currentActor.getWidth(), temp.y, currentActor.getWidth(), currentActor.getHeight()); nextActor.addAction( Actions.sequence(Actions.moveTo(temp.x, temp.y, transitionDuration, interpolation), Actions.run(() -> { if (cardGroup.actors.size > 0) cardGroup.showIndex(shownIndex); setClip(false); transitioning = false; Gdx.app.postRunnable(() -> { if (queuedButtons.size > 0) { var button = queuedButtons.first(); queuedButtons.removeIndex(0); button.fire(new ChangeEvent()); } }); }))); } fire(new ChangeEvent()); } public int getShownIndex() { return shownIndex; } public Actor getShownActor() { return cardGroup.getActor(shownIndex); } }
411
0.899188
1
0.899188
game-dev
MEDIA
0.781714
game-dev
0.944248
1
0.944248
online-go/online-go.com
11,343
src/views/LearningHub/Sections/BeginnerLevel2/CapturingRace1.tsx
/* * Copyright (C) Online-Go.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* cSpell:disable */ import { GobanConfig } from "goban"; import { LearningPage, LearningPageProperties } from "../../LearningPage"; import { _, pgettext } from "@/lib/translate"; import { LearningHubSection } from "../../LearningHubSection"; export class BL2CapturingRace1 extends LearningHubSection { static pages(): Array<typeof LearningPage> { return [ Page01, Page02, Page03, Page04, Page05, Page06, Page07, Page08, Page09, Page10, Page11, Page12, Page13, ]; } static section(): string { return "bl2-capturing-race-1"; } static title(): string { return pgettext("Tutorial section name on learning approach move", "Capturing Race"); } static subtext(): string { return pgettext("Tutorial section subtext on learning on approach move", "Approach move"); } } class Page01 extends LearningPage { constructor(props: LearningPageProperties) { super(props); } text() { return _( "When counting liberties, you should be aware that you can't always fill the liberties directly. If you put yourself in atari in filling a liberty, your stone will be captured. In order to avoid this, you should first play an approach move, or first connect your stones. In this example White can not play at C immediately, because he puts his stone in atari. White must first approach point C with an approach move at D. This will cost an extra move. That is why it takes three moves to capture the marked black chain. So, effectively Black has three liberties. Similarly, Black can't immediately fill a liberty of the marked white chain at B. Black must first connect his stones at A. So, the marked white chain also has effectively three liberties. White to play. Play an approach move and win the capturing race.", ); } config(): GobanConfig { return { width: 19, height: 19, mode: "puzzle", initial_player: "white", bounds: { top: 10, left: 0, bottom: 18, right: 8 }, initial_state: { black: "arbpbqcncpdqdrdser", white: "brbscqcrdodpeqfqfrhr", }, marks: { triangle: "brbscqcrdqdrdser", A: "aq", B: "as", C: "es", D: "fs" }, move_tree: this.makePuzzleMoveTree(["fs"], ["esfs", "csas"], 19, 19), }; } } class Page02 extends LearningPage { constructor(props: LearningPageProperties) { super(props); } text() { return _("White to play. Play an approach move and win the capturing race."); } config(): GobanConfig { return { width: 19, height: 19, mode: "puzzle", initial_player: "white", bounds: { top: 10, left: 0, bottom: 18, right: 8 }, initial_state: { black: "dnepaqbqcqdqarerfrgrbsfs", white: "goeqfqgqiqbrcrdrhrds", }, move_tree: this.makePuzzleMoveTree(["hs"], [], 19, 19), }; } } class Page03 extends LearningPage { constructor(props: LearningPageProperties) { super(props); } text() { return _("White to play. Play an approach move and win the capturing race."); } config(): GobanConfig { return { width: 19, height: 19, mode: "puzzle", initial_player: "white", bounds: { top: 10, left: 0, bottom: 18, right: 8 }, initial_state: { black: "cldndoapbpcpdqeqcrerdses", white: "fmdpepgpbqcqfqbrfrfs", }, move_tree: this.makePuzzleMoveTree(["bs"], [], 19, 19), }; } } class Page04 extends LearningPage { constructor(props: LearningPageProperties) { super(props); } text() { return _("White to play. Play an approach move and win the capturing race."); } config(): GobanConfig { return { width: 19, height: 19, mode: "puzzle", initial_player: "white", bounds: { top: 10, left: 0, bottom: 18, right: 8 }, initial_state: { black: "blbncngncodoeoepcqdqbrcrbs", white: "boapbpcpdpfpgpbqeqardrfr", }, move_tree: this.makePuzzleMoveTree(["ds"], [], 19, 19), }; } } class Page05 extends LearningPage { constructor(props: LearningPageProperties) { super(props); } text() { return _("White to play. Play an approach move and win the capturing race."); } config(): GobanConfig { return { width: 19, height: 19, mode: "puzzle", initial_player: "white", bounds: { top: 10, left: 0, bottom: 18, right: 8 }, initial_state: { black: "hodpepfpdqhqbrcrfrbsfs", white: "cmdmbobqcqeqardrer", }, move_tree: this.makePuzzleMoveTree(["aq"], ["dsfq"], 19, 19), }; } } class Page06 extends LearningPage { constructor(props: LearningPageProperties) { super(props); } text() { return _("White to play. Play an approach move and win the capturing race."); } config(): GobanConfig { return { width: 19, height: 19, mode: "puzzle", initial_player: "white", bounds: { top: 10, left: 0, bottom: 18, right: 8 }, initial_state: { black: "fpgphpcqdqeqiqbrdrfriresfs", white: "enbofocpdpepbqfqgqarcrgrcsgs", }, move_tree: this.makePuzzleMoveTree(["bs"], [], 19, 19), }; } } class Page07 extends LearningPage { constructor(props: LearningPageProperties) { super(props); } text() { return _("White to play. Play an approach move and win the capturing race."); } config(): GobanConfig { return { width: 19, height: 19, mode: "puzzle", initial_player: "white", bounds: { top: 10, left: 0, bottom: 18, right: 8 }, initial_state: { black: "dpepbqcqfqarcrfrhrcs", white: "bmcodobpcpdqdrbsds", }, move_tree: this.makePuzzleMoveTree(["ap"], [], 19, 19), }; } } class Page08 extends LearningPage { constructor(props: LearningPageProperties) { super(props); } text() { return _("White to play. Play an approach move and win the capturing race."); } config(): GobanConfig { return { width: 19, height: 19, mode: "puzzle", initial_player: "white", bounds: { top: 10, left: 0, bottom: 18, right: 8 }, initial_state: { black: "bpdpepgpbqcqarbrfrbs", white: "cmbocoapcpdqcrdrcs", }, move_tree: this.makePuzzleMoveTree(["ao"], [], 19, 19), }; } } class Page09 extends LearningPage { constructor(props: LearningPageProperties) { super(props); } text() { return _("White to play. Play an approach move and win the capturing race."); } config(): GobanConfig { return { width: 19, height: 19, mode: "puzzle", initial_player: "white", bounds: { top: 10, left: 0, bottom: 18, right: 8 }, initial_state: { black: "gnfphpcqdqeqgqbrcrgrbsgs", white: "dmbpcpdpepbqfqardrerfr", }, move_tree: this.makePuzzleMoveTree(["aq"], ["dsfs"], 19, 19), }; } } class Page10 extends LearningPage { constructor(props: LearningPageProperties) { super(props); } text() { return _("White to play. Play an approach move and win the capturing race."); } config(): GobanConfig { return { width: 19, height: 19, mode: "puzzle", initial_player: "white", bounds: { top: 10, left: 0, bottom: 18, right: 8 }, initial_state: { black: "dlcmcnbodoeobpdpbqdqgqdrerfrdsfs", white: "fmdnencofocpephpaqcqfqarbrcrgrhrircsgs", }, move_tree: this.makePuzzleMoveTree(["fp"], [], 19, 19), }; } } class Page11 extends LearningPage { constructor(props: LearningPageProperties) { super(props); } text() { return _("White to play. Play an approach move and win the capturing race."); } config(): GobanConfig { return { width: 19, height: 19, mode: "puzzle", initial_player: "white", bounds: { top: 10, left: 0, bottom: 18, right: 8 }, initial_state: { black: "fmdoeocpepgpcqfqcrgrbscsfs", white: "cmdnbocobpdpbqdqeqbrerfrds", }, move_tree: this.makePuzzleMoveTree(["ar"], [], 19, 19), }; } } class Page12 extends LearningPage { constructor(props: LearningPageProperties) { super(props); } text() { return _("White to play. Play an approach move and win the capturing race."); } config(): GobanConfig { return { width: 19, height: 19, mode: "puzzle", initial_player: "white", bounds: { top: 10, left: 0, bottom: 18, right: 8 }, initial_state: { black: "dnbocobpcqdqcrerfrcsds", white: "gncpdpepgpbqeqfqbrgrbsfs", }, move_tree: this.makePuzzleMoveTree(["gs"], [], 19, 19), }; } } class Page13 extends LearningPage { constructor(props: LearningPageProperties) { super(props); } text() { return _("White to play. Play an approach move and win the capturing race."); } config(): GobanConfig { return { width: 19, height: 19, mode: "puzzle", initial_player: "white", bounds: { top: 10, left: 0, bottom: 18, right: 8 }, initial_state: { black: "dleneobpcpdpbqeqfqbrdrergres", white: "epfphpcqdqgqcrhrbscsfs", }, move_tree: this.makePuzzleMoveTree(["gs"], ["hsar"], 19, 19), }; } }
411
0.868132
1
0.868132
game-dev
MEDIA
0.858505
game-dev
0.912474
1
0.912474
ReactVision/virocore
4,843
wasm/libs/bullet/src/BulletCollision/CollisionShapes/btCollisionShape.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_COLLISION_SHAPE_H #define BT_COLLISION_SHAPE_H #include "LinearMath/btTransform.h" #include "LinearMath/btVector3.h" #include "LinearMath/btMatrix3x3.h" #include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" //for the shape types class btSerializer; ///The btCollisionShape class provides an interface for collision shapes that can be shared among btCollisionObjects. ATTRIBUTE_ALIGNED16(class) btCollisionShape { protected: int m_shapeType; void* m_userPointer; public: BT_DECLARE_ALIGNED_ALLOCATOR(); btCollisionShape() : m_shapeType (INVALID_SHAPE_PROXYTYPE), m_userPointer(0) { } virtual ~btCollisionShape() { } ///getAabb returns the axis aligned bounding box in the coordinate frame of the given transform t. virtual void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const =0; virtual void getBoundingSphere(btVector3& center,btScalar& radius) const; ///getAngularMotionDisc returns the maximus radius needed for Conservative Advancement to handle time-of-impact with rotations. virtual btScalar getAngularMotionDisc() const; virtual btScalar getContactBreakingThreshold(btScalar defaultContactThresholdFactor) const; ///calculateTemporalAabb calculates the enclosing aabb for the moving object over interval [0..timeStep) ///result is conservative void calculateTemporalAabb(const btTransform& curTrans,const btVector3& linvel,const btVector3& angvel,btScalar timeStep, btVector3& temporalAabbMin,btVector3& temporalAabbMax) const; SIMD_FORCE_INLINE bool isPolyhedral() const { return btBroadphaseProxy::isPolyhedral(getShapeType()); } SIMD_FORCE_INLINE bool isConvex2d() const { return btBroadphaseProxy::isConvex2d(getShapeType()); } SIMD_FORCE_INLINE bool isConvex() const { return btBroadphaseProxy::isConvex(getShapeType()); } SIMD_FORCE_INLINE bool isNonMoving() const { return btBroadphaseProxy::isNonMoving(getShapeType()); } SIMD_FORCE_INLINE bool isConcave() const { return btBroadphaseProxy::isConcave(getShapeType()); } SIMD_FORCE_INLINE bool isCompound() const { return btBroadphaseProxy::isCompound(getShapeType()); } SIMD_FORCE_INLINE bool isSoftBody() const { return btBroadphaseProxy::isSoftBody(getShapeType()); } ///isInfinite is used to catch simulation error (aabb check) SIMD_FORCE_INLINE bool isInfinite() const { return btBroadphaseProxy::isInfinite(getShapeType()); } #ifndef __SPU__ virtual void setLocalScaling(const btVector3& scaling) =0; virtual const btVector3& getLocalScaling() const =0; virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const = 0; //debugging support virtual const char* getName()const =0 ; #endif //__SPU__ int getShapeType() const { return m_shapeType; } ///the getAnisotropicRollingFrictionDirection can be used in combination with setAnisotropicFriction ///See Bullet/Demos/RollingFrictionDemo for an example virtual btVector3 getAnisotropicRollingFrictionDirection() const { return btVector3(1,1,1); } virtual void setMargin(btScalar margin) = 0; virtual btScalar getMargin() const = 0; ///optional user data pointer void setUserPointer(void* userPtr) { m_userPointer = userPtr; } void* getUserPointer() const { return m_userPointer; } virtual int calculateSerializeBufferSize() const; ///fills the dataBuffer and returns the struct name (and 0 on failure) virtual const char* serialize(void* dataBuffer, btSerializer* serializer) const; virtual void serializeSingleShape(btSerializer* serializer) const; }; ///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64 struct btCollisionShapeData { char *m_name; int m_shapeType; char m_padding[4]; }; SIMD_FORCE_INLINE int btCollisionShape::calculateSerializeBufferSize() const { return sizeof(btCollisionShapeData); } #endif //BT_COLLISION_SHAPE_H
411
0.964785
1
0.964785
game-dev
MEDIA
0.988113
game-dev
0.947611
1
0.947611
dxmz/Mobx-Chinese-Interpretation
5,579
src/v5/utils/decorators.ts
import { EMPTY_ARRAY, addHiddenProp, fail } from "../internal" export const mobxDidRunLazyInitializersSymbol = Symbol("mobx did run lazy initializers") export const mobxPendingDecorators = Symbol("mobx pending decorators") type DecoratorTarget = { [mobxDidRunLazyInitializersSymbol]?: boolean [mobxPendingDecorators]?: { [prop: string]: DecoratorInvocationDescription } } /** * interface PropertyDescriptor { configurable?: boolean; enumerable?: boolean; value?: any; writable?: boolean; get?(): any; set?(v: any): void; } */ export type BabelDescriptor = PropertyDescriptor & { initializer?: () => any } export type PropertyCreator = ( instance: any, propertyName: PropertyKey, descriptor: BabelDescriptor | undefined, decoratorTarget: any, decoratorArgs: any[] ) => void type DecoratorInvocationDescription = { prop: string propertyCreator: PropertyCreator descriptor: BabelDescriptor | undefined decoratorTarget: any decoratorArguments: any[] } const enumerableDescriptorCache: { [prop: string]: PropertyDescriptor } = {} const nonEnumerableDescriptorCache: { [prop: string]: PropertyDescriptor } = {} function createPropertyInitializerDescriptor( prop: string, enumerable: boolean ): PropertyDescriptor { const cache = enumerable ? enumerableDescriptorCache : nonEnumerableDescriptorCache return ( cache[prop] || (cache[prop] = { configurable: true, enumerable: enumerable, get() { initializeInstance(this) return this[prop] }, set(value) { initializeInstance(this) this[prop] = value } }) ) } export function initializeInstance(target: any) export function initializeInstance(target: DecoratorTarget) { if (target[mobxDidRunLazyInitializersSymbol] === true) return /** target[mobxPendingDecorators]![prop] = { prop, propertyCreator, descriptor, decoratorTarget: target, decoratorArguments } */ const decorators = target[mobxPendingDecorators] if (decorators) { addHiddenProp(target, mobxDidRunLazyInitializersSymbol, true) // Build property key array from both strings and symbols const keys = [...Object.getOwnPropertySymbols(decorators), ...Object.keys(decorators)] for (const key of keys) { const d = decorators[key as any] d.propertyCreator(target, d.prop, d.descriptor, d.decoratorTarget, d.decoratorArguments) } } } export function createPropDecorator( propertyInitiallyEnumerable: boolean, propertyCreator: PropertyCreator ) { return function decoratorFactory() { let decoratorArguments: any[] const decorator = function decorate( target: DecoratorTarget, prop: string, descriptor: BabelDescriptor | undefined, applyImmediately?: any // This is a special parameter to signal the direct application of a decorator, allow extendObservable to skip the entire type decoration part, // as the instance to apply the decorator to equals the target ) { if (applyImmediately === true) { propertyCreator(target, prop, descriptor, target, decoratorArguments) return null } if (process.env.NODE_ENV !== "production" && !quacksLikeADecorator(arguments)) fail("This function is a decorator, but it wasn't invoked like a decorator") if (!Object.prototype.hasOwnProperty.call(target, mobxPendingDecorators)) { // mobxPendingDecorators = Symbol("mobx pending decorators") const inheritedDecorators = target[mobxPendingDecorators] addHiddenProp(target, mobxPendingDecorators, { ...inheritedDecorators }) } /** * createPropDecorator 传进来的第二个参数, * 然后放进了 target[mobxPendingDecorators]![prop] 属性中, * 供 extendObservable 使用 */ target[mobxPendingDecorators]![prop] = { prop, propertyCreator, descriptor, decoratorTarget: target, decoratorArguments } return createPropertyInitializerDescriptor(prop, propertyInitiallyEnumerable) } if (quacksLikeADecorator(arguments)) { // @decorator 无参数 decoratorArguments = EMPTY_ARRAY // 无参时,返回描述符descriptor(decorator.apply(null, arguments)执行的结果返回描述符) return decorator.apply(null, arguments as any) } else { // @decorator(args) 有参数 // decoratorArguments在此处赋值,在 decorator 函数中使用(利用闭包) decoratorArguments = Array.prototype.slice.call(arguments) return decorator } } as Function } /** * quacksLikeADecorator 判断装饰器为哪种类型:无参返回true * * (1)当装饰器无参时: * args: * target: DecoratorTarget, prop: string, descriptor: BabelDescriptor | undefined, applyImmediately?: any * (2)当装饰器有参时 args: 为装饰器带有的参数,多个参数的话是个数组对象(如@deepDecorator("deep") b = 2) */ export function quacksLikeADecorator(args: IArguments): boolean { return ( ((args.length === 2 || args.length === 3) && (typeof args[1] === "string" || typeof args[1] === "symbol")) || (args.length === 4 && args[3] === true) ) }
411
0.91091
1
0.91091
game-dev
MEDIA
0.570663
game-dev,graphics-rendering
0.912405
1
0.912405
alliedmodders/hl2sdk
2,326
public/tier1/rangecheckedvar.h
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #ifndef RANGECHECKEDVAR_H #define RANGECHECKEDVAR_H #ifdef _WIN32 #pragma once #endif #include "tier0/dbg.h" #include "tier0/threadtools.h" #include "mathlib/vector.h" #include <float.h> // Use this to disable range checks within a scope. class CDisableRangeChecks { public: CDisableRangeChecks(); ~CDisableRangeChecks(); }; template< class T > inline void RangeCheck( const T &value, int minValue, int maxValue ) { #ifdef _DEBUG extern bool g_bDoRangeChecks; if ( ThreadInMainThread() && g_bDoRangeChecks ) { // Ignore the min/max stuff for now.. just make sure it's not a NAN. Assert( _finite( value ) ); } #endif } inline void RangeCheck( const Vector &value, int minValue, int maxValue ) { #ifdef _DEBUG RangeCheck( value.x, minValue, maxValue ); RangeCheck( value.y, minValue, maxValue ); RangeCheck( value.z, minValue, maxValue ); #endif } template< class T, int minValue, int maxValue, int startValue > class CRangeCheckedVar { public: inline CRangeCheckedVar() { m_Val = startValue; } inline CRangeCheckedVar( const T &value ) { *this = value; } T GetRaw() const { return m_Val; } // Clamp the value to its limits. Interpolation code uses this after interpolating. inline void Clamp() { if ( m_Val < minValue ) m_Val = minValue; else if ( m_Val > maxValue ) m_Val = maxValue; } inline operator const T&() const { return m_Val; } inline CRangeCheckedVar<T, minValue, maxValue, startValue>& operator=( const T &value ) { RangeCheck( value, minValue, maxValue ); m_Val = value; return *this; } inline CRangeCheckedVar<T, minValue, maxValue, startValue>& operator+=( const T &value ) { return (*this = m_Val + value); } inline CRangeCheckedVar<T, minValue, maxValue, startValue>& operator-=( const T &value ) { return (*this = m_Val - value); } inline CRangeCheckedVar<T, minValue, maxValue, startValue>& operator*=( const T &value ) { return (*this = m_Val * value); } inline CRangeCheckedVar<T, minValue, maxValue, startValue>& operator/=( const T &value ) { return (*this = m_Val / value); } private: T m_Val; }; #endif // RANGECHECKEDVAR_H
411
0.964049
1
0.964049
game-dev
MEDIA
0.219613
game-dev
0.863862
1
0.863862
lukewasthefish/AutomatonLung
3,889
Assets/Cinema Suite/Cinema Director/System/Editor/Controls/TrackItemControls/CinemaShotControl.cs
using UnityEngine; using System.Collections; using UnityEditor; using CinemaDirector; [CutsceneItemControlAttribute(typeof(CinemaShot))] public class CinemaShotControl : CinemaActionControl { #region Language private const string MODIFY_CAMERA = "Set Camera/{0}"; #endregion public override void Initialize(TimelineItemWrapper wrapper, TimelineTrackWrapper track) { base.Initialize(wrapper, track); actionIcon = EditorGUIUtility.Load("Cinema Suite/Cinema Director/Director_ShotIcon.png") as Texture; } public override void Draw(DirectorControlState state) { CinemaShot shot = Wrapper.Behaviour as CinemaShot; if (shot == null) return; if (Selection.Contains(shot.gameObject)) { GUI.Box(controlPosition, GUIContent.none, TimelineTrackControl.styles.ShotTrackItemSelectedStyle); } else { GUI.Box(controlPosition, GUIContent.none, TimelineTrackControl.styles.ShotTrackItemStyle); } // Draw Icon Color temp = GUI.color; GUI.color = (shot.shotCamera != null) ? new Color(0.19f, 0.76f, 0.84f) : Color.red; Rect icon = controlPosition; icon.x += 4; icon.width = 16; icon.height = 16; //GUI.DrawTexture(icon, shotIcon, ScaleMode.ScaleToFit, true, 0); GUI.Box(icon, actionIcon, GUIStyle.none); GUI.color = temp; Rect labelPosition = controlPosition; labelPosition.x = icon.xMax; labelPosition.width -= (icon.width + 4); if (TrackControl.isExpanded) { labelPosition.height = TimelineTrackControl.ROW_HEIGHT; if (shot.shotCamera != null) { Rect extraInfo = labelPosition; extraInfo.y += TimelineTrackControl.ROW_HEIGHT; GUI.Label(extraInfo, string.Format("Camera: {0}", shot.shotCamera.name)); } } DrawRenameLabel(shot.name, labelPosition); } protected override void showContextMenu(Behaviour behaviour) { CinemaShot shot = behaviour as CinemaShot; if (shot == null) return; Camera[] cameras = GameObject.FindObjectsOfType<Camera>(); GenericMenu createMenu = new GenericMenu(); createMenu.AddItem(new GUIContent("Rename"), false, renameItem, behaviour); createMenu.AddItem(new GUIContent("Copy"), false, copyItem, behaviour); createMenu.AddItem(new GUIContent("Delete"), false, deleteItem, shot); createMenu.AddSeparator(string.Empty); createMenu.AddItem(new GUIContent("Focus"), false, focusShot, shot); for (int i = 0; i < cameras.Length; i++) { ContextSetCamera arg = new ContextSetCamera(); arg.shot = shot; arg.camera = cameras[i]; createMenu.AddItem(new GUIContent(string.Format(MODIFY_CAMERA, cameras[i].gameObject.name)), false, setCamera, arg); } createMenu.ShowAsContext(); } private void focusShot(object userData) { CinemaShot shot = userData as CinemaShot; if (shot.shotCamera != null) { if (SceneView.lastActiveSceneView != null) { SceneView.lastActiveSceneView.AlignViewToObject(shot.shotCamera.transform); } else { Debug.Log("Focus is not supported in this version of Unity."); } } } private void setCamera(object userData) { ContextSetCamera arg = userData as ContextSetCamera; if (arg != null) { Undo.RecordObject(arg.shot, "Set Camera"); arg.shot.shotCamera = arg.camera; } } private class ContextSetCamera { public Camera camera; public CinemaShot shot; } }
411
0.773887
1
0.773887
game-dev
MEDIA
0.444311
game-dev,desktop-app
0.745934
1
0.745934
Frostshake/WMVx
35,576
src/core/modeling/CharacterCustomization.cpp
#include "../../stdafx.h" #include "CharacterCustomization.h" #include "../filesystem/GameFileSystem.h" #include "../database/GameDatabase.h" #include "../database/GameDataset.h" #include "../modeling/Model.h" #include "../modeling/Scene.h" #include "../game/GameClientAdaptor.h" #include <ranges> #include <functional> #include <algorithm> namespace core { int32_t bitMaskToSectionType(int32_t mask) { if (mask == -1 || mask == 0) { return mask; } auto val = 1; while (((mask = mask >> 1) & 0x01) == 0) val++; return val; } bool CharacterDetails::detect(const Model* model, const GameDatabase* gameDB, CharacterDetails& out) { if (!gameDB->characterRacesDB) { return false; } if (model->model->getModelPathInfo().isCharacter()) { const auto& path_info = model->model->getModelPathInfo(); auto charRaceRecord = gameDB->characterRacesDB->find([&](const CharacterRaceRecordAdaptor* item) -> bool { auto recordName = item->getClientFileString(); return recordName.compare(path_info.raceName(), Qt::CaseInsensitive) == 0; }); if (charRaceRecord != nullptr) { out.gender = GenderUtil::fromString(path_info.genderName()); out.raceId = charRaceRecord->getId(); out.isHd = model->model->getModelPathInfo().isHdCharacter(); return true; } } return false; } ModelTraits::ModelTraits(const core::Model* model) { hasRobeBottom = false; if (model != nullptr) { if (!hasRobeBottom && model->characterEquipment.contains(CharacterSlot::CHEST)) { const auto& item_wrapper = model->characterEquipment.at(CharacterSlot::CHEST); const auto* record = item_wrapper.display(); hasRobeBottom = item_wrapper.item()->getInventorySlotId() == ItemInventorySlotId::ROBE || record->getGeosetRobeFlags() == 1; } if (!hasRobeBottom && model->characterEquipment.contains(CharacterSlot::PANTS)) { const auto& item_wrapper = model->characterEquipment.at(CharacterSlot::PANTS); const auto* record = item_wrapper.display(); hasRobeBottom = record->getGeosetRobeFlags() == 1; } } } bool CharacterCustomizationProvider::apply(Model* model, const CharacterDetails& details, const CharacterCustomizations& choices) { model->characterCustomizationChoices = choices; model->getGeosetTransform().getOrMakeModifier<ModelDefaultsGeosetModifier>([&] { return std::make_shared<ModelDefaultsGeosetModifier>(); }); model->getGeosetTransform().getOrMakeModifier<CharacterDefaultsGeosetModifier>([&] { return std::make_shared<CharacterDefaultsGeosetModifier>(model); }); model->getGeosetTransform().getOrMakeModifier<CharacterEquipGeosetModifier>([&] { return std::make_shared<CharacterEquipGeosetModifier>(model); }); model->getGeosetTransform().getOrMakeModifier<CharacterOverridesGeosetModifier>([&] { return std::make_shared<CharacterOverridesGeosetModifier>(model); }); return updateContext(model, details, choices); } LegacyCharacterCustomizationProvider::LegacyCharacterCustomizationProvider(GameFileSystem* fs, GameDatabase* db) : CharacterCustomizationProvider(), gameFS(fs), gameDB(db) { eyeGlowModifierFactory = [](const Model* m) -> std::shared_ptr<CharEyeGlowGeosetModifier> { return std::make_shared<CharEyeGlowEnumBasedGeosetModifier>(m); }; } void LegacyCharacterCustomizationProvider::initialise(const CharacterDetails& details) { for (const auto& key : LegacyCharacterCustomization::All) { known_options[key] = {}; } auto filterCustomizationOptions = [&]<typename T>(const T * adaptor) -> bool { constexpr auto hasHD = requires(const T & t) { t.isHD(); }; if constexpr (hasHD) { if (adaptor->isHD() != details.isHd) { return false; } } return adaptor->getRaceId() == details.raceId && adaptor->getSexId() == details.gender; }; const auto matching_char_sections = gameDB->characterSectionsDB->where(filterCustomizationOptions); auto choice_incrementer = [&](const auto& choice_name) { known_options[choice_name].push_back( std::to_string(known_options[choice_name].size()) ); }; // load available customisations for (auto charSectionRecord : matching_char_sections) { //only checking for variationIndex 0 to avoid duplicates being included. auto section_type = charSectionRecord->getType(); if (section_type == CharacterSectionType::Skin) { choice_incrementer(LegacyCharacterCustomization::Name::Skin); } else if (section_type == CharacterSectionType::Face) { if (charSectionRecord->getVariationIndex() == 0) { choice_incrementer(LegacyCharacterCustomization::Name::Face); } } else if (section_type == CharacterSectionType::Hair) { if (charSectionRecord->getVariationIndex() == 0) { choice_incrementer(LegacyCharacterCustomization::Name::HairColor); } } else if (section_type == CharacterSectionType::FacialHair) { if (charSectionRecord->getVariationIndex() == 0 /* && charSectionRecord->getSection() == 0 */) { //TODO check logic choice_incrementer(LegacyCharacterCustomization::Name::FacialColor); } } } const auto hair_style_count = gameDB->characterHairGeosetsDB->count(filterCustomizationOptions); const auto facial_hair_count = gameDB->characterFacialHairStylesDB->count(filterCustomizationOptions); for (auto i = 0; i < hair_style_count; i++) { choice_incrementer(LegacyCharacterCustomization::Name::HairStyle); } for (auto i = 0; i < facial_hair_count; i++) { choice_incrementer(LegacyCharacterCustomization::Name::FacialStyle); } } void LegacyCharacterCustomizationProvider::reset() { known_options.clear(); context.reset(); } bool LegacyCharacterCustomizationProvider::updateContext(Model* model, const CharacterDetails& details, const CharacterCustomizations& choices) { //updating records... if (!context) { context = std::make_shared<Context>(); } { auto geo_mod = model->getGeosetTransform().getOrMakeModifier<LegacyCharCustomGeosetModifier>([&] { return std::make_shared<LegacyCharCustomGeosetModifier>(model); }); geo_mod->context = context; } model->getGeosetTransform().getOrMakeModifier<CharEyeGlowGeosetModifier>([&] { return eyeGlowModifierFactory(model); }); auto found = 0; auto filterCustomizationOptions = [&]<typename T>(const T * adaptor) -> bool { constexpr auto hasHD = requires(const T & t) { t.isHD(); }; if constexpr (hasHD) { if (adaptor->isHD() != details.isHd) { return false; } } return adaptor->getRaceId() == details.raceId && adaptor->getSexId() == details.gender; }; const auto matching_char_sections = gameDB->characterSectionsDB->where(filterCustomizationOptions); //TODO THIS CHECK CURRENTLY NOT WORKING FOR VANILLA //#ifdef _DEBUG // { // //sanity check available options - multiple hits on a variation indicate an issue with the underlying adaptor data. // // // variation_index -> frequency // auto unique_skins = std::map<uint32_t, size_t>(); // for (auto charSectionRecord : matching_char_sections) { // if (CharacterSectionType::Skin == charSectionRecord->getType()) { // unique_skins[charSectionRecord->getVariationIndex()]++; // } // } // // for (const auto& skin : unique_skins) { // assert(skin.second == 1); // } // } //#endif for (auto charSectionRecord : matching_char_sections) { auto section_type = charSectionRecord->getType(); if (section_type == CharacterSectionType::Skin) { if (charSectionRecord->getVariationIndex() == choices.at(LegacyCharacterCustomization::Name::Skin)) { context->skin = charSectionRecord; found++; } } else if (section_type == CharacterSectionType::Face) { if (charSectionRecord->getVariationIndex() == choices.at(LegacyCharacterCustomization::Name::Skin)) { if (charSectionRecord->getSection() == choices.at(LegacyCharacterCustomization::Name::Face)) { context->face = charSectionRecord; found++; } } } else if (section_type == CharacterSectionType::Hair) { if (charSectionRecord->getVariationIndex() == choices.at(LegacyCharacterCustomization::Name::HairColor) && charSectionRecord->getSection() == choices.at(LegacyCharacterCustomization::Name::HairStyle)) { context->hairColour = charSectionRecord; found++; } } else if (section_type == CharacterSectionType::FacialHair) { if (charSectionRecord->getVariationIndex() == choices.at(LegacyCharacterCustomization::Name::HairColor) && charSectionRecord->getSection() == choices.at(LegacyCharacterCustomization::Name::FacialColor)) { context->facialColour = charSectionRecord; found++; } } if (found >= 4) { //exit early if all have been found. break; } } auto hair_style_index = 0; for (auto& hairStyleRecord : gameDB->characterHairGeosetsDB->where(filterCustomizationOptions)) { if (hair_style_index == choices.at(LegacyCharacterCustomization::Name::HairStyle)) { context->hairStyle = hairStyleRecord; break; } hair_style_index++; } auto facial_style_index = 0; for (auto& facialHairStyleRecord : gameDB->characterFacialHairStylesDB->where(filterCustomizationOptions)) { if (facial_style_index == choices.at(LegacyCharacterCustomization::Name::FacialStyle)) { context->facialStyle = facialHairStyleRecord; break; } facial_style_index++; } auto tmp_underwear = gameDB->characterSectionsDB->find([&](const CharacterSectionRecordAdaptor* adaptor) ->bool { return adaptor->getRaceId() == details.raceId && adaptor->getSexId() == details.gender && adaptor->getVariationIndex() == context->skin->getVariationIndex() && adaptor->isHD() == details.isHd && adaptor->getType() == CharacterSectionType::Underwear; }); context->underwear = const_cast<CharacterSectionRecordAdaptor*>(tmp_underwear); return context->isValid(); } bool LegacyCharacterCustomizationProvider::update(Model* model, CharacterTextureBuilder* builder, Scene* scene) { assert(context); std::shared_ptr<Texture> hairtex = nullptr; std::shared_ptr<Texture> furtex = nullptr; if(context->skin != nullptr) { const auto& skin = context->skin->getTextures(); if (!skin[0].isEmpty()) { builder->setBaseLayer(skin[0]); } if (!skin[1].isEmpty()) { furtex = scene->textureManager.add(skin[1], gameFS); } if (model->characterOptions.showUnderWear) { if (context->underwear != nullptr) { const auto& underwear_skins = context->underwear->getTextures(); if (!underwear_skins[0].isEmpty()) { builder->addLayer(underwear_skins[0], CharacterRegion::LEG_UPPER, 1); } if (!underwear_skins[1].isEmpty()) { builder->addLayer(underwear_skins[1], CharacterRegion::TORSO_UPPER, 1); } } } } if (context->hairStyle != nullptr) { if (context->face != nullptr) { const auto& face = context->face->getTextures(); if (!face[0].isEmpty()) { builder->addLayer(face[0], CharacterRegion::FACE_LOWER, 1); } if (!face[1].isEmpty()) { builder->addLayer(face[1], CharacterRegion::FACE_UPPER, 1); } } } if (model->characterOptions.showFacialHair) { const auto* facial_geoset = context->facialStyle; if (facial_geoset != nullptr) { if (context->facialColour != nullptr) { const auto& face_feature = context->facialColour->getTextures(); if (!face_feature[0].isEmpty()) { builder->addLayer(face_feature[0], CharacterRegion::FACE_LOWER, 2); } if (!face_feature[1].isEmpty()) { builder->addLayer(face_feature[1], CharacterRegion::FACE_UPPER, 2); } } } } if(context->hairColour != nullptr) { const auto& hair = context->hairColour->getTextures(); if (!hair[0].isEmpty()) { hairtex = scene->textureManager.add(hair[0], gameFS); } if (context->hairStyle && !context->hairStyle->isBald()) { if (!hair[1].isEmpty()) { builder->addLayer(hair[1], CharacterRegion::FACE_LOWER, 3); } if (!hair[2].isEmpty()) { builder->addLayer(hair[2], CharacterRegion::FACE_UPPER, 3); } } if (hairtex == nullptr) { //TODO need to use alternative texture? } } if (hairtex != nullptr) { model->replacableTextures[TextureType::HAIR] = hairtex; } else { model->replacableTextures.erase(TextureType::HAIR); } if (furtex != nullptr) { model->replacableTextures[TextureType::SKIN_EXTRA] = furtex; } else { model->replacableTextures.erase(TextureType::SKIN_EXTRA); } //TODO GAMEOBJECT1 //TODO geosets return true; } CharacterComponentTextureAdaptor* LegacyCharacterCustomizationProvider::getComponentTextureAdaptor(const CharacterDetails& details) { auto raceInfo = gameDB->characterRacesDB->findById(details.raceId); const bool is_hd_model = details.isHd; if (raceInfo != nullptr && raceInfo->getComponentTextureLayoutId(is_hd_model).has_value()) { const auto raceLayoutId = raceInfo->getComponentTextureLayoutId(is_hd_model).value(); auto temp_componentAdaptor = gameDB->characterComponentTexturesDB->find([raceLayoutId](const CharacterComponentTextureAdaptor* componentAdaptor) -> bool { return componentAdaptor->getLayoutId() == raceLayoutId; }); if (temp_componentAdaptor != nullptr) { return const_cast<CharacterComponentTextureAdaptor*>(temp_componentAdaptor); } } return nullptr; } ModernCharacterCustomizationProvider::ModernCharacterCustomizationProvider(GameFileSystem* fs, GameDatabase* db, const WDBReader::GameVersion& version) : CharacterCustomizationProvider(), gameFS(fs), gameDB(db) { fileDataDB = dynamic_cast<IFileDataGameDatabase*>(gameDB); auto* const cascFS = (CascFileSystem*)(gameFS); auto make_db = [&](const auto& db_name, const auto& def_name) { auto schema = make_wbdr_schema(def_name, version); auto file = cascFS->openFile(db_name); auto casc_source = file->release(); auto memory_source = std::make_unique<WDBReader::Filesystem::MemoryFileSource>(*casc_source); auto db = WDBReader::Database::makeDB2File(schema, std::move(memory_source)); return std::make_pair(std::move(schema), std::move(db)); }; _schema_chr_custom = make_wbdr_schema("ChrCustomization.dbd", version); _schema_chr_option = make_wbdr_schema("ChrCustomizationOption.dbd", version); _schema_chr_choice = make_wbdr_schema("ChrCustomizationChoice.dbd", version); elementsDB = make_db( "dbfilesclient/chrcustomizationelement.db2", "ChrCustomizationElement.dbd" ); geosetsDB = make_db( "dbfilesclient/chrcustomizationgeoset.db2", "ChrCustomizationGeoset.dbd" ); skinnedModelsDB = make_db( "dbfilesclient/chrcustomizationskinnedmodel.db2", "ChrCustomizationSkinnedModel.dbd" ); materialsDB = make_db( "dbfilesclient/chrcustomizationmaterial.db2", "ChrCustomizationMaterial.dbd" ); textureLayersDB = make_db( "dbfilesclient/chrmodeltexturelayer.db2", "ChrModelTextureLayer.dbd" ); modelsDB = make_db( "dbfilesclient/chrmodel.db2", "ChrModel.dbd" ); raceModelsDB = make_db( "dbfilesclient/chrracexchrmodel.db2", "ChrRaceXChrModel.dbd" ); } void ModernCharacterCustomizationProvider::initialise(const CharacterDetails& details) { auto* const cascFS = (CascFileSystem*)(gameFS); auto model_id = getModelIdForCharacter(details); assert(model_id > 0); auto custom_file = cascFS->openFile("dbfilesclient/chrcustomization.db2"); auto customs = WDBReader::Database::makeDB2File( _schema_chr_custom, custom_file->release() ); auto opts_file = cascFS->openFile("dbfilesclient/chrcustomizationoption.db2"); auto custom_opts = WDBReader::Database::makeDB2File( _schema_chr_option, opts_file->release() ); auto choice_file = cascFS->openFile("dbfilesclient/chrcustomizationchoice.db2"); auto custom_choices = WDBReader::Database::makeDB2File( _schema_chr_choice, choice_file->release() ); // for whatever reason, returned string can contain invalid characters, likely an error in the record reading. //TODO investigate auto safe_format_choice_str = [](std::string& str, uint32_t index) { str.erase(remove_if(str.begin(), str.end(), [](char c) {return !(c >= 32 && c <= 126); }), str.end()); if (str.size() <= 2) { str = std::to_string(index); } }; for (auto& custom_row : *customs) { if (custom_row.encryptionState == WDBReader::Database::RecordEncryption::ENCRYPTED) { continue; } auto [cust_id, cust_sex, cust_race, cust_str] = _schema_chr_custom(custom_row) .get<uint32_t, uint32_t, uint32_t, WDBReader::Database::string_data_ref_t>( "ID", "Sex", "RaceID", "Name_lang" ); if ((cust_sex == (uint32_t)details.gender || cust_sex == (uint32_t)Gender::ANY) && (cust_race == details.raceId || cust_race == 0)) { const auto customization_str = std::string(cust_str); for (auto& option_row : *custom_opts) { if (option_row.encryptionState == WDBReader::Database::RecordEncryption::ENCRYPTED) { continue; } auto [opt_id, opt_cust_id, opt_model_id, opt_str_val] = _schema_chr_option(option_row) .get<uint32_t, uint32_t, uint32_t, WDBReader::Database::string_data_ref_t>( "ID", "ChrCustomizationID", "ChrModelID", "Name_lang" ); if (opt_cust_id == cust_id && opt_model_id == model_id) { auto opt_str = std::string(opt_str_val); std::vector<uint32_t> choice_ids; std::vector<std::string> choice_strings; for (auto& choice_row : *custom_choices) { if (choice_row.encryptionState == WDBReader::Database::RecordEncryption::ENCRYPTED) { continue; } auto [choice_id, choice_opt_id, choice_str_val] = _schema_chr_choice(choice_row) .get<uint32_t, uint32_t, WDBReader::Database::string_data_ref_t>( "ID", "ChrCustomizationOptionID", "Name_lang" ); if (choice_opt_id == opt_id) { auto choice_str = std::string(choice_str_val); choice_ids.push_back(choice_id); choice_strings.push_back(std::move(choice_str)); } } if (choice_ids.size() > 0) { assert(choice_ids.size() == choice_strings.size()); auto i = 0; for (auto& choice_string : choice_strings) { safe_format_choice_str(choice_string, i++); } known_options[opt_str] = std::move(choice_strings); cacheOptions[opt_str] = opt_id; cacheChoices[opt_id] = std::move(choice_ids); } } } } } assert(known_options.size() == cacheOptions.size()); assert(known_options.size() == cacheChoices.size()); } void ModernCharacterCustomizationProvider::reset() { known_options.clear(); cacheOptions.clear(); cacheChoices.clear(); context.reset(); } bool ModernCharacterCustomizationProvider::updateContext(Model* model, const CharacterDetails& details, const CharacterCustomizations& choices) { auto* const cascFS = (CascFileSystem*)(gameFS); if (!context) { context = std::make_shared<Context>(); } { auto geo_mod = model->getGeosetTransform().getOrMakeModifier<ModernCharCustomGeosetModifier>([&] { return std::make_shared<ModernCharCustomGeosetModifier>(model); }); geo_mod->context = context; } model->getGeosetTransform().getOrMakeModifier<CharEyeGlowGeosetModifier>([&] { return eyeGlowModifierFactory(model); }); //TODO shouldnt need to fully reset contet each timne. context->geosets.clear(); context->materials.clear(); context->models.clear(); const auto textureLayoutId = getTextureLayoutId(details); std::vector<uint32_t> selected_choices_ids; selected_choices_ids.reserve(choices.size()); for (const auto& choice : choices) { const auto option_id = cacheOptions[choice.first]; const auto choice_id = cacheChoices[option_id][choice.second]; selected_choices_ids.push_back(choice_id); } for (const auto& choice : choices) { const auto option_id = cacheOptions[choice.first]; const auto choice_id = cacheChoices[option_id][choice.second]; bool choice_found_elements = false; for (auto& element : *elementsDB.second) { if (element.encryptionState == WDBReader::Database::RecordEncryption::ENCRYPTED) { continue; } const auto [el_choice_id, el_rel_choice, el_geoset_id, el_sk_model_id, el_mat_id] = elementsDB.first(element) .get<uint32_t, uint32_t, uint32_t, uint32_t, uint32_t>( "ChrCustomizationChoiceID", "RelatedChrCustomizationChoiceID", "ChrCustomizationGeosetID", "ChrCustomizationSkinnedModelID", "ChrCustomizationMaterialID" ); if (el_choice_id == choice_id) { if (el_rel_choice != 0) { if (std::ranges::count(selected_choices_ids, el_rel_choice) == 0) { continue; } } choice_found_elements = true; if (el_geoset_id > 0) { auto tmp = findRecordById(geosetsDB, el_geoset_id); if (tmp.has_value()) { auto [geoset_id, geoset_type] = geosetsDB.first(*tmp).get<uint32_t, uint32_t>("GeosetID", "GeosetType"); context->geosets.emplace_back( geoset_type, geoset_id ); } } if (el_sk_model_id > 0) { auto tmp = findRecordById(skinnedModelsDB, el_sk_model_id); if (tmp.has_value()) { auto [file_id, geoset_id, geoset_type] = skinnedModelsDB.first(*tmp).get<uint32_t, uint32_t, uint32_t>( "CollectionsFileDataID", "GeosetID", "GeosetType" ); const auto& model_uri = file_id; if (model_uri > 0) { context->models.emplace_back( file_id, //TODO not sure if needs needs to be the record id? model_uri, geoset_type, geoset_id ); } } } if (el_mat_id > 0) { auto tmp = findRecordById(materialsDB, el_mat_id); if (tmp.has_value()) { auto [mat_id, mat_res_id, mat_tex_target] = materialsDB.first(*tmp).get<uint32_t, uint32_t, uint32_t>( "ID", "MaterialResourcesID", "ChrModelTextureTargetID" ); Context::Material mat; mat.custMaterialId = mat_id; mat.uri = fileDataDB->findByMaterialResId(mat_res_id, -1, std::nullopt); for (auto& layer : *textureLayersDB.second) { if (layer.encryptionState == WDBReader::Database::RecordEncryption::ENCRYPTED) { continue; } auto [layer_tex_target, layer_tex_layout] = textureLayersDB.first(layer).get<uint32_t, uint32_t>( "ChrModelTextureTargetID", "CharComponentTextureLayoutsID" ); //TODO does [1] need to be checked too? (chrModelTextureTargetId is uint32_t[2]) if (layer_tex_target == mat_tex_target && layer_tex_layout == textureLayoutId) { auto [tex_type, layer_val, blend_mode, section_type] = textureLayersDB.first(layer).get<uint32_t, uint32_t, uint32_t, uint32_t>( "TextureType", "Layer", "BlendMode", "TextureSectionTypeBitMask" ); mat.textureType = tex_type; mat.layer = layer_val; mat.blendMode = blend_mode; mat.region = bitMaskToSectionType(section_type); context->materials.push_back(mat); } } } } } } if (!choice_found_elements) { Log::message("Unable to find character elements for option " + QString::number(option_id) + "'" + QString::fromStdString(choice.first) + "' / choice " + QString::number(choice_id)); } } std::sort(context->materials.begin(), context->materials.end()); return true; } bool ModernCharacterCustomizationProvider::update(Model* model, CharacterTextureBuilder* builder, Scene* scene) { assert(context); if (!context) { return false; } for (const auto& mat : context->materials) { const bool can_be_replacable = std::ranges::count(std::ranges::views::values(model->specialTextures), (TextureType)mat.textureType) > 0; if (mat.textureType <= 1 || !can_be_replacable) { // a few models have a secondary overlay that currently isnt handled correctly during rendering // doesnt seem to make a difference skipping them. if (mat.region == -1 && mat.textureType >= (int32_t)TextureType::CHAR_ACCESSORY) { continue; } if (mat.region == -1 && mat.layer == 0) { //TODO dracthyr base == 11? builder->pushBaseLayer(mat.uri, (CharacterTextureBuilder::BlendMode)mat.blendMode); } else { builder->addLayer(mat.uri, (CharacterRegion)mat.region, mat.layer, (CharacterTextureBuilder::BlendMode)mat.blendMode); } } else { auto tex = scene->textureManager.add(mat.uri, gameFS); model->replacableTextures[(TextureType)mat.textureType] = tex; Log::message("Replaceable texture: " + mat.uri.toString()); } } if (model != nullptr) { // note that multiple context->models can share the same id (e.g when model gets used twice, with different geosets) std::unordered_set<MergedModel::id_t> merge_checked; for (const auto& merged : model->getMerged()) { if (merged->getType() == MergedModel::Type::CHAR_MODEL_ADDITION) { merge_checked.insert(merged->getId()); } } for (auto* merged : model->getMerged()) { if (merged->getType() == MergedModel::Type::CHAR_MODEL_ADDITION) { auto mod = merged->getGeosetTransform().getOrMakeModifier<MergedCustomizationGeosetModifier>( [] { return std::make_shared<MergedCustomizationGeosetModifier>(); } ); mod->contextModels.clear(); } } // add or update for (const auto& model_in : context->models) { MergedModel* existing = nullptr; const auto merged_id = model_in.custSkinnedModelId; for (auto* merged : model->getMerged()) { if (merged->getType() == MergedModel::Type::CHAR_MODEL_ADDITION && merged->getId() == merged_id) { existing = merged; break; } } if (existing == nullptr) { M2Model::Factory factory = &M2Model::make; //TODO should use factory from clientinfo. auto custom = std::make_unique<MergedModel>( model, MergedModel::Type::CHAR_MODEL_ADDITION, merged_id ); custom->initialise(model_in.uri, factory, gameFS, gameDB, scene->textureManager); custom->merge(MergedModel::RESOLUTION_FINE); Log::message("Loaded merged model / char addition - " + QString::number(custom->getId())); existing = custom.get(); { auto* tmp = custom.get(); model->addRelation(std::move(custom)); scene->addComponent(tmp); } } { auto mod = existing->getGeosetTransform().getOrMakeModifier<MergedCustomizationGeosetModifier>( [] { return std::make_shared<MergedCustomizationGeosetModifier>(); } ); mod->contextModels.push_back(model_in); } merge_checked.erase(merged_id); } model->updateAllGeosets(); // cleanup any removed for (const auto& merged_id : merge_checked) { model->removeRelation(MergedModel::Type::CHAR_MODEL_ADDITION, merged_id); Log::message("Removed merged model / char addtion - " + QString::number(merged_id)); } } return true; } CharacterComponentTextureAdaptor* ModernCharacterCustomizationProvider::getComponentTextureAdaptor(const CharacterDetails& details) { const auto layoutId = getTextureLayoutId(details); auto temp_componentAdaptor = gameDB->characterComponentTexturesDB->find([layoutId](const CharacterComponentTextureAdaptor* componentAdaptor) -> bool { return componentAdaptor->getLayoutId() == layoutId; }); if (temp_componentAdaptor != nullptr) { return const_cast<CharacterComponentTextureAdaptor*>(temp_componentAdaptor); } return nullptr; } uint32_t ModernCharacterCustomizationProvider::getTextureLayoutId(const CharacterDetails& details) { auto model_id = getModelIdForCharacter(details); assert(model_id > 0); for (auto& rec : *modelsDB.second) { if (rec.encryptionState == WDBReader::Database::RecordEncryption::ENCRYPTED) { continue; } auto [id, layout_id] = modelsDB.first(rec).get<uint32_t, uint32_t>("ID", "CharComponentTextureLayoutID"); if (id == model_id) { return layout_id; } } return 0; } uint32_t ModernCharacterCustomizationProvider::getModelIdForCharacter(const CharacterDetails& details) { const auto& names = raceModelsDB.first.names(); const bool has_gender_field = std::find(names.begin(), names.end(), std::string("Sex")) != names.end(); if (has_gender_field) { for (auto& rec : *raceModelsDB.second) { if (rec.encryptionState == WDBReader::Database::RecordEncryption::ENCRYPTED) { continue; } auto [race_id, sex, model_id] = raceModelsDB.first(rec).get<uint32_t, uint32_t, uint32_t>("ChrRacesID", "Sex", "ChrModelID"); if (race_id == details.raceId && sex == (uint32_t)details.gender) { return model_id; } } } else { // 9.x didnt have a gender field, assume match index is the gender. uint32_t gender_match = 0; for (auto& rec : *raceModelsDB.second) { if (rec.encryptionState == WDBReader::Database::RecordEncryption::ENCRYPTED) { continue; } auto [race_id, model_id] = raceModelsDB.first(rec).get<uint32_t, uint32_t>("ChrRacesID", "ChrModelID"); if (race_id == details.raceId) { if (gender_match++ == (uint32_t)details.gender) { return model_id; } } } } return 0; } void ModelDefaultsGeosetModifier::operator()(GeosetState& state) { state.each([](auto& el) { //load all the default geosets //e.g 0, 101, 201, 301 ... etc //equipment is responsible for unsetting the visibility of the default geosets. const auto geoset_id = el.first; el.second = geoset_id == 0 || (geoset_id > 100 && geoset_id % 100 == 1); }); } void CharacterDefaultsGeosetModifier::operator()(GeosetState& state) { // apply a simple default for ears that can be overriden in the customization provider if needed. if (model->characterOptions.earVisibilty == CharacterRenderOptions::EarVisibility::NORMAL) { state.setVisibility(CharacterGeosets::CG_EARS, 2, false); } } void CharacterEquipGeosetModifier::operator()(GeosetState& state) { ModelTraits traits = ModelTraits(model); for (const auto& equip : model->characterEquipment) { const auto* record = equip.second.display(); switch (equip.first) { case CharacterSlot::CHEST: case CharacterSlot::SHIRT: state.setVisibility(CharacterGeosets::CG_WRISTBANDS, record->getGeosetGlovesFlags()); if (equip.second.item()->getInventorySlotId() == ItemInventorySlotId::ROBE || record->getGeosetRobeFlags() == 1) { state.setVisibility(CharacterGeosets::CG_TROUSERS, record->getGeosetRobeFlags()); } break; case CharacterSlot::PANTS: state.setVisibility(CharacterGeosets::CG_KNEEPADS, record->getGeosetBracerFlags()); state.setVisibility(CharacterGeosets::CG_TROUSERS, record->getGeosetRobeFlags()); break; case CharacterSlot::GLOVES: state.setVisibility(CharacterGeosets::CG_GLOVES, record->getGeosetGlovesFlags()); break; case CharacterSlot::BOOTS: if (!traits.hasRobeBottom) { state.setVisibility(CharacterGeosets::CG_BOOTS, record->getGeosetGlovesFlags()); } break; case CharacterSlot::TABARD: if (!traits.hasRobeBottom) { state.setVisibility(CharacterGeosets::CG_TABARD, 1); } break; case CharacterSlot::CAPE: state.setVisibility(CharacterGeosets::CG_CAPE, record->getGeosetGlovesFlags()); break; } } } void LegacyCharCustomGeosetModifier::operator()(GeosetState& state) { if (context->hairStyle != nullptr) { const auto hair_geoset_id = std::max(1u, context->hairStyle->getGeoset()); state.each([&](auto& el) { if (el.first == hair_geoset_id) { el.second = model->characterOptions.showHair; } }); } if (model->characterOptions.showFacialHair) { const auto* facial_geoset = context->facialStyle; if (facial_geoset != nullptr) { //must be atleast 1, can be problematic if it doesnt get shown at all. //NOTE records arent in 100, 300, 200 order //TODO check logic, is the adaptor returing data in incorrect order? state.setVisibility(CharacterGeosets::CG_GEOSET100, facial_geoset->getGeoset100()); state.setVisibility(CharacterGeosets::CG_GEOSET200, facial_geoset->getGeoset300()); state.setVisibility(CharacterGeosets::CG_GEOSET300, facial_geoset->getGeoset200()); } } } void ModernCharCustomGeosetModifier::operator()(GeosetState& state) { //TODO handle model->characterOptions.showFacialHair for (const auto& geo : context->geosets) { state.setVisibility((core::CharacterGeosets)geo.geosetType, geo.geosetId, false); } // force the character face to be shown. state.setVisibility(core::CharacterGeosets::CG_FACE, 1); } void CharEyeGlowEnumBasedGeosetModifier::operator()(GeosetState& state) { state.setVisibility(CharacterGeosets::CG_EYEGLOW, (uint32_t)model->characterOptions.eyeGlow); } void CharEyeGlowGeosetBasedGeosetModifier::operator()(GeosetState& state) { if (model->characterOptions.eyeGlow == CharacterRenderOptions::EyeGlow::DEATH_KNIGHT) { state.setVisibility(CharacterGeosets::CG_EYEGLOW, 0); } else { state.clearVisibility(CharacterGeosets::CG_EYEGLOW); } } void CharacterOverridesGeosetModifier::operator()(GeosetState& state) { // after the provider update, handle ear visiblity overrides. switch (model->characterOptions.earVisibilty) { case CharacterRenderOptions::EarVisibility::REMOVED: state.clearVisibility(CharacterGeosets::CG_EARS); break; case CharacterRenderOptions::EarVisibility::MINIMAL: state.setVisibility(CharacterGeosets::CG_EARS, 1, false); break; } } void MergedEquipmentGeosetModifier::operator()(GeosetState& state) { // some merged equipments will include geosets for other equipement too (shared file) // so we do need to filter geosets based on the related slot. auto set_range = [&state](CharacterGeosets geoset) { const uint32_t start = geoset * 100; const uint32_t end = (geoset * (100 + 1)) - 1; state.each([&](auto& el) { if (el.first >= start && el.first <= end) { el.second = true; } }); }; switch (slot) { case CharacterSlot::HEAD: set_range(CharacterGeosets::CG_HEADDRESS); set_range(CharacterGeosets::CG_HEAD_ATTACHMENT); set_range(CharacterGeosets::CG_GEOSET2700); break; case CharacterSlot::SHOULDER: set_range(CharacterGeosets::CG_GEOSET2600); break; case CharacterSlot::CAPE: set_range(CharacterGeosets::CG_CAPE); break; case CharacterSlot::TABARD: set_range(CharacterGeosets::CG_TABARD); break; case CharacterSlot::CHEST: set_range(CharacterGeosets::CG_CHEST); set_range(CharacterGeosets::CG_TORSO); break; case CharacterSlot::BELT: set_range(CharacterGeosets::CG_BELT); break; case CharacterSlot::PANTS: set_range(CharacterGeosets::CG_PANTS); set_range(CharacterGeosets::CG_TROUSERS); break; case CharacterSlot::BOOTS: set_range(CharacterGeosets::CG_BOOTS); set_range(CharacterGeosets::CG_FEET); break; case CharacterSlot::BRACERS: set_range(CharacterGeosets::CG_WRISTBANDS); break; case CharacterSlot::GLOVES: set_range(CharacterGeosets::CG_GLOVES); set_range(CharacterGeosets::CG_HAND_ATTACHMENT); break; } } void MergedCustomizationGeosetModifier::operator()(GeosetState& state) { for (const auto& context : contextModels) { state.setVisibility((CharacterGeosets)context.geosetType, context.geosetId, false); } } }
411
0.94578
1
0.94578
game-dev
MEDIA
0.582778
game-dev
0.890917
1
0.890917
magefree/mage
2,780
Mage.Sets/src/mage/cards/c/CloudhoofKirin.java
package mage.cards.c; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.SpellCastControllerTriggeredAbility; import mage.abilities.effects.OneShotEffect; import mage.abilities.keyword.FlyingAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.*; import mage.filter.StaticFilters; import mage.game.Game; import mage.game.stack.Spell; import mage.players.Player; import mage.target.Target; import mage.target.TargetPlayer; import java.util.UUID; /** * @author LevelX2 */ public final class CloudhoofKirin extends CardImpl { public CloudhoofKirin(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{U}{U}"); this.supertype.add(SuperType.LEGENDARY); this.subtype.add(SubType.KIRIN); this.subtype.add(SubType.SPIRIT); this.power = new MageInt(4); this.toughness = new MageInt(4); // Flying this.addAbility(FlyingAbility.getInstance()); // Whenever you cast a Spirit or Arcane spell, you may have target player put the top X cards of their library into their graveyard, where X is that spell's converted mana cost. Ability ability = new SpellCastControllerTriggeredAbility(Zone.BATTLEFIELD, new CloudhoofKirinEffect(), StaticFilters.FILTER_SPELL_SPIRIT_OR_ARCANE, true, SetTargetPointer.SPELL); ability.addTarget(new TargetPlayer()); this.addAbility(ability); } private CloudhoofKirin(final CloudhoofKirin card) { super(card); } @Override public CloudhoofKirin copy() { return new CloudhoofKirin(this); } } class CloudhoofKirinEffect extends OneShotEffect { CloudhoofKirinEffect() { super(Outcome.Detriment); this.staticText = "target player mill X cards, where X is that spell's mana value"; } private CloudhoofKirinEffect(final CloudhoofKirinEffect effect) { super(effect); } @Override public CloudhoofKirinEffect copy() { return new CloudhoofKirinEffect(this); } @Override public boolean apply(Game game, Ability source) { Spell spell = game.getSpellOrLKIStack(this.getTargetPointer().getFirst(game, source)); if (spell != null) { Player targetPlayer = null; for (Target target : source.getTargets()) { if (target instanceof TargetPlayer) { targetPlayer = game.getPlayer(target.getFirstTarget()); } } int cmc = spell.getManaValue(); if (targetPlayer != null && cmc > 0) { targetPlayer.millCards(cmc, source, game); return true; } } return false; } }
411
0.923013
1
0.923013
game-dev
MEDIA
0.931308
game-dev
0.991847
1
0.991847
RSDKModding/Sonic-Mania-Decompilation
9,658
SonicMania/Objects/GHZ/BuzzBomber.c
// --------------------------------------------------------------------- // RSDK Project: Sonic Mania // Object Description: BuzzBomber Object // Object Author: Christian Whitehead/Simon Thomley/Hunter Bridges // Decompiled by: Rubberduckycooly & RMGRich // --------------------------------------------------------------------- #include "Game.h" ObjectBuzzBomber *BuzzBomber; void BuzzBomber_Update(void) { RSDK_THIS(BuzzBomber); StateMachine_Run(self->state); } void BuzzBomber_LateUpdate(void) {} void BuzzBomber_StaticUpdate(void) {} void BuzzBomber_Draw(void) { RSDK_THIS(BuzzBomber); if (self->inkEffect == INK_ADD) { RSDK.DrawSprite(&self->animator, NULL, false); } else { RSDK.DrawSprite(&self->animator, NULL, false); self->inkEffect = INK_ALPHA; RSDK.DrawSprite(&self->wingAnimator, NULL, false); self->inkEffect = INK_NONE; RSDK.DrawSprite(&self->thrustAnimator, NULL, false); } } void BuzzBomber_Create(void *data) { RSDK_THIS(BuzzBomber); self->visible = true; self->drawFX |= FX_FLIP; self->drawGroup = Zone->objectDrawGroup[0]; self->startPos.x = self->position.x; self->startPos.y = self->position.y; self->startDir = self->direction; self->timer = 128; self->detectedPlayer = false; self->projectile = NULL; if (!self->shotRange) self->shotRange = 96; self->hitboxRange.right = self->shotRange; self->hitboxRange.left = -self->shotRange; self->hitboxRange.top = -256; self->hitboxRange.bottom = 256; if (data) { self->inkEffect = INK_ADD; self->alpha = 0xC0; self->active = ACTIVE_NORMAL; self->updateRange.x = 0x200000; self->updateRange.y = 0x200000; RSDK.SetSpriteAnimation(BuzzBomber->aniFrames, 4, &self->animator, true, 0); RSDK.SetSpriteAnimation(-1, 0, &self->wingAnimator, true, 0); RSDK.SetSpriteAnimation(-1, 0, &self->thrustAnimator, true, 0); self->state = BuzzBomber_State_ProjectileCharge; } else { self->active = ACTIVE_BOUNDS; self->updateRange.x = 0x800000; self->updateRange.y = 0x800000; RSDK.SetSpriteAnimation(BuzzBomber->aniFrames, 0, &self->animator, true, 0); RSDK.SetSpriteAnimation(BuzzBomber->aniFrames, 2, &self->wingAnimator, true, 0); RSDK.SetSpriteAnimation(BuzzBomber->aniFrames, 3, &self->thrustAnimator, true, 0); self->state = BuzzBomber_State_Init; self->alpha = 0xC0; } } void BuzzBomber_StageLoad(void) { if (RSDK.CheckSceneFolder("GHZ")) BuzzBomber->aniFrames = RSDK.LoadSpriteAnimation("GHZ/BuzzBomber.bin", SCOPE_STAGE); else if (RSDK.CheckSceneFolder("Blueprint")) BuzzBomber->aniFrames = RSDK.LoadSpriteAnimation("Blueprint/BuzzBomber.bin", SCOPE_STAGE); BuzzBomber->hitboxBadnik.left = -24; BuzzBomber->hitboxBadnik.top = -12; BuzzBomber->hitboxBadnik.right = 24; BuzzBomber->hitboxBadnik.bottom = 12; BuzzBomber->hitboxProjectile.left = -6; BuzzBomber->hitboxProjectile.top = -6; BuzzBomber->hitboxProjectile.right = 6; BuzzBomber->hitboxProjectile.bottom = 6; DEBUGMODE_ADD_OBJ(BuzzBomber); } void BuzzBomber_DebugDraw(void) { RSDK.SetSpriteAnimation(BuzzBomber->aniFrames, 0, &DebugMode->animator, true, 0); RSDK.DrawSprite(&DebugMode->animator, NULL, false); } void BuzzBomber_DebugSpawn(void) { RSDK_THIS(DebugMode); EntityBuzzBomber *buzzBomber = CREATE_ENTITY(BuzzBomber, NULL, self->position.x, self->position.y); buzzBomber->direction = self->direction; buzzBomber->startDir = self->direction; } void BuzzBomber_CheckOffScreen(void) { RSDK_THIS(BuzzBomber); if (!RSDK.CheckOnScreen(self, NULL) && !RSDK.CheckPosOnScreen(&self->startPos, &self->updateRange)) { self->position.x = self->startPos.x; self->position.y = self->startPos.y; self->direction = self->startDir; BuzzBomber_Create(NULL); } } void BuzzBomber_CheckPlayerCollisions(void) { RSDK_THIS(BuzzBomber); foreach_active(Player, player) { if (Player_CheckBadnikTouch(player, self, &BuzzBomber->hitboxBadnik)) { if (Player_CheckBadnikBreak(player, self, true)) { if (self->projectile) destroyEntity(self->projectile); } } else if (self->state == BuzzBomber_State_Flying && !self->detectedPlayer) { if (Player_CheckCollisionTouch(player, self, &self->hitboxRange)) { self->detectedPlayer = true; self->timer = 90; RSDK.SetSpriteAnimation(-1, 0, &self->thrustAnimator, true, 0); self->state = BuzzBomber_State_DetectedPlayer; } } } } void BuzzBomber_State_Init(void) { RSDK_THIS(BuzzBomber); self->active = ACTIVE_NORMAL; if (!(self->direction & FLIP_X)) self->velocity.x = -0x40000; else self->velocity.x = 0x40000; self->state = BuzzBomber_State_Flying; BuzzBomber_State_Flying(); } void BuzzBomber_State_Flying(void) { RSDK_THIS(BuzzBomber); self->position.x += self->velocity.x; self->position.y += self->velocity.y; if (!--self->timer) { self->direction ^= FLIP_X; self->timer = 60; self->velocity.x = -self->velocity.x; self->detectedPlayer = false; RSDK.SetSpriteAnimation(-1, 0, &self->thrustAnimator, true, 0); self->state = BuzzBomber_State_Idle; } RSDK.ProcessAnimation(&self->animator); RSDK.ProcessAnimation(&self->wingAnimator); RSDK.ProcessAnimation(&self->thrustAnimator); BuzzBomber_CheckPlayerCollisions(); BuzzBomber_CheckOffScreen(); } void BuzzBomber_State_Idle(void) { RSDK_THIS(BuzzBomber); if (!--self->timer) { self->timer = 128; RSDK.SetSpriteAnimation(BuzzBomber->aniFrames, 3, &self->thrustAnimator, true, 0); self->state = BuzzBomber_State_Flying; } RSDK.ProcessAnimation(&self->animator); RSDK.ProcessAnimation(&self->wingAnimator); BuzzBomber_CheckPlayerCollisions(); BuzzBomber_CheckOffScreen(); } void BuzzBomber_State_DetectedPlayer(void) { RSDK_THIS(BuzzBomber); RSDK.ProcessAnimation(&self->animator); RSDK.ProcessAnimation(&self->wingAnimator); BuzzBomber_CheckPlayerCollisions(); BuzzBomber_CheckOffScreen(); self->timer--; if (self->timer == 82) { RSDK.SetSpriteAnimation(BuzzBomber->aniFrames, 1, &self->animator, true, 0); } else if (self->timer == 45) { EntityBuzzBomber *projectile = CREATE_ENTITY(BuzzBomber, INT_TO_VOID(true), self->position.x, self->position.y); if (self->direction) { projectile->position.x += 0x180000; projectile->velocity.x = 0x20000; } else { projectile->position.x -= 0x180000; projectile->velocity.x = -0x20000; } projectile->position.y += 0x1C0000; projectile->velocity.y = 0x20000; projectile->groundVel = 0; projectile->projectile = (Entity *)self; projectile->direction = self->direction; projectile->active = ACTIVE_NORMAL; self->projectile = (Entity *)projectile; } else if (!self->timer) { RSDK.SetSpriteAnimation(BuzzBomber->aniFrames, 0, &self->animator, true, 0); self->timer = 128; RSDK.SetSpriteAnimation(BuzzBomber->aniFrames, 3, &self->thrustAnimator, true, 0); self->state = BuzzBomber_State_Flying; } } void BuzzBomber_State_ProjectileCharge(void) { RSDK_THIS(BuzzBomber); RSDK.ProcessAnimation(&self->animator); if (self->animator.frameID == 6) { self->state = BuzzBomber_State_ProjectileShot; EntityBuzzBomber *shot = (EntityBuzzBomber *)self->projectile; shot->projectile = NULL; } } void BuzzBomber_State_ProjectileShot(void) { RSDK_THIS(BuzzBomber); self->position.x += self->velocity.x; self->position.y += self->velocity.y; if (RSDK.CheckOnScreen(self, NULL)) { RSDK.ProcessAnimation(&self->animator); foreach_active(Player, player) { if (Player_CheckCollisionTouch(player, self, &BuzzBomber->hitboxProjectile)) Player_ProjectileHurt(player, self); } } else { destroyEntity(self); } } #if GAME_INCLUDE_EDITOR void BuzzBomber_EditorDraw(void) { RSDK_THIS(BuzzBomber); BuzzBomber_Draw(); if (showGizmos()) { RSDK_DRAWING_OVERLAY(true); self->hitboxRange.right = self->shotRange; self->hitboxRange.left = -self->shotRange; self->hitboxRange.top = -256; self->hitboxRange.bottom = 256; DrawHelpers_DrawHitboxOutline(self->position.x, self->position.y, &self->hitboxRange, FLIP_NONE, 0xFF0000); RSDK_DRAWING_OVERLAY(false); } } void BuzzBomber_EditorLoad(void) { if (RSDK.CheckSceneFolder("GHZ")) BuzzBomber->aniFrames = RSDK.LoadSpriteAnimation("GHZ/BuzzBomber.bin", SCOPE_STAGE); else if (RSDK.CheckSceneFolder("Blueprint")) BuzzBomber->aniFrames = RSDK.LoadSpriteAnimation("Blueprint/BuzzBomber.bin", SCOPE_STAGE); RSDK_ACTIVE_VAR(BuzzBomber, direction); RSDK_ENUM_VAR("Left", FLIP_NONE); RSDK_ENUM_VAR("Right", FLIP_X); } #endif void BuzzBomber_Serialize(void) { RSDK_EDITABLE_VAR(BuzzBomber, VAR_UINT8, direction); RSDK_EDITABLE_VAR(BuzzBomber, VAR_UINT8, shotRange); }
411
0.708832
1
0.708832
game-dev
MEDIA
0.80471
game-dev
0.850773
1
0.850773
twhl-community/halflife-unified-sdk
22,368
src/game/client/ui/hud/scoreboard.cpp
/*** * * Copyright (c) 1999, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * Use, distribution, and modification of this source code and/or resulting * object code is restricted to non-commercial enhancements to products from * Valve LLC. All other use, distribution, or modification is prohibited * without written permission from Valve LLC. * ****/ // // Scoreboard.cpp // // implementation of CHudScoreboard class // #include "hud.h" #include "vgui_TeamFortressViewport.h" #include "vgui_ScorePanel.h" #include "ctf/CTFDefs.h" struct icon_sprite_t { char szSpriteName[24]; HSPRITE spr; Rect rc; RGB24 color; unsigned char bFlags; }; icon_sprite_t g_PlayerSpriteList[MAX_PLAYERS_HUD + 1][6]; bool CHudScoreboard::Init() { gHUD.AddHudElem(this); // Hook messages & commands here // RegisterClientCommand("+showscores", &CHudScoreboard::UserCmd_ShowScores, this); // RegisterClientCommand("-showscores", &CHudScoreboard::UserCmd_HideScores, this); g_ClientUserMessages.RegisterHandler("ScoreInfo", &CHudScoreboard::MsgFunc_ScoreInfo, this); g_ClientUserMessages.RegisterHandler("TeamScore", &CHudScoreboard::MsgFunc_TeamScore, this); g_ClientUserMessages.RegisterHandler("TeamInfo", &CHudScoreboard::MsgFunc_TeamInfo, this); g_ClientUserMessages.RegisterHandler("PlayerIcon", &CHudScoreboard::MsgFunc_PlayerIcon, this); g_ClientUserMessages.RegisterHandler("CTFScore", &CHudScoreboard::MsgFunc_CTFScore, this); InitHUDData(); cl_showpacketloss = CVAR_CREATE("cl_showpacketloss", "0", FCVAR_ARCHIVE); return true; } bool CHudScoreboard::VidInit() { // Load sprites here return true; } void CHudScoreboard::InitHUDData() { memset(g_PlayerExtraInfo, 0, sizeof g_PlayerExtraInfo); m_iLastKilledBy = 0; m_fLastKillTime = 0; m_iPlayerNum = 0; m_iNumTeams = 0; memset(g_TeamInfo, 0, sizeof g_TeamInfo); m_iFlags &= ~HUD_ACTIVE; // starts out inactive m_iFlags |= HUD_INTERMISSION; // is always drawn during an intermission memset(g_PlayerSpriteList, 0, sizeof(g_PlayerSpriteList)); } /* The scoreboard We have a minimum width of 1-320 - we could have the field widths scale with it? */ // X positions // relative to the side of the scoreboard #define NAME_RANGE_MIN 20 #define NAME_RANGE_MAX 145 #define KILLS_RANGE_MIN 130 #define KILLS_RANGE_MAX 170 #define DIVIDER_POS 180 #define DEATHS_RANGE_MIN 185 #define DEATHS_RANGE_MAX 210 #define PING_RANGE_MIN 245 #define PING_RANGE_MAX 295 #define PL_RANGE_MIN 295 #define PL_RANGE_MAX 375 #define PL_CTF_RANGE_MIN 345 #define PL_CTF_RANGE_MAX 390 int SCOREBOARD_WIDTH = 320; // Y positions #define ROW_GAP 13 #define ROW_RANGE_MIN 15 #define ROW_RANGE_MAX (ScreenHeight - 50) bool CHudScoreboard::Draw(float fTime) { bool can_show_packetloss = false; int FAR_RIGHT; if (!m_iShowscoresHeld && gHUD.m_Health.m_iHealth > 0) { if (!gHUD.m_iIntermission || gHUD.m_Teamplay == 2) { return true; } } else { if (gHUD.m_iIntermission && gHUD.m_Teamplay == 2) { return true; } } GetAllPlayersInfo(); // Packetloss removed on Kelly 'shipping nazi' Bailey's orders if (cl_showpacketloss && 0 != cl_showpacketloss->value && (ScreenWidth >= 400)) { can_show_packetloss = true; SCOREBOARD_WIDTH = 400; } else { SCOREBOARD_WIDTH = 320; } // just sort the list on the fly // list is sorted first by frags, then by deaths float list_slot = 0; int xpos_rel = (ScreenWidth - SCOREBOARD_WIDTH) / 2; // print the heading line int ypos = ROW_RANGE_MIN + (list_slot * ROW_GAP); int xpos = NAME_RANGE_MIN + xpos_rel; const RGB24 color{255, 140, 0}; if (0 == gHUD.m_Teamplay) gHUD.DrawHudString(xpos, ypos, NAME_RANGE_MAX + xpos_rel, "Player", color); else gHUD.DrawHudString(xpos, ypos, NAME_RANGE_MAX + xpos_rel, "Teams", color); gHUD.DrawHudStringReverse(KILLS_RANGE_MAX + xpos_rel, ypos, 0, "kills", color); gHUD.DrawHudString(DIVIDER_POS + xpos_rel, ypos, ScreenWidth, "/", color); if (gHUD.m_Teamplay == 2) { gHUD.DrawHudString(xpos_rel + 190, ypos, ScreenWidth, "deaths", color); gHUD.DrawHudString(xpos_rel + 240, ypos, ScreenWidth, "/", color); gHUD.DrawHudString(xpos_rel + 255, ypos, ScreenWidth, "scores", color); gHUD.DrawHudString(xpos_rel + 310, ypos, ScreenWidth, "latency", color); if (can_show_packetloss) { gHUD.DrawHudString(xpos_rel + 355, ypos, ScreenWidth, "pkt loss", color); } FAR_RIGHT = can_show_packetloss ? 390 : 345; } else { gHUD.DrawHudString(xpos_rel + 190, ypos, ScreenWidth, "deaths", color); gHUD.DrawHudString(xpos_rel + PING_RANGE_MAX - 35, ypos, ScreenWidth, "latency", color); if (can_show_packetloss) { gHUD.DrawHudString(xpos_rel + PL_RANGE_MAX - 35, ypos, ScreenWidth, "pkt loss", color); } FAR_RIGHT = can_show_packetloss ? PL_RANGE_MAX : PING_RANGE_MAX; } FAR_RIGHT += 5; list_slot += 1.2; ypos = ROW_RANGE_MIN + (list_slot * ROW_GAP); xpos = NAME_RANGE_MIN + xpos_rel; FillRGBA(xpos - 5, ypos, FAR_RIGHT, 1, color, 255); // draw the seperator line list_slot += 0.8; if (0 == gHUD.m_Teamplay) { // it's not teamplay, so just draw a simple player list DrawPlayers(xpos_rel, list_slot); return true; } // clear out team scores for (int i = 1; i <= m_iNumTeams; i++) { if (gHUD.m_Teamplay != 2) { if (!g_TeamInfo[i].scores_overriden) g_TeamInfo[i].frags = g_TeamInfo[i].deaths = 0; } g_TeamInfo[i].ping = g_TeamInfo[i].packetloss = 0; } // recalc the team scores, then draw them for (int i = 1; i < MAX_PLAYERS_HUD; i++) { if (g_PlayerInfoList[i].name == nullptr) continue; // empty player slot, skip if (g_PlayerExtraInfo[i].teamname[0] == 0) continue; // skip over players who are not in a team // find what team this player is in int j; for (j = 1; j <= m_iNumTeams; j++) { if (!stricmp(g_PlayerExtraInfo[i].teamname, g_TeamInfo[j].name)) break; } if (j > m_iNumTeams) // player is not in a team, skip to the next guy continue; if (gHUD.m_Teamplay != 2 && !g_TeamInfo[j].scores_overriden) { g_TeamInfo[j].frags += g_PlayerExtraInfo[i].frags; g_TeamInfo[j].deaths += g_PlayerExtraInfo[i].deaths; } g_TeamInfo[j].ping += g_PlayerInfoList[i].ping; g_TeamInfo[j].packetloss += g_PlayerInfoList[i].packetloss; if (0 != g_PlayerInfoList[i].thisplayer) g_TeamInfo[j].ownteam = true; else g_TeamInfo[j].ownteam = false; } // find team ping/packetloss averages for (int i = 1; i <= m_iNumTeams; i++) { g_TeamInfo[i].already_drawn = false; if (g_TeamInfo[i].players > 0) { g_TeamInfo[i].ping /= g_TeamInfo[i].players; // use the average ping of all the players in the team as the teams ping g_TeamInfo[i].packetloss /= g_TeamInfo[i].players; // use the average ping of all the players in the team as the teams ping } } // Draw the teams while (true) { int highest_frags = -99999; int lowest_deaths = 99999; int best_team = 0; for (int i = 1; i <= m_iNumTeams; i++) { if (g_TeamInfo[i].players <= 0) continue; if (!g_TeamInfo[i].already_drawn && g_TeamInfo[i].frags >= highest_frags) { if (g_TeamInfo[i].frags > highest_frags || g_TeamInfo[i].deaths < lowest_deaths) { best_team = i; lowest_deaths = g_TeamInfo[i].deaths; highest_frags = g_TeamInfo[i].frags; } } } // draw the best team on the scoreboard if (0 == best_team) break; // draw out the best team team_info_t* team_info = &g_TeamInfo[best_team]; ypos = ROW_RANGE_MIN + (list_slot * ROW_GAP); // check we haven't drawn too far down if (ypos > ROW_RANGE_MAX) // don't draw to close to the lower border break; xpos = NAME_RANGE_MIN + xpos_rel; const RGB24 textColor{255, 225, 55}; // draw the stuff kinda yellowish if (team_info->ownteam) // if it is their team, draw the background different color { // overlay the background in blue, then draw the score text over it FillRGBA(NAME_RANGE_MIN + xpos_rel - 5, ypos, FAR_RIGHT, ROW_GAP, {0, 0, 255}, 70); } static char buf[64]; if (gHUD.m_Teamplay != 2) { // draw their name (left to right) gHUD.DrawHudString(xpos, ypos, NAME_RANGE_MAX + xpos_rel, team_info->name, textColor); // draw kills (right to left) xpos = KILLS_RANGE_MAX + xpos_rel; gHUD.DrawHudNumberString(xpos, ypos, KILLS_RANGE_MIN + xpos_rel, team_info->frags, textColor); // draw divider xpos = DIVIDER_POS + xpos_rel; gHUD.DrawHudString(xpos, ypos, xpos + 20, "/", textColor); // draw deaths xpos = DEATHS_RANGE_MAX + xpos_rel; gHUD.DrawHudNumberString(xpos, ypos, DEATHS_RANGE_MIN + xpos_rel, team_info->deaths, textColor); xpos = ((PING_RANGE_MAX - PING_RANGE_MIN) / 2) + PING_RANGE_MIN + xpos_rel + 25; } else { sprintf(buf, "%s Team Score:", team_info->name); gHUD.DrawHudString(xpos, ypos, xpos_rel + 205, buf, textColor); gHUD.DrawHudNumberString(xpos_rel + 275, ypos, xpos_rel + 250, team_info->frags, textColor); xpos = ((PING_RANGE_MAX - PING_RANGE_MIN) / 2) + PING_RANGE_MIN + xpos_rel + 25 + 50; } // draw ping // draw ping & packetloss sprintf(buf, "%d", team_info->ping); gHUD.DrawHudStringReverse(xpos, ypos, xpos - 50, buf, gHUD.m_HudColor); // Packetloss removed on Kelly 'shipping nazi' Bailey's orders if (can_show_packetloss) { xpos = ((PL_RANGE_MAX - PL_RANGE_MIN) / 2) + PL_RANGE_MIN + xpos_rel + 25 + 10; sprintf(buf, " %d", team_info->packetloss); gHUD.DrawHudString(xpos, ypos, xpos + 50, buf, gHUD.m_HudColor); } team_info->already_drawn = true; // set the already_drawn to be true, so this team won't get drawn again list_slot++; // draw all the players that belong to this team, indented slightly list_slot = DrawPlayers(xpos_rel, list_slot, 10, team_info->name); } // draw all the players who are not in a team list_slot += 0.5; DrawPlayers(xpos_rel, list_slot, 0, ""); return true; } // returns the ypos where it finishes drawing int CHudScoreboard::DrawPlayers(int xpos_rel, float list_slot, int nameoffset, const char* team) { bool can_show_packetloss = false; int FAR_RIGHT; // Packetloss removed on Kelly 'shipping nazi' Bailey's orders if (cl_showpacketloss && 0 != cl_showpacketloss->value && (ScreenWidth >= 400)) { can_show_packetloss = true; SCOREBOARD_WIDTH = 400; } else { SCOREBOARD_WIDTH = 320; } if (gHUD.m_Teamplay == 2) { FAR_RIGHT = can_show_packetloss ? PL_CTF_RANGE_MAX : PL_CTF_RANGE_MIN; } else { FAR_RIGHT = can_show_packetloss ? PL_RANGE_MAX : PING_RANGE_MAX; } FAR_RIGHT += 5; // draw the players, in order, and restricted to team if set while (true) { // Find the top ranking player int highest_frags = -99999; int lowest_deaths = 99999; int best_player = 0; for (int i = 1; i < MAX_PLAYERS_HUD; i++) { if (g_PlayerInfoList[i].name && (g_PlayerExtraInfo[i].frags + g_PlayerExtraInfo[i].flagcaptures) >= highest_frags) { if (!(team && stricmp(g_PlayerExtraInfo[i].teamname, team))) // make sure it is the specified team { extra_player_info_t* pl_info = &g_PlayerExtraInfo[i]; if ((pl_info->frags + pl_info->flagcaptures) > highest_frags || pl_info->deaths < lowest_deaths) { best_player = i; lowest_deaths = pl_info->deaths; highest_frags = (pl_info->frags + pl_info->flagcaptures); } } } } if (0 == best_player) break; // draw out the best player hud_player_info_t* pl_info = &g_PlayerInfoList[best_player]; int ypos = ROW_RANGE_MIN + (list_slot * ROW_GAP); // check we haven't drawn too far down if (ypos > ROW_RANGE_MAX) // don't draw to close to the lower border break; int xpos_icon = xpos_rel; for (int icon = 0; icon < 6; ++icon) { const auto& sprite = g_PlayerSpriteList[best_player][icon]; if (0 != sprite.spr) { SPR_Set(sprite.spr, sprite.color); gEngfuncs.pfnSPR_DrawAdditive(0, xpos_icon, ypos, &sprite.rc); xpos_icon += sprite.rc.left - sprite.rc.right - 5; } } int xpos = NAME_RANGE_MIN + xpos_rel; RGB24 textColor{255, 255, 255}; if (best_player == m_iLastKilledBy && 0 != m_fLastKillTime && m_fLastKillTime > gHUD.m_flTime) { if (0 != pl_info->thisplayer) { // green is the suicide color? i wish this could do grey... FillRGBA(NAME_RANGE_MIN + xpos_rel - 5, ypos, FAR_RIGHT, ROW_GAP, {80, 155, 0}, 70); } else { // Highlight the killers name - overlay the background in red, then draw the score text over it FillRGBA(NAME_RANGE_MIN + xpos_rel - 5, ypos, FAR_RIGHT, ROW_GAP, {255, 0, 0}, ((float)15 * (float)(m_fLastKillTime - gHUD.m_flTime))); } } else if (0 != pl_info->thisplayer) // if it is their name, draw it a different color { // overlay the background in blue, then draw the score text over it FillRGBA(NAME_RANGE_MIN + xpos_rel - 5, ypos, FAR_RIGHT, ROW_GAP, {0, 0, 255}, 70); } // draw their name (left to right) gHUD.DrawHudString(xpos + nameoffset, ypos, NAME_RANGE_MAX + xpos_rel, pl_info->name, textColor); // draw kills (right to left) xpos = KILLS_RANGE_MAX + xpos_rel; gHUD.DrawHudNumberString(xpos, ypos, KILLS_RANGE_MIN + xpos_rel, g_PlayerExtraInfo[best_player].frags, textColor); // draw divider xpos = DIVIDER_POS + xpos_rel; gHUD.DrawHudString(xpos, ypos, xpos + 20, "/", textColor); // draw deaths if (gHUD.m_Teamplay == 2) { gHUD.DrawHudNumberString(xpos_rel + 230, ypos, xpos_rel + DEATHS_RANGE_MIN, g_PlayerExtraInfo[best_player].deaths, textColor); gHUD.DrawHudString(xpos_rel + 240, ypos, xpos_rel + 260, "/", textColor); gHUD.DrawHudNumberString(xpos_rel + 275, ypos, xpos_rel + 250, g_PlayerExtraInfo[best_player].flagcaptures, textColor); } else { gHUD.DrawHudNumberString(xpos_rel + DEATHS_RANGE_MAX, ypos, xpos_rel + DEATHS_RANGE_MIN, g_PlayerExtraInfo[best_player].deaths, textColor); } // draw ping & packetloss static char buf[64]; sprintf(buf, "%d", g_PlayerInfoList[best_player].ping); xpos = ((PING_RANGE_MAX - PING_RANGE_MIN) / 2) + PING_RANGE_MIN + xpos_rel + 25; if (gHUD.m_Teamplay == 2) { xpos = xpos_rel + 345; } gHUD.DrawHudStringReverse(xpos, ypos, xpos - 50, buf, textColor); // Packetloss removed on Kelly 'shipping nazi' Bailey's orders if (can_show_packetloss) { if (g_PlayerInfoList[best_player].packetloss >= 63) { textColor = RGB_REDISH; sprintf(buf, " !!!!"); } else { sprintf(buf, " %d", g_PlayerInfoList[best_player].packetloss); } xpos = ((PL_RANGE_MAX - PL_RANGE_MIN) / 2) + PL_RANGE_MIN + xpos_rel + 25 + 10; if (gHUD.m_Teamplay == 2) { xpos = xpos_rel + 385; } gHUD.DrawHudString(xpos, ypos, xpos + 50, buf, textColor); } pl_info->name = nullptr; // set the name to be nullptr, so this client won't get drawn again list_slot++; } return list_slot; } void CHudScoreboard::GetAllPlayersInfo() { for (int i = 1; i < MAX_PLAYERS_HUD; i++) { gEngfuncs.pfnGetPlayerInfo(i, &g_PlayerInfoList[i]); if (0 != g_PlayerInfoList[i].thisplayer) m_iPlayerNum = i; // !!!HACK: this should be initialized elsewhere... maybe gotten from the engine } } void CHudScoreboard::MsgFunc_ScoreInfo(const char* pszName, BufferReader& reader) { m_iFlags |= HUD_ACTIVE; short cl = reader.ReadByte(); short frags = reader.ReadShort(); short deaths = reader.ReadShort(); short playerclass = reader.ReadShort(); short teamnumber = reader.ReadShort(); if (cl > 0 && cl <= MAX_PLAYERS_HUD) { g_PlayerExtraInfo[cl].frags = frags; g_PlayerExtraInfo[cl].deaths = deaths; g_PlayerExtraInfo[cl].playerclass = playerclass; g_PlayerExtraInfo[cl].teamnumber = teamnumber; gViewPort->UpdateOnPlayerInfo(); } } // Message handler for TeamInfo message // accepts two values: // byte: client number // string: client team name void CHudScoreboard::MsgFunc_TeamInfo(const char* pszName, BufferReader& reader) { short cl = reader.ReadByte(); if (cl > 0 && cl <= MAX_PLAYERS_HUD) { // set the players team strncpy(g_PlayerExtraInfo[cl].teamname, reader.ReadString(), MAX_TEAM_NAME); if (gHUD.m_Teamplay == 2) { g_PlayerExtraInfo[cl].teamid = reader.ReadByte(); } } if (gViewPort && gViewPort->m_pScoreBoard) { m_iNumTeams = gViewPort->m_pScoreBoard->RebuildTeams(); return; } // rebuild the list of teams // clear out player counts from teams for (int i = 1; i <= m_iNumTeams; i++) { g_TeamInfo[i].players = 0; } // rebuild the team list GetAllPlayersInfo(); m_iNumTeams = 0; for (int i = 1; i < MAX_PLAYERS_HUD; i++) { if (g_PlayerInfoList[i].name == nullptr) continue; if (g_PlayerExtraInfo[i].teamname[0] == 0) continue; // skip over players who are not in a team // is this player in an existing team? int j; for (j = 1; j <= m_iNumTeams; j++) { if (g_TeamInfo[j].name[0] == '\0') break; if (!stricmp(g_PlayerExtraInfo[i].teamname, g_TeamInfo[j].name)) break; } if (j > m_iNumTeams) { // they aren't in a listed team, so make a new one // search through for an empty team slot for (j = 1; j <= m_iNumTeams; j++) { if (g_TeamInfo[j].name[0] == '\0') break; } m_iNumTeams = std::max(j, m_iNumTeams); strncpy(g_TeamInfo[j].name, g_PlayerExtraInfo[i].teamname, MAX_TEAM_NAME); g_TeamInfo[j].players = 0; } g_TeamInfo[j].players++; } // clear out any empty teams for (int i = 1; i <= m_iNumTeams; i++) { if (g_TeamInfo[i].players < 1) memset(&g_TeamInfo[i], 0, sizeof(team_info_t)); } } // Message handler for TeamScore message // accepts three values: // string: team name // short: teams kills // short: teams deaths // if this message is never received, then scores will simply be the combined totals of the players. void CHudScoreboard::MsgFunc_TeamScore(const char* pszName, BufferReader& reader) { char* TeamName = reader.ReadString(); // find the team matching the name int i; for (i = 1; i <= m_iNumTeams; i++) { if (!stricmp(TeamName, g_TeamInfo[i].name)) break; } if (i > m_iNumTeams) return; // use this new score data instead of combined player scores g_TeamInfo[i].scores_overriden = true; g_TeamInfo[i].frags = reader.ReadShort(); g_TeamInfo[i].deaths = reader.ReadShort(); } void CHudScoreboard::MsgFunc_PlayerIcon(const char* pszName, BufferReader& reader) { const short playerIndex = reader.ReadByte(); const bool isActive = 0 != reader.ReadByte(); const int iconIndex = reader.ReadByte(); const unsigned char itemId = reader.ReadByte(); if (playerIndex > MAX_PLAYERS_HUD) return; if (!isActive) { for (int i = 0; i < 6; ++i) { if ((itemId & g_PlayerSpriteList[playerIndex][i].bFlags) != 0) { memset(&g_PlayerSpriteList[playerIndex][i], 0, sizeof(g_PlayerSpriteList[playerIndex][i])); } } return; } if (0 == itemId) { memset(&g_PlayerSpriteList[playerIndex][iconIndex], 0, sizeof(g_PlayerSpriteList[playerIndex][iconIndex])); return; } for (int i = 0, id = CTFItem::BlackMesaFlag; i < 2; ++i, id <<= 1) { if ((itemId & id) == 0) { continue; } const int spriteIndex = gHUD.GetSpriteIndex("score_flag"); auto& sprite = g_PlayerSpriteList[playerIndex][0]; sprite.spr = gHUD.GetSprite(spriteIndex); sprite.rc = gHUD.GetSpriteRect(spriteIndex); sprite.bFlags = itemId; sprite.color = id == CTFItem::BlackMesaFlag ? RGB_YELLOWISH : RGB_GREENISH; strcpy(sprite.szSpriteName, "score_flag"); return; } for (int i = 1; i < 6; ++i) { if ((itemId & g_PlayerSpriteList[playerIndex][i].bFlags) != 0) { return; } } // Find an empty sprite slot for (int i = 1; i < 6; ++i) { auto& sprite = g_PlayerSpriteList[playerIndex][i]; if (0 == sprite.spr) { if ((itemId & CTFItem::LongJump) != 0) { const int spriteIndex = gHUD.GetSpriteIndex("score_ctfljump"); sprite.spr = gHUD.GetSprite(spriteIndex); sprite.rc = gHUD.GetSpriteRect(spriteIndex); sprite.bFlags = itemId; sprite.color = {255, 160, 0}; strcpy(sprite.szSpriteName, "score_ctfljump"); } else if ((itemId & CTFItem::PortableHEV) != 0) { const int spriteIndex = gHUD.GetSpriteIndex("score_ctfphev"); sprite.spr = gHUD.GetSprite(spriteIndex); sprite.rc = gHUD.GetSpriteRect(spriteIndex); sprite.bFlags = itemId; sprite.color = {128, 160, 255}; strcpy(sprite.szSpriteName, "score_ctfphev"); } else if ((itemId & CTFItem::Backpack) != 0) { const int spriteIndex = gHUD.GetSpriteIndex("score_ctfbpack"); sprite.spr = gHUD.GetSprite(spriteIndex); sprite.rc = gHUD.GetSpriteRect(spriteIndex); sprite.bFlags = itemId; sprite.color = {255, 255, 0}; strcpy(sprite.szSpriteName, "score_ctfbpack"); } else if ((itemId & CTFItem::Acceleration) != 0) { const int spriteIndex = gHUD.GetSpriteIndex("score_ctfaccel"); sprite.spr = gHUD.GetSprite(spriteIndex); sprite.rc = gHUD.GetSpriteRect(spriteIndex); sprite.bFlags = itemId; sprite.color = {255, 0, 0}; strcpy(sprite.szSpriteName, "score_ctfaccel"); } else if ((itemId & CTFItem::Regeneration) != 0) { const int spriteIndex = gHUD.GetSpriteIndex("score_ctfregen"); sprite.spr = gHUD.GetSprite(spriteIndex); sprite.rc = gHUD.GetSpriteRect(spriteIndex); sprite.bFlags = itemId; sprite.color = {0, 255, 0}; strcpy(sprite.szSpriteName, "score_ctfregen"); } break; } } m_iFlags |= HUD_ACTIVE; } void CHudScoreboard::MsgFunc_CTFScore(const char* pszName, BufferReader& reader) { const int playerIndex = reader.ReadByte(); const int score = reader.ReadByte(); if (playerIndex >= 1 && playerIndex <= MAX_PLAYERS_HUD) { g_PlayerExtraInfo[playerIndex].flagcaptures = score; } } void CHudScoreboard::DeathMsg(int killer, int victim) { // if we were the one killed, or the world killed us, set the scoreboard to indicate suicide if (victim == m_iPlayerNum || killer == 0) { m_iLastKilledBy = 0 != killer ? killer : m_iPlayerNum; m_fLastKillTime = gHUD.m_flTime + 10; // display who we were killed by for 10 seconds if (killer == m_iPlayerNum) m_iLastKilledBy = m_iPlayerNum; } } void CHudScoreboard::UserCmd_ShowScores() { m_iShowscoresHeld = true; } void CHudScoreboard::UserCmd_HideScores() { m_iShowscoresHeld = false; }
411
0.893262
1
0.893262
game-dev
MEDIA
0.851464
game-dev
0.929899
1
0.929899
magefree/mage
1,062
Mage.Sets/src/mage/cards/p/PrimocEscapee.java
package mage.cards.p; import java.util.UUID; import mage.MageInt; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.keyword.CyclingAbility; import mage.abilities.keyword.FlyingAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; /** * * @author North */ public final class PrimocEscapee extends CardImpl { public PrimocEscapee(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{6}{U}"); this.subtype.add(SubType.BIRD); this.subtype.add(SubType.BEAST); this.power = new MageInt(4); this.toughness = new MageInt(4); // Flying this.addAbility(FlyingAbility.getInstance()); // Cycling {2} this.addAbility(new CyclingAbility(new ManaCostsImpl<>("{2}"))); } private PrimocEscapee(final PrimocEscapee card) { super(card); } @Override public PrimocEscapee copy() { return new PrimocEscapee(this); } }
411
0.899882
1
0.899882
game-dev
MEDIA
0.94382
game-dev
0.974015
1
0.974015
shit-ware/IW4
5,141
ui/menu_online_ended.menu
{ menuDef { name "menu_online_ended" rect -150 -104 300 104 2 2 popup legacySplitScreenScale visible 1 style 1 forecolor 1 1 1 1 backcolor 1 1 1 1 background "white" focuscolor 1 1 1 1 fadeCycle 1 fadeClamp 1 fadeAmount 0.1 onOpen { setLocalVarInt "ui_centerPopup" ( 1 ); } onClose { setLocalVarInt "ui_centerPopup" ( 0 ); execnow "nosplitscreen"; resolveError; } onEsc { close self; } itemDef { rect -854 -480 1708 960 0 0 decoration visible 1 style 1 forecolor 1 1 1 1 backcolor 0 0 0 0.35 background "white" textscale 0.55 } itemDef { rect -854 -480 1708 960 0 0 decoration visible 1 style 1 forecolor 1 1 1 1 backcolor 1 1 1 1 background "xpbar_stencilbase" textscale 0.55 } itemDef { rect 0 0 300 104 0 0 decoration visible 1 style 1 forecolor 1 1 1 1 backcolor 0.5 0.5 0.5 1 background "white" textscale 0.55 } itemDef { rect 0 0 1708 480 0 0 decoration visible 1 style 3 forecolor 1 1 1 0.75 background "mw2_popup_bg_fogstencil" textscale 0.55 exp rect x ( 0 - ( ( float( milliseconds( ) % 60000 ) / 60000 ) * ( 854 ) ) ) } itemDef { rect 0 0 -1708 -480 0 0 decoration visible 1 style 3 forecolor 0.85 0.85 0.85 1 background "mw2_popup_bg_fogscroll" textscale 0.55 exp rect x ( 0 - ( ( float( milliseconds( ) % 60000 ) / 60000 ) * ( 854 ) ) ) } itemDef { rect 0 0 300 0 0 0 decoration visible 1 style 3 forecolor 1 1 1 1 background "mockup_popup_bg_stencilfill" textscale 0.55 exp rect h ( ( 24 + 4 * 20 ) ) } itemDef { rect 0 0 -1708 -480 0 0 decoration visible 1 style 3 forecolor 1 1 1 0.75 background "mw2_popup_bg_fogstencil" textscale 0.55 exp rect x ( ( - 854 ) + ( ( float( milliseconds( ) % 50000 ) / 50000 ) * ( 854 ) ) ) } itemDef { rect 0 0 -1708 -480 0 0 decoration visible 1 style 3 forecolor 0.85 0.85 0.85 1 background "mw2_popup_bg_fogscroll" textscale 0.55 exp rect x ( ( - 854 ) + ( ( float( milliseconds( ) % 50000 ) / 50000 ) * ( 854 ) ) ) } itemDef { rect 0 0 300 0 1 1 decoration visible 1 style 3 forecolor 1 1 1 0 background "small_box_lightfx" textscale 0.55 exp rect h ( ( 24 + 4 * 20 ) ) } itemDef { rect -64 -64 64 64 0 0 decoration visible 1 style 3 forecolor 0 0 0 1 background "drop_shadow_tl" textscale 0.55 visible when ( 1 ) } itemDef { rect 0 -64 300 64 0 0 decoration visible 1 style 3 forecolor 0 0 0 1 background "drop_shadow_t" textscale 0.55 visible when ( 1 ) } itemDef { rect 300 -64 64 64 0 0 decoration visible 1 style 3 forecolor 0 0 0 1 background "drop_shadow_tr" textscale 0.55 visible when ( 1 ) } itemDef { rect 300 0 64 0 0 0 decoration visible 1 style 3 forecolor 0 0 0 1 background "drop_shadow_r" textscale 0.55 exp rect h ( ( 24 + 4 * 20 ) ) visible when ( 1 ) } itemDef { rect 300 0 64 64 0 0 decoration visible 1 style 3 forecolor 0 0 0 1 background "drop_shadow_br" textscale 0.55 exp rect y ( ( 0 - 0 ) + ( ( 24 + 4 * 20 ) ) ) visible when ( 1 ) } itemDef { rect 0 0 300 64 0 0 decoration visible 1 style 3 forecolor 0 0 0 1 background "drop_shadow_b" textscale 0.55 exp rect y ( ( 0 - 0 ) + ( ( 24 + 4 * 20 ) ) ) visible when ( 1 ) } itemDef { rect -64 0 64 64 0 0 decoration visible 1 style 3 forecolor 0 0 0 1 background "drop_shadow_bl" textscale 0.55 exp rect y ( ( 0 - 0 ) + ( ( 24 + 4 * 20 ) ) ) visible when ( 1 ) } itemDef { rect -64 0 64 0 0 0 decoration visible 1 style 3 forecolor 0 0 0 1 background "drop_shadow_l" textscale 0.55 exp rect h ( ( 24 + 4 * 20 ) ) visible when ( 1 ) } itemDef { rect 0 0 300 24 0 0 decoration visible 1 style 1 forecolor 1 1 1 1 background "gradient_fadein" textfont 9 textalign 5 textalignx -4 textscale 0.375 text "@MENU_NOTICE" } itemDef { rect 4 20 292 42 0 0 decoration autowrapped visible 1 style 1 forecolor 1 1 1 1 textfont 3 textalign 5 textscale 0.375 visible when ( 1 ) exp text ( dvarstring( "online_end_reason" ) ) } itemDef { name "ok" rect 4 84 292 20 0 0 visible 1 group "mw2_popup_button" style 1 forecolor 1 1 1 1 disablecolor 0.6 0.55 0.55 1 background "popup_button_selection_bar" type 1 textfont 3 textalign 6 textalignx -24 textscale 0.375 text "@MENU_OK" visible when ( 1 ) action { play "mouse_click"; close self; } onFocus { play "mouse_over"; if ( dvarstring( "gameMode" ) != "mp" ) { setItemColor "mw2_popup_button" backcolor 0 0 0 0; } setItemColor self backcolor 0 0 0 1; setLocalVarBool "ui_popupAButton" ( 1 ); } leaveFocus { setItemColor self backcolor 1 1 1 0; setLocalVarBool "ui_popupAButton" ( 0 ); } } } }
411
0.70971
1
0.70971
game-dev
MEDIA
0.670403
game-dev,desktop-app
0.895335
1
0.895335
Admer456/halflife-adm
10,613
src/game/server/entities/NPCs/racex/shockroach.cpp
/*** * * Copyright (c) 1996-2001, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * This source code contains proprietary and confidential information of * Valve LLC and its suppliers. Access to this code is restricted to * persons who have executed a written SDK license with Valve. Any access, * use or distribution of this code by or to any unlicensed person is illegal. * ****/ #include "cbase.h" #define SR_AE_JUMPATTACK (2) Task_t tlSRRangeAttack1[] = { {TASK_STOP_MOVING, (float)0}, {TASK_FACE_IDEAL, (float)0}, {TASK_RANGE_ATTACK1, (float)0}, {TASK_SET_ACTIVITY, (float)ACT_IDLE}, {TASK_FACE_IDEAL, (float)0}, {TASK_WAIT_RANDOM, (float)0.5}, }; Schedule_t slRCRangeAttack1[] = { {tlSRRangeAttack1, std::size(tlSRRangeAttack1), bits_COND_ENEMY_OCCLUDED | bits_COND_NO_AMMO_LOADED, 0, "HCRangeAttack1"}, }; Task_t tlSRRangeAttack1Fast[] = { {TASK_STOP_MOVING, (float)0}, {TASK_FACE_IDEAL, (float)0}, {TASK_RANGE_ATTACK1, (float)0}, {TASK_SET_ACTIVITY, (float)ACT_IDLE}, }; Schedule_t slRCRangeAttack1Fast[] = { {tlSRRangeAttack1Fast, std::size(tlSRRangeAttack1Fast), bits_COND_ENEMY_OCCLUDED | bits_COND_NO_AMMO_LOADED, 0, "HCRAFast"}, }; class COFShockRoach : public CBaseMonster { DECLARE_CLASS(COFShockRoach, CBaseMonster); DECLARE_DATAMAP(); DECLARE_CUSTOM_SCHEDULES(); public: void OnCreate() override; void Spawn() override; void Precache() override; void RunTask(const Task_t* pTask) override; void StartTask(const Task_t* pTask) override; void SetYawSpeed() override; bool HasAlienGibs() override { return true; } /** * @brief this is the shock roach's touch function when it is in the air */ void LeapTouch(CBaseEntity* pOther); /** * @brief returns the real center of the shock roach. * The bounding box is much larger than the actual creature so this is needed for targeting */ Vector Center() override; Vector BodyTarget(const Vector& posSrc) override; void PainSound() override; void DeathSound() override; void IdleSound() override; void AlertSound() override; void PrescheduleThink() override; void HandleAnimEvent(MonsterEvent_t* pEvent) override; bool CheckRangeAttack1(float flDot, float flDist) override; bool CheckRangeAttack2(float flDot, float flDist) override; bool TakeDamage(CBaseEntity* inflictor, CBaseEntity* attacker, float flDamage, int bitsDamageType) override; virtual float GetDamageAmount() { return GetSkillFloat("shockroach_dmg_bite"sv); } virtual int GetVoicePitch() { return 100; } virtual float GetSoundVolue() { return 1.0; } const Schedule_t* GetScheduleOfType(int Type) override; void MonsterThink() override; float m_flBirthTime; bool m_fRoachSolid; static const char* pIdleSounds[]; static const char* pAlertSounds[]; static const char* pPainSounds[]; static const char* pAttackSounds[]; static const char* pDeathSounds[]; static const char* pBiteSounds[]; }; LINK_ENTITY_TO_CLASS(monster_shockroach, COFShockRoach); BEGIN_DATAMAP(COFShockRoach) DEFINE_FIELD(m_flBirthTime, FIELD_TIME), DEFINE_FUNCTION(LeapTouch), END_DATAMAP(); BEGIN_CUSTOM_SCHEDULES(COFShockRoach) slRCRangeAttack1, slRCRangeAttack1Fast END_CUSTOM_SCHEDULES(); const char* COFShockRoach::pIdleSounds[] = { "shockroach/shock_idle1.wav", "shockroach/shock_idle2.wav", "shockroach/shock_idle3.wav", }; const char* COFShockRoach::pAlertSounds[] = { "shockroach/shock_angry.wav", }; const char* COFShockRoach::pPainSounds[] = { "shockroach/shock_flinch.wav", }; const char* COFShockRoach::pAttackSounds[] = { "shockroach/shock_jump1.wav", "shockroach/shock_jump2.wav", }; const char* COFShockRoach::pDeathSounds[] = { "shockroach/shock_die.wav", }; const char* COFShockRoach::pBiteSounds[] = { "shockroach/shock_bite.wav", }; void COFShockRoach::OnCreate() { CBaseMonster::OnCreate(); pev->health = GetSkillFloat("shockroach_health"sv); pev->model = MAKE_STRING("models/w_shock_rifle.mdl"); SetClassification("alien_prey"); } Vector COFShockRoach::Center() { return Vector(pev->origin.x, pev->origin.y, pev->origin.z + 6); } Vector COFShockRoach::BodyTarget(const Vector& posSrc) { return Center(); } void COFShockRoach::SetYawSpeed() { int ys; switch (m_Activity) { case ACT_IDLE: case ACT_LEAP: case ACT_FALL: case ACT_TURN_LEFT: case ACT_TURN_RIGHT: ys = 90; break; default: ys = 30; break; } pev->yaw_speed = ys; } void COFShockRoach::HandleAnimEvent(MonsterEvent_t* pEvent) { switch (pEvent->event) { case SR_AE_JUMPATTACK: { ClearBits(pev->flags, FL_ONGROUND); SetOrigin(pev->origin + Vector(0, 0, 1)); // take him off ground so engine doesn't instantly reset onground UTIL_MakeVectors(pev->angles); Vector vecJumpDir; if (m_hEnemy != nullptr) { float gravity = g_psv_gravity->value; if (gravity <= 1) gravity = 1; // How fast does the headcrab need to travel to reach that height given gravity? float height = (m_hEnemy->pev->origin.z + m_hEnemy->pev->view_ofs.z - pev->origin.z); if (height < 16) height = 16; float speed = sqrt(2 * gravity * height); float time = speed / gravity; // Scale the sideways velocity to get there at the right time vecJumpDir = (m_hEnemy->pev->origin + m_hEnemy->pev->view_ofs - pev->origin); vecJumpDir = vecJumpDir * (1.0 / time); // Speed to offset gravity at the desired height vecJumpDir.z = speed; // Don't jump too far/fast float distance = vecJumpDir.Length(); if (distance > 650) { vecJumpDir = vecJumpDir * (650.0 / distance); } } else { // jump hop, don't care where vecJumpDir = Vector(gpGlobals->v_forward.x, gpGlobals->v_forward.y, gpGlobals->v_up.z) * 350; } // Not used for Shock Roach // int iSound = RANDOM_LONG(0,2); // if ( iSound != 0 ) // EmitSoundDyn(CHAN_VOICE, pAttackSounds[iSound], GetSoundVolue(), ATTN_IDLE, 0, GetVoicePitch()); pev->velocity = vecJumpDir; m_flNextAttack = gpGlobals->time + 2; } break; default: CBaseMonster::HandleAnimEvent(pEvent); break; } } void COFShockRoach::Spawn() { Precache(); SetModel(STRING(pev->model)); SetSize(Vector(-12, -12, 0), Vector(12, 12, 4)); pev->solid = SOLID_SLIDEBOX; pev->movetype = MOVETYPE_FLY; m_bloodColor = BLOOD_COLOR_GREEN; pev->effects = 0; pev->view_ofs = Vector(0, 0, 20); // position of the eyes relative to monster's origin. pev->yaw_speed = 5; //!!! should we put this in the monster's changeanim function since turn rates may vary with state/anim? m_flFieldOfView = 0.5; // indicates the width of this monster's forward view cone ( as a dotproduct result ) m_MonsterState = MONSTERSTATE_NONE; m_fRoachSolid = false; m_flBirthTime = gpGlobals->time; MonsterInit(); } void COFShockRoach::Precache() { PRECACHE_SOUND_ARRAY(pIdleSounds); PRECACHE_SOUND_ARRAY(pAlertSounds); PRECACHE_SOUND_ARRAY(pPainSounds); PRECACHE_SOUND_ARRAY(pAttackSounds); PRECACHE_SOUND_ARRAY(pDeathSounds); PRECACHE_SOUND_ARRAY(pBiteSounds); PrecacheSound("shockroach/shock_walk.wav"); PrecacheModel(STRING(pev->model)); } void COFShockRoach::RunTask(const Task_t* pTask) { switch (pTask->iTask) { case TASK_RANGE_ATTACK1: case TASK_RANGE_ATTACK2: { if (m_fSequenceFinished) { TaskComplete(); SetTouch(nullptr); m_IdealActivity = ACT_IDLE; } break; } default: { CBaseMonster::RunTask(pTask); } } } void COFShockRoach::LeapTouch(CBaseEntity* pOther) { if (0 == pOther->pev->takedamage) { return; } if (pOther->Classify() == Classify()) { return; } // Give the player a shock rifle if they don't have one if (auto player = ToBasePlayer(pOther); player) { if (!player->HasNamedPlayerWeapon("weapon_shockrifle")) { player->GiveNamedItem("weapon_shockrifle"); SetTouch(nullptr); UTIL_Remove(this); return; } } // Don't hit if back on ground if (!FBitSet(pev->flags, FL_ONGROUND)) { EmitSoundDyn(CHAN_WEAPON, RANDOM_SOUND_ARRAY(pBiteSounds), GetSoundVolue(), ATTN_IDLE, 0, GetVoicePitch()); pOther->TakeDamage(this, this, GetDamageAmount(), DMG_SLASH); } SetTouch(nullptr); } void COFShockRoach::PrescheduleThink() { // make the crab coo a little bit in combat state if (m_MonsterState == MONSTERSTATE_COMBAT && RANDOM_FLOAT(0, 5) < 0.1) { IdleSound(); } } void COFShockRoach::StartTask(const Task_t* pTask) { m_iTaskStatus = TASKSTATUS_RUNNING; switch (pTask->iTask) { case TASK_RANGE_ATTACK1: { EmitSoundDyn(CHAN_WEAPON, pAttackSounds[0], GetSoundVolue(), ATTN_IDLE, 0, GetVoicePitch()); m_IdealActivity = ACT_RANGE_ATTACK1; SetTouch(&COFShockRoach::LeapTouch); break; } default: { CBaseMonster::StartTask(pTask); } } } bool COFShockRoach::CheckRangeAttack1(float flDot, float flDist) { if (FBitSet(pev->flags, FL_ONGROUND) && flDist <= 256 && flDot >= 0.65) { return true; } return false; } bool COFShockRoach::CheckRangeAttack2(float flDot, float flDist) { return false; // BUGBUG: Why is this code here? There is no ACT_RANGE_ATTACK2 animation. I've disabled it for now. #if 0 if (FBitSet(pev->flags, FL_ONGROUND) && flDist > 64 && flDist <= 256 && flDot >= 0.5) { return true; } return false; #endif } bool COFShockRoach::TakeDamage(CBaseEntity* inflictor, CBaseEntity* attacker, float flDamage, int bitsDamageType) { // Don't take any acid damage -- BigMomma's mortar is acid if ((bitsDamageType & DMG_ACID) != 0) flDamage = 0; // Don't take damage while spawning if (gpGlobals->time - m_flBirthTime < 2) flDamage = 0; // Never gib the roach return CBaseMonster::TakeDamage(inflictor, attacker, flDamage, (bitsDamageType & ~DMG_ALWAYSGIB) | DMG_NEVERGIB); } void COFShockRoach::IdleSound() { } void COFShockRoach::AlertSound() { } void COFShockRoach::PainSound() { } void COFShockRoach::DeathSound() { } const Schedule_t* COFShockRoach::GetScheduleOfType(int Type) { switch (Type) { case SCHED_RANGE_ATTACK1: { return &slRCRangeAttack1[0]; } break; } return CBaseMonster::GetScheduleOfType(Type); } void COFShockRoach::MonsterThink() { const auto lifeTime = gpGlobals->time - m_flBirthTime; if (lifeTime >= 0.2) { pev->movetype = MOVETYPE_STEP; } if (!m_fRoachSolid && lifeTime >= 2.0) { SetSize(Vector(-12, -12, 0), Vector(12, 12, 4)); m_fRoachSolid = true; } if (lifeTime >= GetSkillFloat("shockroach_lifespan"sv)) TakeDamage(this, this, pev->health, DMG_NEVERGIB); CBaseMonster::MonsterThink(); }
411
0.89958
1
0.89958
game-dev
MEDIA
0.990174
game-dev
0.847593
1
0.847593
bit-bots/bitbots_main
6,945
bitbots_motion/bitbots_dynamic_kick/include/bitbots_dynamic_kick/kick_engine.hpp
#ifndef BITBOTS_DYNAMIC_KICK_INCLUDE_BITBOTS_DYNAMIC_KICK_KICK_ENGINE_H_ #define BITBOTS_DYNAMIC_KICK_INCLUDE_BITBOTS_DYNAMIC_KICK_KICK_ENGINE_H_ #include <rot_conv/rot_conv.h> #include <Eigen/Geometry> #include <bitbots_msgs/action/kick.hpp> #include <bitbots_splines/abstract_engine.hpp> #include <bitbots_splines/pose_spline.hpp> #include <bitbots_splines/position_spline.hpp> #include <cmath> #include <optional> #include <tf2/convert.hpp> #include <tf2/exceptions.hpp> #include <tf2/utils.hpp> #include <tf2_eigen/tf2_eigen.hpp> #include <tf2_geometry_msgs/tf2_geometry_msgs.hpp> #include "stabilizer.hpp" #include "visualizer.hpp" namespace bitbots_dynamic_kick { struct KickParams { double foot_rise; double foot_distance; double kick_windup_distance; double trunk_height; double trunk_roll; double trunk_pitch; double trunk_yaw; double move_trunk_time = 1; double raise_foot_time = 1; double move_to_ball_time = 1; double kick_time = 1; double move_back_time = 1; double lower_foot_time = 1; double move_trunk_back_time = 1; double stabilizing_point_x; double stabilizing_point_y; double choose_foot_corridor_width; }; /** * An instance of this class describes after which time a KickPhase is done */ class PhaseTimings { public: double move_trunk; double raise_foot; double windup; double kick; double move_back; double lower_foot; double move_trunk_back; }; /** * The KickEngine takes care of choosing an optimal foot to reach a given goal, * planning that foots required movement (rotation and positioning) * and updating short-term MotorGoals to move (the foot) along that planned path. * * It is vital to call the engines tick() method repeatedly because that is where these short-term MotorGoals are * returned. * * The KickEngine utilizes a Stabilizer to balance the robot during foot movments. */ class KickEngine : public bitbots_splines::AbstractEngine<KickGoals, KickPositions> { public: explicit KickEngine(rclcpp::Node::SharedPtr node); /** * Set new goal which the engine tries to kick at. This will remove the old goal completely and plan new splines. * @param header Definition of frame and time in which the goals were published * @param ball_position Position of the ball * @param kick_direction Direction into which to kick the ball * @param kick_speed Speed with which to kick the ball * @param r_foot_pose Current pose of right foot in l_sole frame * @param l_foot_pose Current pose of left foot in r_sole frame * * @throws tf2::TransformException when goal cannot be converted into needed tf frames */ void setGoals(const KickGoals &goals) override; /** * Reset this KickEngine completely, removing the goal, all splines and thereby stopping all output */ void reset() override; /** * Do one iteration of spline-progress-updating. This means that whenever update() is called, * new position goals are retrieved from previously calculated splines, stabilized and transformed into * JointGoals * @param dt Passed delta-time between last call to update() and now. Measured in seconds * @return New motor goals only if a goal is currently set, position extractions from splines was possible and * IK was able to compute valid motor positions */ KickPositions update(double dt) override; /** * Is the currently performed kick with the left foot or not */ bool isLeftKick(); int getPercentDone() const override; /** * Get the current position of the trunk relative to the support foot */ geometry_msgs::msg::Pose getTrunkPose(); bitbots_splines::PoseSpline getFlyingSplines() const; bitbots_splines::PoseSpline getTrunkSplines() const; void setParams(KickParams params); /** * Get the current phase of the engine */ KickPhase getPhase() const; Eigen::Vector3d getWindupPoint(); /** * Set a pointer to the current state of the robot, updated from joint states */ void setRobotState(moveit::core::RobotStatePtr current_state); private: rclcpp::Node::SharedPtr node_; double time_; Eigen::Vector3d ball_position_; Eigen::Quaterniond kick_direction_; double kick_speed_; bool is_left_kick_; bitbots_splines::PoseSpline flying_foot_spline_, trunk_spline_; KickParams params_; PhaseTimings phase_timings_; Eigen::Vector3d windup_point_; moveit::core::RobotStatePtr current_state_; /** * Calculate splines for a complete kick whereby is_left_kick_ should already be set correctly * * @param flying_foot_pose Current pose of the flying foot relative to the support foot * @param trunk_pose Current pose of the trunk relative to the support foot */ void calcSplines(const Eigen::Isometry3d &flying_foot_pose, const Eigen::Isometry3d &trunk_pose); /** * Calculate the point from which to perform the final kicking movement */ Eigen::Vector3d calcKickWindupPoint(); /** * Choose with which foot the kick should be performed * * This is done by checking whether the ball is outside of a corridor ranging from base_footprint forward. * If it is, the foot on that side will be chosen as the kicking foot. * If not, a more fine grained angle based criterion is used. * * * @param ball_position Position where the ball is currently located * @param kick_direction Direction into which the ball should be kicked * @return Whether the resulting kick should be performed with the left foot * * @throws tf2::TransformException when ball_position and kick_direction cannot be converted into base_footprint frame */ bool calcIsLeftFootKicking(const Eigen::Vector3d &ball_position, const Eigen::Quaterniond &kick_direction); /** * Calculate the yaw of the kicking foot, so that it is turned * in the direction of the kick */ double calcKickFootYaw(); /** * Transform then goal into our support_foots frame * @param support_foot_frame Name of the support foots frame, meaning where to transform to * @param trunk_to_base_footprint Pose of the base_footprint relative to the trunk * @param ball_position Position of the ball * @param kick_direction Direction in which to kick the ball * @return pair of (transformed_pose, transformed_direction) * * @throws tf2::TransformException when goal cannot be transformed into support_foot_frame */ std::pair<Eigen::Vector3d, Eigen::Quaterniond> transformGoal(const std::string &support_foot_frame, const Eigen::Isometry3d &trunk_to_base_footprint, const Eigen::Vector3d &ball_position, const Eigen::Quaterniond &kick_direction); }; } // namespace bitbots_dynamic_kick #endif // BITBOTS_DYNAMIC_KICK_INCLUDE_BITBOTS_DYNAMIC_KICK_KICK_ENGINE_H_
411
0.865335
1
0.865335
game-dev
MEDIA
0.76733
game-dev
0.695211
1
0.695211
FLAIROx/JaxMARL
44,606
jaxmarl/environments/storm/storm_2p.py
from enum import IntEnum import math from typing import Any, Optional, Tuple, Union, Dict import chex import jax import jax.numpy as jnp import numpy as onp from flax.struct import dataclass from jaxmarl.environments.multi_agent_env import MultiAgentEnv from jaxmarl.environments import spaces from .rendering import ( downsample, fill_coords, highlight_img, point_in_circle, point_in_rect, point_in_triangle, rotate_fn, ) GRID_SIZE = 8 OBS_SIZE = 5 PADDING = OBS_SIZE - 1 NUM_TYPES = 5 # empty (0), red (1), blue, red coin, blue coin, wall, interact NUM_COINS = 6 # per type NUM_COIN_TYPES = 2 NUM_OBJECTS = ( 2 + NUM_COIN_TYPES * NUM_COINS + 1 ) # red, blue, 2 red coin, 2 blue coin INTERACT_THRESHOLD = 0 @dataclass class State: red_pos: jnp.ndarray blue_pos: jnp.ndarray inner_t: int outer_t: int grid: jnp.ndarray red_inventory: jnp.ndarray blue_inventory: jnp.ndarray red_coins: jnp.ndarray blue_coins: jnp.ndarray freeze: int @chex.dataclass class EnvParams: payoff_matrix: chex.ArrayDevice freeze_penalty: int class Actions(IntEnum): left = 0 right = 1 forward = 2 interact = 3 stay = 4 class Items(IntEnum): empty = 0 red_agent = 1 blue_agent = 2 red_coin = 3 blue_coin = 4 wall = 5 interact = 6 ROTATIONS = jnp.array( [ [0, 0, 1], # turn left [0, 0, -1], # turn right [0, 0, 0], # forward [0, 0, 0], # stay [0, 0, 0], # zap` ], dtype=jnp.int8, ) STEP = jnp.array( [ [0, 1, 0], # up [1, 0, 0], # right [0, -1, 0], # down [-1, 0, 0], # left ], dtype=jnp.int8, ) GRID = jnp.zeros( (GRID_SIZE + 2 * PADDING, GRID_SIZE + 2 * PADDING), dtype=jnp.int8, ) # First layer of Padding is Wall GRID = GRID.at[PADDING - 1, :].set(5) GRID = GRID.at[GRID_SIZE + PADDING, :].set(5) GRID = GRID.at[:, PADDING - 1].set(5) GRID = GRID.at[:, GRID_SIZE + PADDING].set(5) COIN_SPAWNS = [ [1, 1], [1, 2], [2, 1], [1, GRID_SIZE - 2], [2, GRID_SIZE - 2], [1, GRID_SIZE - 3], # [2, 2], # [2, GRID_SIZE - 3], [GRID_SIZE - 2, 2], [GRID_SIZE - 3, 1], [GRID_SIZE - 2, 1], [GRID_SIZE - 2, GRID_SIZE - 2], [GRID_SIZE - 2, GRID_SIZE - 3], [GRID_SIZE - 3, GRID_SIZE - 2], # [GRID_SIZE - 3, 2], # [GRID_SIZE - 3, GRID_SIZE - 3], ] COIN_SPAWNS = jnp.array( COIN_SPAWNS, dtype=jnp.int8, ) RED_SPAWN = jnp.array( COIN_SPAWNS[::2, :], dtype=jnp.int8, ) BLUE_SPAWN = jnp.array( COIN_SPAWNS[1::2, :], dtype=jnp.int8, ) AGENT_SPAWNS = [ [0, 0], [0, 1], [0, 2], [1, 0], # [1, 1], [1, 2], [0, GRID_SIZE - 1], [0, GRID_SIZE - 2], [0, GRID_SIZE - 3], [1, GRID_SIZE - 1], # [1, GRID_SIZE - 2], # [1, GRID_SIZE - 3], [GRID_SIZE - 1, 0], [GRID_SIZE - 1, 1], [GRID_SIZE - 1, 2], [GRID_SIZE - 2, 0], # [GRID_SIZE - 2, 1], # [GRID_SIZE - 2, 2], [GRID_SIZE - 1, GRID_SIZE - 1], [GRID_SIZE - 1, GRID_SIZE - 2], [GRID_SIZE - 1, GRID_SIZE - 3], [GRID_SIZE - 2, GRID_SIZE - 1], # [GRID_SIZE - 2, GRID_SIZE - 2], [GRID_SIZE - 2, GRID_SIZE - 3], ] AGENT_SPAWNS = jnp.array( [ [(j, i), (GRID_SIZE - 1 - j, GRID_SIZE - 1 - i)] for (i, j) in AGENT_SPAWNS ], dtype=jnp.int8, ).reshape(-1, 2, 2) PLAYER1_COLOUR = (255.0, 127.0, 14.0) PLAYER2_COLOUR = (31.0, 119.0, 180.0) GREEN_COLOUR = (44.0, 160.0, 44.0) RED_COLOUR = (214.0, 39.0, 40.0) class InTheGrid_2p(MultiAgentEnv): """ JAX Compatible version of *inTheMatix environment. """ # used for caching tile_cache: Dict[Tuple[Any, ...], Any] = {} def __init__( self, num_inner_steps=152, num_outer_steps=1, fixed_coin_location=True, num_agents=2, payoff_matrix=jnp.array([[[3, 0], [5, 1]], [[3, 5], [0, 1]]]), freeze_penalty=5 ): super().__init__(num_agents=num_agents) self.agents = list(range(num_agents)) def _get_obs_point(x: int, y: int, dir: int) -> jnp.ndarray: x, y = x + PADDING, y + PADDING x = jnp.where(dir == 0, x - (OBS_SIZE // 2), x) x = jnp.where(dir == 2, x - (OBS_SIZE // 2), x) x = jnp.where(dir == 3, x - (OBS_SIZE - 1), x) y = jnp.where(dir == 1, y - (OBS_SIZE // 2), y) y = jnp.where(dir == 2, y - (OBS_SIZE - 1), y) y = jnp.where(dir == 3, y - (OBS_SIZE // 2), y) return x, y def _get_obs(state: State) -> jnp.ndarray: # create state grid = jnp.pad( state.grid, ((PADDING, PADDING), (PADDING, PADDING)), constant_values=Items.wall, ) x, y = _get_obs_point( state.red_pos[0], state.red_pos[1], state.red_pos[2] ) grid1 = jax.lax.dynamic_slice( grid, start_indices=(x, y), slice_sizes=(OBS_SIZE, OBS_SIZE), ) # rotate grid1 = jnp.where( state.red_pos[2] == 1, jnp.rot90(grid1, k=1, axes=(0, 1)), grid1, ) grid1 = jnp.where( state.red_pos[2] == 2, jnp.rot90(grid1, k=2, axes=(0, 1)), grid1, ) grid1 = jnp.where( state.red_pos[2] == 3, jnp.rot90(grid1, k=3, axes=(0, 1)), grid1, ) angle1 = -1 * jnp.ones_like(grid1, dtype=jnp.int8) angle1 = jnp.where( grid1 == Items.blue_agent, (state.blue_pos[2] - state.red_pos[2]) % 4, -1, ) angle1 = jax.nn.one_hot(angle1, 4) # one-hot (drop first channel as its empty blocks) grid1 = jax.nn.one_hot(grid1 - 1, len(Items) - 1, dtype=jnp.int8) obs1 = jnp.concatenate([grid1, angle1], axis=-1) x, y = _get_obs_point( state.blue_pos[0], state.blue_pos[1], state.blue_pos[2] ) grid2 = jax.lax.dynamic_slice( grid, start_indices=(x, y), slice_sizes=(OBS_SIZE, OBS_SIZE), ) grid2 = jnp.where( state.blue_pos[2] == 1, jnp.rot90(grid2, k=1, axes=(0, 1)), grid2, ) grid2 = jnp.where( state.blue_pos[2] == 2, jnp.rot90(grid2, k=2, axes=(0, 1)), grid2, ) grid2 = jnp.where( state.blue_pos[2] == 3, jnp.rot90(grid2, k=3, axes=(0, 1)), grid2, ) angle2 = -1 * jnp.ones_like(grid2, dtype=jnp.int8) angle2 = jnp.where( grid2 == Items.red_agent, (state.red_pos[2] - state.blue_pos[2]) % 4, -1, ) angle2 = jax.nn.one_hot(angle2, 4) # sends 0 -> -1 and droped by one_hot grid2 = jax.nn.one_hot(grid2 - 1, len(Items) - 1, dtype=jnp.int8) # make agent 2 think it is agent 1 _grid2 = grid2.at[:, :, 0].set(grid2[:, :, 1]) _grid2 = _grid2.at[:, :, 1].set(grid2[:, :, 0]) _obs2 = jnp.concatenate([_grid2, angle2], axis=-1) red_pickup = jnp.sum(state.red_inventory) > INTERACT_THRESHOLD blue_pickup = jnp.sum(state.blue_inventory) > INTERACT_THRESHOLD blue_to_show = jnp.where( state.freeze >= 0, state.blue_inventory, 0 ) red_to_show = jnp.where(state.freeze >= 0, state.red_inventory, 0) return { "observation": obs1, "inventory": jnp.array( [ state.red_inventory[0], state.red_inventory[1], red_pickup, blue_pickup, blue_to_show[0], blue_to_show[1], ], dtype=jnp.int8, ), }, { "observation": _obs2, "inventory": jnp.array( [ state.blue_inventory[0], state.blue_inventory[1], blue_pickup, red_pickup, red_to_show[0], red_to_show[1], ], dtype=jnp.int8, ), } def _get_reward(state: State) -> jnp.ndarray: inv1 = state.red_inventory / state.red_inventory.sum() inv2 = state.blue_inventory / state.blue_inventory.sum() r1 = inv1 @ payoff_matrix[0] @ inv2.T r2 = inv1 @ payoff_matrix[1] @ inv2.T return r1, r2 def _interact( state: State, actions: Tuple[int, int] ) -> Tuple[bool, float, float, State]: # if interact a0, a1 = actions red_zap = a0 == Actions.interact blue_zap = a1 == Actions.interact interact_idx = jnp.int8(Items.interact) # remove old interacts state = state.replace(grid=jnp.where( state.grid == interact_idx, jnp.int8(Items.empty), state.grid )) # check 1 ahead red_target = jnp.clip( state.red_pos + STEP[state.red_pos[2]], 0, GRID_SIZE - 1 ) blue_target = jnp.clip( state.blue_pos + STEP[state.blue_pos[2]], 0, GRID_SIZE - 1 ) red_interact = ( state.grid[red_target[0], red_target[1]] == Items.blue_agent ) blue_interact = ( state.grid[blue_target[0], blue_target[1]] == Items.red_agent ) # check 2 ahead red_target_ahead = jnp.clip( state.red_pos + 2 * STEP[state.red_pos[2]], 0, GRID_SIZE - 1 ) blue_target_ahead = jnp.clip( state.blue_pos + 2 * STEP[state.blue_pos[2]], 0, GRID_SIZE - 1 ) red_interact_ahead = ( state.grid[red_target_ahead[0], red_target_ahead[1]] == Items.blue_agent ) blue_interact_ahead = ( state.grid[blue_target_ahead[0], blue_target_ahead[1]] == Items.red_agent ) # check to your right - clip can't be used here as it will wrap down red_target_right = ( state.red_pos + STEP[state.red_pos[2]] + STEP[(state.red_pos[2] + 1) % 4] ) oob_red = jnp.logical_or( (red_target_right > GRID_SIZE - 1).any(), (red_target_right < 0).any(), ) red_target_right = jnp.where(oob_red, red_target, red_target_right) blue_target_right = ( state.blue_pos + STEP[state.blue_pos[2]] + STEP[(state.blue_pos[2] + 1) % 4] ) oob_blue = jnp.logical_or( (blue_target_right > GRID_SIZE - 1).any(), (blue_target_right < 0).any(), ) blue_target_right = jnp.where( oob_blue, blue_target, blue_target_right ) red_interact_right = ( state.grid[red_target_right[0], red_target_right[1]] == Items.blue_agent ) blue_interact_right = ( state.grid[blue_target_right[0], blue_target_right[1]] == Items.red_agent ) # check to your left red_target_left = ( state.red_pos + STEP[state.red_pos[2]] + STEP[(state.red_pos[2] - 1) % 4] ) oob_red = jnp.logical_or( (red_target_left > GRID_SIZE - 1).any(), (red_target_left < 0).any(), ) red_target_left = jnp.where(oob_red, red_target, red_target_left) blue_target_left = ( state.blue_pos + STEP[state.blue_pos[2]] + STEP[(state.blue_pos[2] - 1) % 4] ) oob_blue = jnp.logical_or( (blue_target_left > GRID_SIZE - 1).any(), (blue_target_left < 0).any(), ) blue_target_left = jnp.where( oob_blue, blue_target, blue_target_left ) red_interact_left = ( state.grid[red_target_left[0], red_target_left[1]] == Items.blue_agent ) blue_interact_left = ( state.grid[blue_target_left[0], blue_target_left[1]] == Items.red_agent ) red_interact = jnp.logical_or( red_interact, jnp.logical_or( red_interact_ahead, jnp.logical_or(red_interact_right, red_interact_left), ), ) # update grid with red zaps aux_grid = jnp.copy(state.grid) item = jnp.where( state.grid[red_target[0], red_target[1]], state.grid[red_target[0], red_target[1]], interact_idx, ) aux_grid = aux_grid.at[red_target[0], red_target[1]].set(item) item = jnp.where( state.grid[red_target_ahead[0], red_target_ahead[1]], state.grid[red_target_ahead[0], red_target_ahead[1]], interact_idx, ) aux_grid = aux_grid.at[ red_target_ahead[0], red_target_ahead[1] ].set(item) item = jnp.where( state.grid[red_target_right[0], red_target_right[1]], state.grid[red_target_right[0], red_target_right[1]], interact_idx, ) aux_grid = aux_grid.at[ red_target_right[0], red_target_right[1] ].set(item) item = jnp.where( state.grid[red_target_left[0], red_target_left[1]], state.grid[red_target_left[0], red_target_left[1]], interact_idx, ) aux_grid = aux_grid.at[red_target_left[0], red_target_left[1]].set( item ) state = state.replace(grid=jnp.where(red_zap, aux_grid, state.grid)) # update grid with blue zaps aux_grid = jnp.copy(state.grid) blue_interact = jnp.logical_or( blue_interact, jnp.logical_or( blue_interact_ahead, jnp.logical_or(blue_interact_right, blue_interact_left), ), ) item = jnp.where( state.grid[blue_target[0], blue_target[1]], state.grid[blue_target[0], blue_target[1]], interact_idx, ) aux_grid = aux_grid.at[blue_target[0], blue_target[1]].set(item) item = jnp.where( state.grid[blue_target_ahead[0], blue_target_ahead[1]], state.grid[blue_target_ahead[0], blue_target_ahead[1]], interact_idx, ) aux_grid = aux_grid.at[ blue_target_ahead[0], blue_target_ahead[1] ].set(item) item = jnp.where( state.grid[blue_target_right[0], blue_target_right[1]], state.grid[blue_target_right[0], blue_target_right[1]], interact_idx, ) aux_grid = aux_grid.at[ blue_target_right[0], blue_target_right[1] ].set(item) item = jnp.where( state.grid[blue_target_left[0], blue_target_left[1]], state.grid[blue_target_left[0], blue_target_left[1]], interact_idx, ) aux_grid = aux_grid.at[ blue_target_left[0], blue_target_left[1] ].set(item) state = state.replace(grid=jnp.where(blue_zap, aux_grid, state.grid)) # rewards red_reward, blue_reward = 0.0, 0.0 _r_reward, _b_reward = _get_reward(state) interact = jnp.logical_or( red_zap * red_interact, blue_zap * blue_interact ) red_pickup = state.red_inventory.sum() > INTERACT_THRESHOLD blue_pickup = state.blue_inventory.sum() > INTERACT_THRESHOLD interact = jnp.logical_and( interact, jnp.logical_and(red_pickup, blue_pickup) ) red_reward = jnp.where( interact, red_reward + _r_reward, red_reward ) blue_reward = jnp.where( interact, blue_reward + _b_reward, blue_reward ) return interact, red_reward, blue_reward, state def _step( key: chex.PRNGKey, state: State, actions: Tuple[int, int] ): """Step the environment.""" # freeze check action_0, action_1 = actions action_0 = jnp.where(state.freeze > 0, Actions.stay, action_0) action_1 = jnp.where(state.freeze > 0, Actions.stay, action_1) # turning red new_red_pos = jnp.int8( (state.red_pos + ROTATIONS[action_0]) % jnp.array([GRID_SIZE + 1, GRID_SIZE + 1, 4]) ) # moving red red_move = action_0 == Actions.forward new_red_pos = jnp.where( red_move, new_red_pos + STEP[state.red_pos[2]], new_red_pos ) new_red_pos = jnp.clip( new_red_pos, a_min=jnp.array([0, 0, 0], dtype=jnp.int8), a_max=jnp.array( [GRID_SIZE - 1, GRID_SIZE - 1, 3], dtype=jnp.int8 ), ) # if you bounced back to ur original space, we change your move to stay (for collision logic) red_move = (new_red_pos[:2] != state.red_pos[:2]).any() # turning blue new_blue_pos = jnp.int8( (state.blue_pos + ROTATIONS[action_1]) % jnp.array([GRID_SIZE + 1, GRID_SIZE + 1, 4], dtype=jnp.int8) ) # moving blue blue_move = action_1 == Actions.forward new_blue_pos = jnp.where( blue_move, new_blue_pos + STEP[state.blue_pos[2]], new_blue_pos ) new_blue_pos = jnp.clip( new_blue_pos, a_min=jnp.array([0, 0, 0], dtype=jnp.int8), a_max=jnp.array( [GRID_SIZE - 1, GRID_SIZE - 1, 3], dtype=jnp.int8 ), ) blue_move = (new_blue_pos[:2] != state.blue_pos[:2]).any() # if collision, priority to whoever didn't move collision = jnp.all(new_red_pos[:2] == new_blue_pos[:2]) new_red_pos = jnp.where( collision * red_move * (1 - blue_move), # red moved, blue didn't state.red_pos, new_red_pos, ) new_blue_pos = jnp.where( collision * (1 - red_move) * blue_move, # blue moved, red didn't state.blue_pos, new_blue_pos, ) # if both moved, then randomise red_takes_square = jax.random.choice(key, jnp.array([0, 1])) new_red_pos = jnp.where( collision * blue_move * red_move * ( 1 - red_takes_square ), # if both collide and red doesn't take square state.red_pos, new_red_pos, ) new_blue_pos = jnp.where( collision * blue_move * red_move * ( red_takes_square ), # if both collide and blue doesn't take square state.blue_pos, new_blue_pos, ) # update inventories red_red_matches = ( state.grid[new_red_pos[0], new_red_pos[1]] == Items.red_coin ) red_blue_matches = ( state.grid[new_red_pos[0], new_red_pos[1]] == Items.blue_coin ) blue_red_matches = ( state.grid[new_blue_pos[0], new_blue_pos[1]] == Items.red_coin ) blue_blue_matches = ( state.grid[new_blue_pos[0], new_blue_pos[1]] == Items.blue_coin ) state = state.replace(red_inventory=state.red_inventory + jnp.array( [red_red_matches, red_blue_matches] )) state = state.replace(blue_inventory=state.blue_inventory + jnp.array( [blue_red_matches, blue_blue_matches] )) # update grid state = state.replace(grid=state.grid.at[ (state.red_pos[0], state.red_pos[1]) ].set(jnp.int8(Items.empty))) state = state.replace(grid=state.grid.at[ (state.blue_pos[0], state.blue_pos[1]) ].set(jnp.int8(Items.empty))) state = state.replace(grid=state.grid.at[(new_red_pos[0], new_red_pos[1])].set( jnp.int8(Items.red_agent) )) state = state.replace(grid=state.grid.at[(new_blue_pos[0], new_blue_pos[1])].set( jnp.int8(Items.blue_agent) )) state = state.replace(red_pos=new_red_pos) state = state.replace(blue_pos=new_blue_pos) red_reward, blue_reward = 0, 0 ( interact, red_interact_reward, blue_interact_reward, state, ) = _interact(state, (action_0, action_1)) red_reward += red_interact_reward blue_reward += blue_interact_reward # if we interacted, then we set freeze state = state.replace(freeze=jnp.where( interact, freeze_penalty, state.freeze )) # if we didn't interact, then we decrement freeze state = state.replace(freeze=jnp.where( state.freeze > 0, state.freeze - 1, state.freeze )) state_sft_re = _soft_reset_state(key, state) state = jax.tree.map( lambda x, y: jnp.where(state.freeze == 0, x, y), state_sft_re, state, ) state_nxt = State( red_pos=state.red_pos, blue_pos=state.blue_pos, inner_t=state.inner_t + 1, outer_t=state.outer_t, grid=state.grid, red_inventory=state.red_inventory, blue_inventory=state.blue_inventory, red_coins=state.red_coins, blue_coins=state.blue_coins, freeze=jnp.where( interact, freeze_penalty, state.freeze ), ) # now calculate if done for inner or outer episode inner_t = state_nxt.inner_t outer_t = state_nxt.outer_t reset_inner = inner_t == num_inner_steps # if inner episode is done, return start state for next game state_re = _reset_state(key) state_re = state_re.replace(outer_t=outer_t + 1) state = jax.tree.map( lambda x, y: jax.lax.select(reset_inner, x, y), state_re, state_nxt, ) outer_t = state.outer_t reset_outer = outer_t == num_outer_steps done = {} done["__all__"] = reset_outer obs = _get_obs(state) blue_reward = jnp.where(reset_inner, 0, blue_reward) red_reward = jnp.where(reset_inner, 0, red_reward) return ( obs, state, (red_reward, blue_reward), done, {"discount": jnp.zeros((), dtype=jnp.int8)}, ) def _soft_reset_state(key: jnp.ndarray, state: State) -> State: """Reset the grid to original state and""" # Find the free spaces in the grid grid = jnp.zeros((GRID_SIZE, GRID_SIZE), jnp.int8) # if coin location can change, then we need to reset the coins for i in range(NUM_COINS): grid = grid.at[ state.red_coins[i, 0], state.red_coins[i, 1] ].set(jnp.int8(Items.red_coin)) for i in range(NUM_COINS): grid = grid.at[ state.blue_coins[i, 0], state.blue_coins[i, 1] ].set(jnp.int8(Items.blue_coin)) agent_pos = jax.random.choice( key, AGENT_SPAWNS, shape=(), replace=False ) player_dir = jax.random.randint( key, shape=(2,), minval=0, maxval=3, dtype=jnp.int8 ) player_pos = jnp.array( [agent_pos[:2, 0], agent_pos[:2, 1], player_dir] ).T red_pos = player_pos[0, :] blue_pos = player_pos[1, :] grid = grid.at[red_pos[0], red_pos[1]].set( jnp.int8(Items.red_agent) ) grid = grid.at[blue_pos[0], blue_pos[1]].set( jnp.int8(Items.blue_agent) ) return State( red_pos=red_pos, blue_pos=blue_pos, inner_t=state.inner_t, outer_t=state.outer_t, grid=grid, red_inventory=jnp.zeros(2), blue_inventory=jnp.zeros(2), red_coins=state.red_coins, blue_coins=state.blue_coins, freeze=jnp.int16(-1), ) def _reset_state( key: jnp.ndarray ) -> Tuple[jnp.ndarray, State]: key, subkey = jax.random.split(key) # coin_pos = jax.random.choice( # subkey, COIN_SPAWNS, shape=(NUM_COIN_TYPES*NUM_COINS,), replace=False # ) agent_pos = jax.random.choice( subkey, AGENT_SPAWNS, shape=(), replace=False ) player_dir = jax.random.randint( subkey, shape=(2,), minval=0, maxval=3, dtype=jnp.int8 ) player_pos = jnp.array( [agent_pos[:2, 0], agent_pos[:2, 1], player_dir] ).T grid = jnp.zeros((GRID_SIZE, GRID_SIZE), jnp.int8) grid = grid.at[player_pos[0, 0], player_pos[0, 1]].set( jnp.int8(Items.red_agent) ) grid = grid.at[player_pos[1, 0], player_pos[1, 1]].set( jnp.int8(Items.blue_agent) ) if fixed_coin_location: rand_idx = jax.random.randint( subkey, shape=(), minval=0, maxval=1 ) red_coins = jnp.where(rand_idx, RED_SPAWN, BLUE_SPAWN) blue_coins = jnp.where(rand_idx, BLUE_SPAWN, RED_SPAWN) else: coin_spawn = jax.random.permutation( subkey, COIN_SPAWNS, axis=0 ) red_coins = coin_spawn[:NUM_COINS, :] blue_coins = coin_spawn[NUM_COINS:, :] for i in range(NUM_COINS): grid = grid.at[red_coins[i, 0], red_coins[i, 1]].set( jnp.int8(Items.red_coin) ) for i in range(NUM_COINS): grid = grid.at[blue_coins[i, 0], blue_coins[i, 1]].set( jnp.int8(Items.blue_coin) ) return State( red_pos=player_pos[0, :], blue_pos=player_pos[1, :], inner_t=0, outer_t=0, grid=grid, red_inventory=jnp.zeros(2), blue_inventory=jnp.zeros(2), red_coins=red_coins, blue_coins=blue_coins, freeze=jnp.int16(-1), ) def reset( key: jnp.ndarray ) -> Tuple[jnp.ndarray, State]: state = _reset_state(key) obs = _get_obs(state) return obs, state # overwrite Gymnax as it makes single-agent assumptions # self.step = jax.jit(_step) self.step_env = _step self.reset = jax.jit(reset) self.get_obs_point = _get_obs_point self.get_reward = _get_reward # for debugging self.get_obs = _get_obs self.cnn = True self.num_inner_steps = num_inner_steps self.num_outer_steps = num_outer_steps _shape = ( (OBS_SIZE, OBS_SIZE, len(Items) - 1 + 4) if self.cnn else (OBS_SIZE**2 * (len(Items) - 1 + 4),) ) self.observation_spaces = { a: { "observation": spaces.Box( low=0, high=1, shape=_shape, dtype=jnp.uint8 ), "inventory": spaces.Box( low=0, high=NUM_COINS, shape=NUM_COIN_TYPES + 4, dtype=jnp.uint8, ), } for a in self.agents } self.action_spaces = { a: spaces.Discrete(len(Actions)) for a in self.agents } @property def name(self) -> str: """Environment name.""" return "2PMGinTheGrid" @property def num_actions(self) -> int: """Number of actions possible in environment.""" return len(Actions) def action_space(self, agent: str) -> spaces.Discrete: """Action space of the environment.""" return self.action_spaces[agent] def observation_space(self, agent:str) -> spaces.Dict: """Observation space of the environment.""" return self.observation_spaces[agent] def state_space(self) -> spaces.Dict: """State space of the environment.""" _shape = ( (GRID_SIZE, GRID_SIZE, NUM_TYPES + 4) if self.cnn else (GRID_SIZE**2 * (NUM_TYPES + 4),) ) return spaces.Box(low=0, high=1, shape=_shape, dtype=jnp.uint8) @classmethod def render_tile( cls, obj: int, agent_dir: Union[int, None] = None, agent_hat: bool = False, highlight: bool = False, tile_size: int = 32, subdivs: int = 3, ) -> onp.ndarray: """ Render a tile and cache the result """ # Hash map lookup key for the cache key: tuple[Any, ...] = (agent_dir, agent_hat, highlight, tile_size) if obj: key = (obj, 0, 0, 0) + key if obj else key if key in cls.tile_cache: return cls.tile_cache[key] img = onp.zeros( shape=(tile_size * subdivs, tile_size * subdivs, 3), dtype=onp.uint8, ) # Draw the grid lines (top and left edges) fill_coords(img, point_in_rect(0, 0.031, 0, 1), (100, 100, 100)) fill_coords(img, point_in_rect(0, 1, 0, 0.031), (100, 100, 100)) if obj == Items.red_agent: # Draw the agent 1 agent_color = PLAYER1_COLOUR elif obj == Items.blue_agent: # Draw agent 2 agent_color = PLAYER2_COLOUR elif obj == Items.red_coin: # Draw the red coin as GREEN COOPERATE fill_coords( img, point_in_circle(0.5, 0.5, 0.31), (44.0, 160.0, 44.0) ) elif obj == Items.blue_coin: # Draw the blue coin as DEFECT/ RED COIN fill_coords( img, point_in_circle(0.5, 0.5, 0.31), (214.0, 39.0, 40.0) ) elif obj == Items.wall: fill_coords(img, point_in_rect(0, 1, 0, 1), (127.0, 127.0, 127.0)) elif obj == Items.interact: fill_coords(img, point_in_rect(0, 1, 0, 1), (188.0, 189.0, 34.0)) elif obj == 99: fill_coords(img, point_in_rect(0, 1, 0, 1), (44.0, 160.0, 44.0)) elif obj == 100: fill_coords(img, point_in_rect(0, 1, 0, 1), (214.0, 39.0, 40.0)) elif obj == 101: # white square fill_coords(img, point_in_rect(0, 1, 0, 1), (255.0, 255.0, 255.0)) # Overlay the agent on top if agent_dir is not None: if agent_hat: tri_fn = point_in_triangle( (0.12, 0.19), (0.87, 0.50), (0.12, 0.81), 0.3, ) # Rotate the agent based on its direction tri_fn = rotate_fn( tri_fn, cx=0.5, cy=0.5, theta=0.5 * math.pi * (1 - agent_dir), ) fill_coords(img, tri_fn, (255.0, 255.0, 255.0)) tri_fn = point_in_triangle( (0.12, 0.19), (0.87, 0.50), (0.12, 0.81), 0.0, ) # Rotate the agent based on its direction tri_fn = rotate_fn( tri_fn, cx=0.5, cy=0.5, theta=0.5 * math.pi * (1 - agent_dir) ) fill_coords(img, tri_fn, agent_color) # Highlight the cell if needed if highlight: highlight_img(img) # Downsample the image to perform supersampling/anti-aliasing img = downsample(img, subdivs) # Cache the rendered tile cls.tile_cache[key] = img return img def render_agent_view( self, state: State, agent: int ) -> Tuple[onp.ndarray]: """ Render the observation for each agent""" tile_size = 32 obs = self.get_obs(state) grid = onp.array(obs[agent]["observation"][:, :, :-4]) empty_space_channel = onp.zeros((OBS_SIZE, OBS_SIZE, 1)) grid = onp.concatenate((empty_space_channel, grid), axis=-1) grid = onp.argmax(grid.reshape(-1, grid.shape[-1]), axis=1) grid = grid.reshape(OBS_SIZE, OBS_SIZE) angles = onp.array(obs[agent]["observation"][:, :, -4:]) angles = onp.argmax(angles.reshape(-1, angles.shape[-1]), axis=1) angles = angles.reshape(OBS_SIZE, OBS_SIZE) # Compute the total grid size width_px = grid.shape[0] * tile_size height_px = grid.shape[0] * tile_size img = onp.zeros(shape=(height_px, width_px, 3), dtype=onp.uint8) # agent direction pricipal_dir = 0 red_hat = bool(state.red_inventory.sum() > INTERACT_THRESHOLD) blue_hat = bool(state.blue_inventory.sum() > INTERACT_THRESHOLD) if agent == 0: principal_hat = red_hat other_hat = blue_hat else: principal_hat = blue_hat other_hat = red_hat # Render the grid for j in range(0, grid.shape[1]): for i in range(0, grid.shape[0]): cell = grid[i, j] if cell == 0: cell = None principal_agent_here = cell == 1 other_agent_here = cell == 2 if principal_agent_here: agent_dir = pricipal_dir agent_hat = principal_hat elif other_agent_here: agent_dir = angles[i, j] agent_hat = other_hat else: agent_dir = None agent_hat = None tile_img = InTheGrid_2p.render_tile( cell, agent_dir=agent_dir, agent_hat=agent_hat, highlight=None, tile_size=tile_size, ) ymin = j * tile_size ymax = (j + 1) * tile_size xmin = i * tile_size xmax = (i + 1) * tile_size img[ymin:ymax, xmin:xmax, :] = tile_img img = onp.rot90(img, 2, axes=(0, 1)) inv = self.render_inventory( state.red_inventory if agent == 0 else state.blue_inventory, width_px, ) return onp.concatenate((img, inv), axis=0) def render( self, state: State ) -> onp.ndarray: """ Render this grid at a given scale :param r: target renderer object :param tile_size: tile size in pixels """ tile_size = 32 highlight_mask = onp.zeros_like(onp.array(GRID)) # Compute the total grid size width_px = GRID.shape[0] * tile_size height_px = GRID.shape[0] * tile_size img = onp.zeros(shape=(height_px, width_px, 3), dtype=onp.uint8) grid = onp.array(state.grid) grid = onp.pad( grid, ((PADDING, PADDING), (PADDING, PADDING)), constant_values=5 ) startx, starty = self.get_obs_point( state.red_pos[0], state.red_pos[1], state.red_pos[2] ) highlight_mask[ startx : startx + OBS_SIZE, starty : starty + OBS_SIZE ] = True startx, starty = self.get_obs_point( state.blue_pos[0], state.blue_pos[1], state.blue_pos[2] ) highlight_mask[ startx : startx + OBS_SIZE, starty : starty + OBS_SIZE ] = True if state.freeze > 0: # check which agent won r1, r2 = self.get_reward(state) if r1 == -r2: # zero sum game if r1 > r2: # red won img = onp.tile( PLAYER1_COLOUR, (img.shape[0], img.shape[1], 1) ) elif r2 > r1: # blue won img = onp.tile( PLAYER2_COLOUR, (img.shape[0], img.shape[1], 1) ) elif r1 == r2: img[:, : width_px // 2, :] = onp.tile( PLAYER2_COLOUR, (img.shape[0], img.shape[1] // 2, 1) ) img[:, width_px // 2 :, :] = onp.tile( PLAYER1_COLOUR, (img.shape[0], img.shape[1] // 2, 1) ) else: # otherwise we got some cool general sum game welfare = r1 + r2 if welfare > 5: # cooperate img[:, width_px // 2 :, :] = onp.tile( GREEN_COLOUR, (img.shape[0], img.shape[1] // 2, 1) ) else: img[:, width_px // 2 :, :] = onp.tile( RED_COLOUR, (img.shape[0], img.shape[1] // 2, 1) ) if r1 > r2: # red won img[:, : width_px // 2, :] = onp.tile( PLAYER1_COLOUR, (img.shape[0], img.shape[1] // 2, 1) ) elif r1 < r2: # blue won img[:, : width_px // 2, :] = onp.tile( PLAYER2_COLOUR, (img.shape[0], img.shape[1] // 2, 1) ) elif r1 == r2: img[height_px // 2 :, : width_px // 2, :] = onp.tile( PLAYER1_COLOUR, (img.shape[0] // 2, img.shape[1] // 2, 1), ) img[: height_px // 2, : width_px // 2, :] = onp.tile( PLAYER2_COLOUR, (img.shape[0] // 2, img.shape[1] // 2, 1), ) img = img.astype(onp.uint8) else: # Render the grid for j in range(0, grid.shape[1]): for i in range(0, grid.shape[0]): cell = grid[i, j] if cell == 0: cell = None red_agent_here = cell == 1 blue_agent_here = cell == 2 agent_dir = None agent_dir = ( state.red_pos[2].item() if red_agent_here else agent_dir ) agent_dir = ( state.blue_pos[2].item() if blue_agent_here else agent_dir ) agent_hat = False agent_hat = ( bool(state.red_inventory.sum() > INTERACT_THRESHOLD) if red_agent_here else agent_hat ) agent_hat = ( bool(state.blue_inventory.sum() > INTERACT_THRESHOLD) if blue_agent_here else agent_hat ) tile_img = InTheGrid_2p.render_tile( cell, agent_dir=agent_dir, agent_hat=agent_hat, highlight=highlight_mask[i, j], tile_size=tile_size, ) ymin = j * tile_size ymax = (j + 1) * tile_size xmin = i * tile_size xmax = (i + 1) * tile_size img[ymin:ymax, xmin:xmax, :] = tile_img img = onp.rot90( img[ (PADDING - 1) * tile_size : -(PADDING - 1) * tile_size, (PADDING - 1) * tile_size : -(PADDING - 1) * tile_size, :, ], 2, ) # Render the inventory red_inv = self.render_inventory(state.red_inventory, img.shape[1]) blue_inv = self.render_inventory(state.blue_inventory, img.shape[1]) time = self.render_time(state, img.shape[1]) img = onp.concatenate((img, red_inv, blue_inv, time), axis=0) return img def render_inventory(self, inventory, width_px) -> onp.array: tile_height = 32 height_px = NUM_COIN_TYPES * tile_height img = onp.zeros(shape=(height_px, width_px, 3), dtype=onp.uint8) tile_width = width_px // NUM_COINS for j in range(0, NUM_COIN_TYPES): num_coins = inventory[j] for i in range(int(num_coins)): cell = None if j == 0: cell = 99 elif j == 1: cell = 100 tile_img = InTheGrid_2p.render_tile(cell, tile_size=tile_height) ymin = j * tile_height ymax = (j + 1) * tile_height xmin = i * tile_width xmax = (i + 1) * tile_width img[ymin:ymax, xmin:xmax, :] = onp.resize( tile_img, (tile_height, tile_width, 3) ) return img def render_time(self, state, width_px) -> onp.array: inner_t = state.inner_t outer_t = state.outer_t tile_height = 32 img = onp.zeros(shape=(2 * tile_height, width_px, 3), dtype=onp.uint8) tile_width = width_px // (self.num_inner_steps) j = 0 for i in range(0, inner_t): ymin = j * tile_height ymax = (j + 1) * tile_height xmin = i * tile_width xmax = (i + 1) * tile_width img[ymin:ymax, xmin:xmax, :] = onp.int8(255) tile_width = width_px // (self.num_outer_steps) j = 1 for i in range(0, outer_t): ymin = j * tile_height ymax = (j + 1) * tile_height xmin = i * tile_width xmax = (i + 1) * tile_width img[ymin:ymax, xmin:xmax, :] = onp.int8(255) return img
411
0.887411
1
0.887411
game-dev
MEDIA
0.333594
game-dev
0.968742
1
0.968742
KindoSaur/Pseudo3D
1,039
NEW Pseudo 3D without DEBUG/Scripts/World Elements/Racers/Player.gd
#Player.gd extends Racer func Setup(mapSize : int): SetMapSize(mapSize) func Update(mapForward : Vector3): if(_isPushedBack): ApplyCollisionBump() var nextPos : Vector3 = _mapPosition + ReturnVelocity() var nextPixelPos : Vector2i = Vector2i(ceil(nextPos.x), ceil(nextPos.z)) if(_collisionHandler.IsCollidingWithWall(Vector2i(ceil(nextPos.x), ceil(_mapPosition.z)))): nextPos.x = _mapPosition.x SetCollisionBump(Vector3(-sign(ReturnVelocity().x), 0, 0)) if(_collisionHandler.IsCollidingWithWall(Vector2i(ceil(_mapPosition.x), ceil(nextPos.z)))): nextPos.z = _mapPosition.z SetCollisionBump(Vector3(0, 0, -sign(ReturnVelocity().z))) HandleRoadType(nextPixelPos, _collisionHandler.ReturnCurrentRoadType(nextPixelPos)) SetMapPosition(nextPos) UpdateMovementSpeed() UpdateVelocity(mapForward) func ReturnPlayerInput() -> Vector2: _inputDir.x = Input.get_action_strength("Left") - Input.get_action_strength("Right") _inputDir.y = -Input.get_action_strength("Forward") return Vector2(_inputDir.x, _inputDir.y)
411
0.824396
1
0.824396
game-dev
MEDIA
0.839159
game-dev
0.963932
1
0.963932
DarkRTA/rb3
9,481
doc/rb2_dump/rockband2/system/src/net/SessionMessages.cpp
/* Compile unit: C:\rockband2\system\src\net\SessionMessages.cpp Producer: MW EABI PPC C-Compiler Language: C++ Code range: 0x805393D8 -> 0x8053AADC */ // Range: 0x805393D8 -> 0x805393EC void SessionMsg::Dispatch() { // References // -> class Net TheNet; } // Range: 0x805393EC -> 0x80539474 int JoinRequestMsg::GetPlayerID(const class JoinRequestMsg * const this /* r30 */, int index /* r31 */) { // References // -> class Debug TheDebug; // -> const char * kAssertStr; } // Range: 0x80539474 -> 0x8053948C void JoinRequestMsg::GetAuthenticationData(const class JoinRequestMsg * const this /* r5 */) {} // Range: 0x8053948C -> 0x805395B4 void JoinRequestMsg::Save(const class JoinRequestMsg * const this /* r30 */, class BinStream & dest /* r31 */) { // Local variables unsigned char numPlayers; // r29 int n; // r28 } // Range: 0x805395B4 -> 0x80539934 void JoinRequestMsg::Load(class JoinRequestMsg * const this /* r28 */, class BinStream & src /* r29 */) { // Local variables unsigned char numPlayers; // r1+0x39 int n; // r30 unsigned char playerID; // r1+0x38 int playerDataSize; // r1+0x44 class MemStream playerBuffer; // r1+0x48 int authDataSize; // r1+0x40 // References // -> const char * gStlAllocName; // -> struct [anonymous] __RTTI__Pc; // -> unsigned char gStlAllocNameLookup; // -> struct [anonymous] __vt__9MemStream; // -> struct [anonymous] __vt__9BinStream; } // Range: 0x80539934 -> 0x80539968 void * JoinResponseMsg::JoinResponseMsg() { // References // -> struct [anonymous] __vt__15JoinResponseMsg; } // Range: 0x80539968 -> 0x80539978 unsigned char JoinResponseMsg::Joined() {} // Range: 0x80539978 -> 0x80539A48 void JoinResponseMsg::SetNewPlayerID(class JoinResponseMsg * const this /* r31 */, int oldID /* r1+0x8 */, int newID /* r1+0xC */) {} // Range: 0x80539A48 -> 0x80539A98 void JoinResponseMsg::SwapOldIDs() { // Local variables int n; // r8 } // Range: 0x80539A98 -> 0x80539B74 void JoinResponseMsg::Save(const class JoinResponseMsg * const this /* r27 */, class BinStream & dest /* r28 */) { // Local variables int numIDs; // r30 int n; // r29 } // Range: 0x80539B74 -> 0x80539CC0 void JoinResponseMsg::Load(class JoinResponseMsg * const this /* r29 */, class BinStream & src /* r30 */) { // Local variables int error; // r1+0x1C int numIDs; // r1+0x18 int n; // r31 int oldID; // r1+0x14 int newID; // r1+0x10 } // Range: 0x80539CC0 -> 0x80539D34 void * NewPlayerMsg::NewPlayerMsg(class NewPlayerMsg * const this /* r30 */, const class User * newPlayer /* r31 */) { // References // -> struct [anonymous] __vt__12NewPlayerMsg; } // Range: 0x80539D34 -> 0x80539D4C void NewPlayerMsg::GetUser(const class NewPlayerMsg * const this /* r5 */) {} // Range: 0x80539D4C -> 0x80539DC4 void NewPlayerMsg::Save(const class NewPlayerMsg * const this /* r30 */, class BinStream & dest /* r31 */) {} // Range: 0x80539DC4 -> 0x80539E94 void NewPlayerMsg::Load(class NewPlayerMsg * const this /* r29 */, class BinStream & src /* r30 */) { // Local variables int numBytes; // r1+0x10 } // Range: 0x80539E94 -> 0x80539EA8 void * PlayerLeftMsg::PlayerLeftMsg() { // References // -> struct [anonymous] __vt__13PlayerLeftMsg; } // Range: 0x80539EA8 -> 0x80539EE0 void PlayerLeftMsg::Save(const class PlayerLeftMsg * const this /* r5 */) {} // Range: 0x80539EE0 -> 0x80539EF4 void PlayerLeftMsg::Load(class PlayerLeftMsg * const this /* r5 */) {} // Range: 0x80539EF4 -> 0x80539F98 void * AddPlayerRequestMsg::AddPlayerRequestMsg(class AddPlayerRequestMsg * const this /* r30 */, const class User * newPlayer /* r31 */) { // References // -> class Net TheNet; // -> struct [anonymous] __vt__19AddPlayerRequestMsg; } // Range: 0x80539F98 -> 0x80539FB0 void AddPlayerRequestMsg::GetUser(const class AddPlayerRequestMsg * const this /* r5 */) {} // Range: 0x80539FB0 -> 0x80539FC8 void AddPlayerRequestMsg::GetAuthenticationData(const class AddPlayerRequestMsg * const this /* r5 */) {} // Range: 0x80539FC8 -> 0x8053A06C void AddPlayerRequestMsg::Save(const class AddPlayerRequestMsg * const this /* r30 */, class BinStream & dest /* r31 */) {} // Range: 0x8053A06C -> 0x8053A1C0 void AddPlayerRequestMsg::Load(class AddPlayerRequestMsg * const this /* r29 */, class BinStream & src /* r30 */) { // Local variables int numBytes; // r1+0x18 } // Range: 0x8053A1C0 -> 0x8053A248 void AddPlayerResponseMsg::Save(const class AddPlayerResponseMsg * const this /* r30 */, class BinStream & dest /* r31 */) {} // Range: 0x8053A248 -> 0x8053A2C4 void AddPlayerResponseMsg::Load(class AddPlayerResponseMsg * const this /* r30 */, class BinStream & src /* r31 */) {} // Range: 0x8053A2C4 -> 0x8053A348 void * ChangePlayerMsg::ChangePlayerMsg(class ChangePlayerMsg * const this /* r29 */, const class User * playerData /* r30 */, unsigned int dirtyMask /* r31 */) { // References // -> struct [anonymous] __vt__15ChangePlayerMsg; } // Range: 0x8053A348 -> 0x8053A360 void ChangePlayerMsg::GetUser(const class ChangePlayerMsg * const this /* r5 */) {} // Range: 0x8053A360 -> 0x8053A3F0 void ChangePlayerMsg::Save(const class ChangePlayerMsg * const this /* r30 */, class BinStream & dest /* r31 */) {} // Range: 0x8053A3F0 -> 0x8053A4D0 void ChangePlayerMsg::Load(class ChangePlayerMsg * const this /* r29 */, class BinStream & src /* r30 */) { // Local variables int numBytes; // r1+0x10 } // Range: 0x8053A4D0 -> 0x8053A4E4 void * FinishedLoadingMsg::FinishedLoadingMsg() { // References // -> struct [anonymous] __vt__18FinishedLoadingMsg; } // Range: 0x8053A4E4 -> 0x8053A51C void FinishedLoadingMsg::Save(const class FinishedLoadingMsg * const this /* r5 */) {} // Range: 0x8053A51C -> 0x8053A530 void FinishedLoadingMsg::Load(class FinishedLoadingMsg * const this /* r5 */) {} // Range: 0x8053A530 -> 0x8053A548 void * StartGameOnTimeMsg::StartGameOnTimeMsg() { // References // -> struct [anonymous] __vt__18StartGameOnTimeMsg; } // Range: 0x8053A548 -> 0x8053A588 void StartGameOnTimeMsg::Save(const class StartGameOnTimeMsg * const this /* r5 */) {} // Range: 0x8053A588 -> 0x8053A59C void StartGameOnTimeMsg::Load(class StartGameOnTimeMsg * const this /* r5 */) {} // Range: 0x8053A59C -> 0x8053A5B4 void * EndGameMsg::EndGameMsg() { // References // -> struct [anonymous] __vt__10EndGameMsg; } // Range: 0x8053A5B4 -> 0x8053A618 void EndGameMsg::Save(const class EndGameMsg * const this /* r30 */, class BinStream & dest /* r31 */) {} // Range: 0x8053A618 -> 0x8053A680 void EndGameMsg::Load(class EndGameMsg * const this /* r30 */, class BinStream & src /* r31 */) {} // Range: 0x8053A680 -> 0x8053A698 void VoiceDataMsg::GetVoiceData(const class VoiceDataMsg * const this /* r5 */) {} // Range: 0x8053A698 -> 0x8053A710 void VoiceDataMsg::Save(const class VoiceDataMsg * const this /* r30 */, class BinStream & dest /* r31 */) {} // Range: 0x8053A710 -> 0x8053A7E0 void VoiceDataMsg::Load(class VoiceDataMsg * const this /* r29 */, class BinStream & src /* r30 */) { // Local variables int numBytes; // r1+0x10 } // Range: 0x8053A7E0 -> 0x8053A84C void * DataArrayMsg::DataArrayMsg(class DataArrayMsg * const this /* r30 */, class DataArray * dataArray /* r31 */) { // References // -> struct [anonymous] __vt__12DataArrayMsg; } // Range: 0x8053A84C -> 0x8053A8B4 void DataArrayMsg::Save(const class DataArrayMsg * const this /* r30 */, class BinStream & dest /* r31 */) {} // Range: 0x8053A8B4 -> 0x8053A974 void DataArrayMsg::Load(class DataArrayMsg * const this /* r29 */, class BinStream & src /* r30 */) { // Local variables int numBytes; // r1+0x10 } // Range: 0x8053A974 -> 0x8053A9FC void DataArrayMsg::Dispatch() { // Local variables class DataArray * msg; // r1+0x8 } // Range: 0x8053A9FC -> 0x8053AADC void DataArrayMsg::Print(const class DataArrayMsg * const this /* r30 */, class TextStream & text /* r31 */) { // Local variables class MemStream newBuffer; // r1+0x10 class DataArray * msg; // r1+0xC } struct { // total size: 0x28 } __vt__12DataArrayMsg; // size: 0x28, address: 0x80907E70 struct { // total size: 0x8 } __RTTI__12DataArrayMsg; // size: 0x8, address: 0x80907EB8 struct { // total size: 0x28 } __vt__12VoiceDataMsg; // size: 0x28, address: 0x80907EC0 struct { // total size: 0x28 } __vt__10EndGameMsg; // size: 0x28, address: 0x80907EE8 struct { // total size: 0x28 } __vt__18StartGameOnTimeMsg; // size: 0x28, address: 0x80907F10 struct { // total size: 0x28 } __vt__18FinishedLoadingMsg; // size: 0x28, address: 0x80907F38 struct { // total size: 0x28 } __vt__15ChangePlayerMsg; // size: 0x28, address: 0x80907F60 struct { // total size: 0x28 } __vt__20AddPlayerResponseMsg; // size: 0x28, address: 0x80907F88 struct { // total size: 0x28 } __vt__19AddPlayerRequestMsg; // size: 0x28, address: 0x80907FB0 struct { // total size: 0x28 } __vt__13PlayerLeftMsg; // size: 0x28, address: 0x80907FD8 struct { // total size: 0x28 } __vt__12NewPlayerMsg; // size: 0x28, address: 0x80908000 struct { // total size: 0x28 } __vt__15JoinResponseMsg; // size: 0x28, address: 0x80908028 struct { // total size: 0x28 } __vt__14JoinRequestMsg; // size: 0x28, address: 0x80908050 struct { // total size: 0x8 } __RTTI__P9MemStream; // size: 0x8, address: 0x80908088
411
0.742336
1
0.742336
game-dev
MEDIA
0.628108
game-dev
0.506465
1
0.506465
The-Cataclysm-Preservation-Project/TrinityCore
15,168
src/server/game/Handlers/NPCHandler.cpp
/* * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "WorldSession.h" #include "Battleground.h" #include "BattlegroundMgr.h" #include "CharmInfo.h" #include "Common.h" #include "Creature.h" #include "CreatureAI.h" #include "DatabaseEnv.h" #include "DBCStores.h" #include "GossipDef.h" #include "Item.h" #include "Language.h" #include "Log.h" #include "Map.h" #include "NPCPackets.h" #include "ObjectMgr.h" #include "Opcodes.h" #include "Pet.h" #include "Player.h" #include "QueryCallback.h" #include "ReputationMgr.h" #include "ScriptMgr.h" #include "SpellInfo.h" #include "SpellMgr.h" #include "Trainer.h" #include "World.h" #include "WorldPacket.h" void WorldSession::HandleTabardVendorActivateOpcode(WorldPacket& recvData) { ObjectGuid guid; recvData >> guid; Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_TABARDDESIGNER); if (!unit) { TC_LOG_DEBUG("network", "WORLD: HandleTabardVendorActivateOpcode - %s not found or you can not interact with him.", guid.ToString().c_str()); return; } // remove fake death if (GetPlayer()->HasUnitState(UNIT_STATE_DIED)) GetPlayer()->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH); SendTabardVendorActivate(guid); } void WorldSession::SendTabardVendorActivate(ObjectGuid guid) { WorldPacket data(MSG_TABARDVENDOR_ACTIVATE, 8); data << guid; SendPacket(&data); } void WorldSession::HandleBankerActivateOpcode(WorldPackets::NPC::Hello& packet) { Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(packet.Unit, UNIT_NPC_FLAG_BANKER); if (!unit) { TC_LOG_DEBUG("network", "WORLD: HandleBankerActivateOpcode - %s not found or you can not interact with him.", packet.Unit.ToString().c_str()); return; } // remove fake death if (GetPlayer()->HasUnitState(UNIT_STATE_DIED)) GetPlayer()->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH); SendShowBank(packet.Unit); } void WorldSession::SendShowBank(ObjectGuid guid) { WorldPacket data(SMSG_SHOW_BANK, 8); data << guid; m_currentBankerGUID = guid; SendPacket(&data); } void WorldSession::SendShowMailBox(ObjectGuid guid) { WorldPacket data(SMSG_SHOW_MAILBOX, 8); data << guid; SendPacket(&data); } void WorldSession::HandleTrainerListOpcode(WorldPackets::NPC::Hello& packet) { Creature* npc = GetPlayer()->GetNPCIfCanInteractWith(packet.Unit, UNIT_NPC_FLAG_TRAINER); if (!npc) { TC_LOG_DEBUG("network", "WorldSession::SendTrainerList - %s not found or you can not interact with him.", packet.Unit.ToString().c_str()); return; } if (uint32 trainerId = sObjectMgr->GetCreatureDefaultTrainer(npc->GetEntry())) SendTrainerList(npc, trainerId); else TC_LOG_DEBUG("network", "WorldSession::SendTrainerList - Creature id %u has no trainer data.", npc->GetEntry()); } void WorldSession::SendTrainerList(Creature* npc, uint32 trainerId) { // remove fake death if (GetPlayer()->HasUnitState(UNIT_STATE_DIED)) GetPlayer()->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH); Trainer::Trainer const* trainer = sObjectMgr->GetTrainer(trainerId); if (!trainer) { TC_LOG_DEBUG("network", "WorldSession::SendTrainerList - trainer spells not found for trainer %s id %d", npc->GetGUID().ToString().c_str(), trainerId); return; } _player->PlayerTalkClass->GetInteractionData().Reset(); _player->PlayerTalkClass->GetInteractionData().SourceGuid = npc->GetGUID(); _player->PlayerTalkClass->GetInteractionData().TrainerId = trainerId; trainer->SendSpells(npc, _player, GetSessionDbLocaleIndex()); } void WorldSession::HandleTrainerBuySpellOpcode(WorldPackets::NPC::TrainerBuySpell& packet) { TC_LOG_DEBUG("network", "WORLD: Received CMSG_TRAINER_BUY_SPELL %s, learn spell id is: %u", packet.TrainerGUID.ToString().c_str(), packet.SpellID); Creature* npc = GetPlayer()->GetNPCIfCanInteractWith(packet.TrainerGUID, UNIT_NPC_FLAG_TRAINER); if (!npc) { TC_LOG_DEBUG("network", "WORLD: HandleTrainerBuySpellOpcode - %s not found or you can not interact with him.", packet.TrainerGUID.ToString().c_str()); return; } // remove fake death if (GetPlayer()->HasUnitState(UNIT_STATE_DIED)) GetPlayer()->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH); if (_player->PlayerTalkClass->GetInteractionData().SourceGuid != packet.TrainerGUID) return; if (_player->PlayerTalkClass->GetInteractionData().TrainerId != uint32(packet.TrainerID)) return; Trainer::Trainer const* trainer = sObjectMgr->GetTrainer(packet.TrainerID); if (!trainer) return; trainer->TeachSpell(npc, _player, packet.SpellID); } void WorldSession::HandleGossipHelloOpcode(WorldPackets::NPC::Hello& packet) { Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(packet.Unit, UNIT_NPC_FLAG_GOSSIP); if (!unit) { TC_LOG_DEBUG("network", "WORLD: HandleGossipHelloOpcode - %s not found or you can not interact with him.", packet.Unit.ToString().c_str()); return; } // set faction visible if needed if (FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(unit->GetFaction())) _player->GetReputationMgr().SetVisible(factionTemplateEntry); GetPlayer()->RemoveAurasWithInterruptFlags(SpellAuraInterruptFlags::Interacting); // Stop the npc if moving if (uint32 pause = unit->GetMovementTemplate().GetInteractionPauseTimer()) { unit->PauseMovement(pause); unit->SetHomePosition(unit->GetPosition()); } // If spiritguide, no need for gossip menu, just put player into resurrect queue if (unit->IsSpiritGuide()) { Battleground* bg = _player->GetBattleground(); if (bg) { bg->AddPlayerToResurrectQueue(unit->GetGUID(), _player->GetGUID()); sBattlegroundMgr->SendAreaSpiritHealerQueryOpcode(_player, bg, unit->GetGUID()); return; } } _player->PlayerTalkClass->ClearMenus(); if (!unit->AI()->GossipHello(_player)) { // _player->TalkedToCreature(unit->GetEntry(), unit->GetGUID()); _player->PrepareGossipMenu(unit, unit->GetCreatureTemplate()->GossipMenuId, true); // If npc is a flightmaster who is a quest giver do not send the gossip if there is no quest if (unit->IsTaxi() && (unit->IsQuestGiver() || unit->IsGossip())) { if (_player->PlayerTalkClass->GetQuestMenu().Empty() && _player->PlayerTalkClass->GetGossipMenu().Empty()) { SendTaxiMenu(unit); return; } } _player->SendPreparedGossip(unit); } } void WorldSession::HandleSpiritHealerActivateOpcode(WorldPacket& recvData) { TC_LOG_DEBUG("network", "WORLD: CMSG_SPIRIT_HEALER_ACTIVATE"); ObjectGuid guid; recvData >> guid; Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_SPIRITHEALER); if (!unit) { TC_LOG_DEBUG("network", "WORLD: HandleSpiritHealerActivateOpcode - %s not found or you can not interact with him.", guid.ToString().c_str()); return; } // remove fake death if (GetPlayer()->HasUnitState(UNIT_STATE_DIED)) GetPlayer()->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH); SendSpiritResurrect(); } void WorldSession::SendSpiritResurrect() { _player->ResurrectPlayer(0.5f, true); _player->DurabilityLossAll(0.25f, true); // get corpse nearest graveyard WorldSafeLocsEntry const* corpseGrave = nullptr; WorldLocation corpseLocation = _player->GetCorpseLocation(); if (_player->HasCorpse()) { corpseGrave = sObjectMgr->GetClosestGraveyard(corpseLocation, _player->GetTeam(), _player); } // now can spawn bones _player->SpawnCorpseBones(); // teleport to nearest from corpse graveyard, if different from nearest to player ghost if (corpseGrave) { WorldSafeLocsEntry const* ghostGrave = sObjectMgr->GetClosestGraveyard(*_player, _player->GetTeam(), _player); if (corpseGrave != ghostGrave) _player->TeleportTo(corpseGrave->Continent, corpseGrave->Loc.X, corpseGrave->Loc.Y, corpseGrave->Loc.Z, _player->GetOrientation()); } } void WorldSession::HandleBinderActivateOpcode(WorldPackets::NPC::Hello& packet) { if (!GetPlayer()->IsInWorld() || !GetPlayer()->IsAlive()) return; Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(packet.Unit, UNIT_NPC_FLAG_INNKEEPER); if (!unit) { TC_LOG_DEBUG("network", "WORLD: HandleBinderActivateOpcode - %s not found or you can not interact with him.", packet.Unit.ToString().c_str()); return; } // remove fake death if (GetPlayer()->HasUnitState(UNIT_STATE_DIED)) GetPlayer()->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH); SendBindPoint(unit); } void WorldSession::SendBindPoint(Creature* npc) { // prevent set homebind to instances in any case if (GetPlayer()->GetMap()->Instanceable()) return; uint32 bindspell = 3286; // send spell for homebinding (3286) npc->CastSpell(_player, bindspell, true); _player->PlayerTalkClass->SendCloseGossip(); } void WorldSession::HandleListStabledPetsOpcode(WorldPacket& recvData) { TC_LOG_DEBUG("network", "WORLD: Recv MSG_LIST_STABLED_PETS"); ObjectGuid npcGUID; recvData >> npcGUID; if (!CheckStableMaster(npcGUID)) return; // remove fake death if (GetPlayer()->HasUnitState(UNIT_STATE_DIED)) GetPlayer()->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH); // remove mounts this fix bug where getting pet from stable while mounted deletes pet. if (GetPlayer()->IsMounted()) GetPlayer()->RemoveAurasByType(SPELL_AURA_MOUNTED); SendStablePet(npcGUID); } void WorldSession::SendStablePet(ObjectGuid guid) { WorldPacket data(MSG_LIST_STABLED_PETS, 200); data << uint64(guid); // Stablemaster data << uint8(_player->PlayerPetDataStore.size()); data << uint8(PET_SLOT_LAST_STABLE_SLOT); // Stable Slots for (std::unique_ptr<PlayerPetData> const& p : _player->PlayerPetDataStore) { uint32 petSlot = p->Slot; uint8 flags = PET_STABLE_ACTIVE; if (petSlot > PET_SLOT_LAST_ACTIVE_SLOT) flags |= PET_STABLE_INACTIVE; data << int32(petSlot); data << uint32(p->PetId); data << uint32(p->CreatureId); data << uint32(p->Petlevel); data << p->Name; data << uint8(flags); } SendPacket(&data); } void WorldSession::SendStableResult(uint8 res) { WorldPacket data(SMSG_STABLE_RESULT, 1); data << uint8(res); SendPacket(&data); } void WorldSession::HandleSetPetSlot(WorldPacket& recvData) { TC_LOG_DEBUG("network", "WORLD: Recv CMSG_STABLE_PET"); ObjectGuid guid; uint32 petId; uint8 new_slot; recvData >> petId >> new_slot; guid[3] = recvData.ReadBit(); guid[2] = recvData.ReadBit(); guid[0] = recvData.ReadBit(); guid[7] = recvData.ReadBit(); guid[5] = recvData.ReadBit(); guid[6] = recvData.ReadBit(); guid[1] = recvData.ReadBit(); guid[4] = recvData.ReadBit(); recvData.ReadByteSeq(guid[5]); recvData.ReadByteSeq(guid[3]); recvData.ReadByteSeq(guid[1]); recvData.ReadByteSeq(guid[7]); recvData.ReadByteSeq(guid[4]); recvData.ReadByteSeq(guid[0]); recvData.ReadByteSeq(guid[6]); recvData.ReadByteSeq(guid[2]); if (!GetPlayer()->IsAlive()) { SendStableResult(STABLE_ERR_STABLE); return; } if (!CheckStableMaster(guid)) { SendStableResult(STABLE_ERR_STABLE); return; } if (new_slot > PET_SLOT_LAST_STABLE_SLOT) { SendStableResult(STABLE_ERR_STABLE); return; } PlayerPetData* playerPetData = _player->GetPlayerPetDataById(petId); CreatureTemplate const* creatureInfo = nullptr; if (playerPetData) creatureInfo = sObjectMgr->GetCreatureTemplate(playerPetData->CreatureId); if (!creatureInfo || !creatureInfo->IsTameable(true)) { SendStableResult(STABLE_ERR_STABLE); return; } if (!creatureInfo->IsTameable(_player->CanTameExoticPets()) && new_slot <= PET_SLOT_LAST_ACTIVE_SLOT) { SendStableResult(STABLE_ERR_EXOTIC); return; } // remove fake death 2 if (GetPlayer()->HasUnitState(UNIT_STATE_DIED)) GetPlayer()->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH); Pet* pet = _player->GetPet(); // can't place in stable dead pet if (pet) { if (pet->GetCharmInfo()->GetPetNumber() == petId) { if (!pet->IsAlive() || !pet->IsHunterPet()) { SendStableResult(STABLE_ERR_STABLE); return; } } } if (playerPetData) { UpdatePetSlot(petId, playerPetData->Slot, new_slot); } } void WorldSession::HandleStableRevivePet(WorldPacket &/* recvData */) { TC_LOG_DEBUG("network", "HandleStableRevivePet: Not implemented"); } void WorldSession::HandleRepairItemOpcode(WorldPacket& recvData) { TC_LOG_DEBUG("network", "WORLD: CMSG_REPAIR_ITEM"); ObjectGuid npcGUID, itemGUID; uint8 guildBank; // new in 2.3.2, bool that means from guild bank money recvData >> npcGUID >> itemGUID >> guildBank; Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(npcGUID, UNIT_NPC_FLAG_REPAIR); if (!unit) { TC_LOG_DEBUG("network", "WORLD: HandleRepairItemOpcode - %s not found or you can not interact with him.", npcGUID.ToString().c_str()); return; } // remove fake death if (GetPlayer()->HasUnitState(UNIT_STATE_DIED)) GetPlayer()->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH); // reputation discount float discountMod = _player->GetReputationPriceDiscount(unit); if (itemGUID) { TC_LOG_DEBUG("network", "ITEM: Repair %s, at %s", itemGUID.ToString().c_str(), npcGUID.ToString().c_str()); Item* item = _player->GetItemByGuid(itemGUID); if (item) _player->DurabilityRepair(item->GetPos(), true, discountMod); } else { TC_LOG_DEBUG("network", "ITEM: Repair all items at %s", npcGUID.ToString().c_str()); _player->DurabilityRepairAll(true, discountMod, guildBank != 0); } }
411
0.980836
1
0.980836
game-dev
MEDIA
0.945589
game-dev
0.972892
1
0.972892
ddiakopoulos/sandbox
1,902
vr-environment/third_party/bullet3/src/BulletCollision/NarrowPhaseCollision/btPointCollector.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_POINT_COLLECTOR_H #define BT_POINT_COLLECTOR_H #include "btDiscreteCollisionDetectorInterface.h" struct btPointCollector : public btDiscreteCollisionDetectorInterface::Result { btVector3 m_normalOnBInWorld; btVector3 m_pointInWorld; btScalar m_distance;//negative means penetration bool m_hasResult; btPointCollector () : m_distance(btScalar(BT_LARGE_FLOAT)),m_hasResult(false) { } virtual void setShapeIdentifiersA(int partId0,int index0) { (void)partId0; (void)index0; } virtual void setShapeIdentifiersB(int partId1,int index1) { (void)partId1; (void)index1; } virtual void addContactPoint(const btVector3& normalOnBInWorld,const btVector3& pointInWorld,btScalar depth) { if (depth< m_distance) { m_hasResult = true; m_normalOnBInWorld = normalOnBInWorld; m_pointInWorld = pointInWorld; //negative means penetration m_distance = depth; } } }; #endif //BT_POINT_COLLECTOR_H
411
0.856943
1
0.856943
game-dev
MEDIA
0.987122
game-dev
0.821747
1
0.821747
alphayellow1/AlphaYellowWidescreenFixes
7,016
source/fixes/TheAntBullyFOVFix/dllmain.cpp
// Include necessary headers #include "stdafx.h" #include "helper.hpp" #include <spdlog/spdlog.h> #include <spdlog/sinks/basic_file_sink.h> #include <inipp/inipp.h> #include <safetyhook.hpp> #include <vector> #include <map> #include <windows.h> #include <psapi.h> // For GetModuleInformation #include <fstream> #include <filesystem> #include <sstream> #include <cstring> #include <iomanip> #include <cstdint> #include <iostream> #include <algorithm> #include <cmath> #include <bit> #define spdlog_confparse(var) spdlog::info("Config Parse: {}: {}", #var, var) HMODULE exeModule = GetModuleHandle(NULL); HMODULE thisModule; // Fix details std::string sFixName = "TheAntBullyFOVFix"; std::string sFixVersion = "1.0"; std::filesystem::path sFixPath; // Ini inipp::Ini<char> ini; std::string sConfigFile = sFixName + ".ini"; // Logger std::shared_ptr<spdlog::logger> logger; std::string sLogFile = sFixName + ".log"; std::filesystem::path sExePath; std::string sExeName; // Ini variables bool bFixActive; int iCurrentResX; int iCurrentResY; float fFOVFactor; // Constants constexpr float fOldAspectRatio = 4.0f / 3.0f; // Variables float fNewAspectRatio; float fCurrentCameraHFOV; float fCurrentCameraVFOV; float fNewCameraHFOV; float fNewCameraVFOV; float fAspectRatioScale; // Game detection enum class Game { TAB, Unknown }; struct GameInfo { std::string GameTitle; std::string ExeName; }; const std::map<Game, GameInfo> kGames = { {Game::TAB, {"The Ant Bully", "TheAntBully.exe"}}, }; const GameInfo* game = nullptr; Game eGameType = Game::Unknown; void Logging() { // Get path to DLL WCHAR dllPath[_MAX_PATH] = { 0 }; GetModuleFileNameW(thisModule, dllPath, MAX_PATH); sFixPath = dllPath; sFixPath = sFixPath.remove_filename(); // Get game name and exe path WCHAR exePathW[_MAX_PATH] = { 0 }; GetModuleFileNameW(exeModule, exePathW, MAX_PATH); sExePath = exePathW; sExeName = sExePath.filename().string(); sExePath = sExePath.remove_filename(); // Spdlog initialization try { logger = spdlog::basic_logger_st(sFixName.c_str(), sExePath.string() + "\\" + sLogFile, true); spdlog::set_default_logger(logger); spdlog::flush_on(spdlog::level::debug); spdlog::set_level(spdlog::level::debug); // Enable debug level logging spdlog::info("----------"); spdlog::info("{:s} v{:s} loaded.", sFixName.c_str(), sFixVersion.c_str()); spdlog::info("----------"); spdlog::info("Log file: {}", sExePath.string() + "\\" + sLogFile); spdlog::info("----------"); spdlog::info("Module Name: {0:s}", sExeName.c_str()); spdlog::info("Module Path: {0:s}", sExePath.string()); spdlog::info("Module Address: 0x{0:X}", (uintptr_t)exeModule); spdlog::info("----------"); spdlog::info("DLL has been successfully loaded."); } catch (const spdlog::spdlog_ex& ex) { AllocConsole(); FILE* dummy; freopen_s(&dummy, "CONOUT$", "w", stdout); std::cout << "Log initialization failed: " << ex.what() << std::endl; FreeLibraryAndExitThread(thisModule, 1); } } void Configuration() { // Inipp initialization std::ifstream iniFile(sFixPath.string() + "\\" + sConfigFile); if (!iniFile) { AllocConsole(); FILE* dummy; freopen_s(&dummy, "CONOUT$", "w", stdout); std::cout << sFixName.c_str() << " v" << sFixVersion.c_str() << " loaded." << std::endl; std::cout << "ERROR: Could not locate config file." << std::endl; std::cout << "ERROR: Make sure " << sConfigFile.c_str() << " is located in " << sFixPath.string().c_str() << std::endl; spdlog::shutdown(); FreeLibraryAndExitThread(thisModule, 1); } else { spdlog::info("Config file: {}", sFixPath.string() + "\\" + sConfigFile); ini.parse(iniFile); } // Parse config ini.strip_trailing_comments(); spdlog::info("----------"); // Load settings from ini inipp::get_value(ini.sections["FOVFix"], "Enabled", bFixActive); spdlog_confparse(bFixActive); // Load resolution from ini inipp::get_value(ini.sections["Settings"], "Width", iCurrentResX); inipp::get_value(ini.sections["Settings"], "Height", iCurrentResY); inipp::get_value(ini.sections["Settings"], "FOVFactor", fFOVFactor); spdlog_confparse(iCurrentResX); spdlog_confparse(iCurrentResY); spdlog_confparse(fFOVFactor); // If resolution not specified, use desktop resolution if (iCurrentResX <= 0 || iCurrentResY <= 0) { spdlog::info("Resolution not specified in ini file. Using desktop resolution."); // Implement Util::GetPhysicalDesktopDimensions() accordingly auto desktopDimensions = Util::GetPhysicalDesktopDimensions(); iCurrentResX = desktopDimensions.first; iCurrentResY = desktopDimensions.second; spdlog_confparse(iCurrentResX); spdlog_confparse(iCurrentResY); } spdlog::info("----------"); } bool DetectGame() { for (const auto& [type, info] : kGames) { if (Util::stringcmp_caseless(info.ExeName, sExeName)) { spdlog::info("Detected game: {:s} ({:s})", info.GameTitle, sExeName); spdlog::info("----------"); eGameType = type; game = &info; return true; } } spdlog::error("Failed to detect supported game, {:s} isn't supported by the fix.", sExeName); return false; } void FOVFix() { if (eGameType == Game::TAB && bFixActive == true) { fNewAspectRatio = static_cast<float>(iCurrentResX) / static_cast<float>(iCurrentResY); fAspectRatioScale = fNewAspectRatio / fOldAspectRatio; std::uint8_t* CameraFOVInstructionScanResult = Memory::PatternScan(exeModule, "89 81 E4 00 00 00 89 91 E8 00 00 00 33 C0 C2 08 00 90 90 90 90 90 90 90"); if (CameraFOVInstructionScanResult) { spdlog::info("Camera FOV Instruction: Address is {:s}+{:x}", sExeName.c_str(), CameraFOVInstructionScanResult - (std::uint8_t*)exeModule); Memory::PatchBytes(CameraFOVInstructionScanResult, "\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90", 12); static SafetyHookMid CameraFOVInstructionsMidHook{}; CameraFOVInstructionsMidHook = safetyhook::create_mid(CameraFOVInstructionScanResult, [](SafetyHookContext& ctx) { fCurrentCameraHFOV = std::bit_cast<float>(ctx.eax); fNewCameraHFOV = Maths::CalculateNewFOV_MultiplierBased(fCurrentCameraHFOV, fAspectRatioScale) * fFOVFactor; *reinterpret_cast<float*>(ctx.ecx + 0xE4) = fNewCameraHFOV; fNewCameraVFOV = fNewCameraHFOV / fNewAspectRatio; *reinterpret_cast<float*>(ctx.ecx + 0xE8) = fNewCameraVFOV; }); } else { spdlog::info("Cannot locate the camera FOV instruction memory address."); return; } } } DWORD __stdcall Main(void*) { Logging(); Configuration(); if (DetectGame()) { FOVFix(); } return TRUE; } BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: { thisModule = hModule; HANDLE mainHandle = CreateThread(NULL, 0, Main, 0, NULL, 0); if (mainHandle) { SetThreadPriority(mainHandle, THREAD_PRIORITY_HIGHEST); CloseHandle(mainHandle); } break; } case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; }
411
0.979198
1
0.979198
game-dev
MEDIA
0.386326
game-dev
0.910504
1
0.910504
SevenDucks/WauzCore
2,510
src/main/java/eu/wauz/wauzcore/players/ui/scoreboard/OneBlockScoreboard.java
package eu.wauz.wauzcore.players.ui.scoreboard; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import eu.wauz.wauzcore.data.players.PlayerCollectionConfigurator; import eu.wauz.wauzcore.oneblock.OneBlockProgression; import eu.wauz.wauzcore.oneblock.OnePhase; import eu.wauz.wauzcore.oneblock.OnePhaseLevel; import eu.wauz.wauzcore.system.util.Formatters; import eu.wauz.wauzcore.system.util.WauzDateUtils; /** * A scoreboard to show the server ip, season, commands, aswell as their one-block progress and tokens to a player. * * @author Wauzmons */ public class OneBlockScoreboard extends BaseScoreboard { /** * Initializes the scoreboard and fills it with data. * * @param player The player who should receive the scoreboard. */ public OneBlockScoreboard(Player player) { super(player); } /** * @return The text to show as scoreboard title. */ @Override public String getTitleText() { return ChatColor.GOLD + "" + ChatColor.BOLD + "OneBlock" + ChatColor.RESET; } /** * Fills the scoreboard with entries for the given player * * @param player The player who should receive the scoreboard. */ @Override public void fillScoreboard(Player player) { rowStrings.add(""); rowStrings.add("" + ChatColor.WHITE + ChatColor.BOLD + "OneBlock Season " + WauzDateUtils.getSurvivalSeason()); rowStrings.add("" + ChatColor.WHITE + ChatColor.BOLD + "IP: play.wauz.eu"); rowStrings.add(" "); OneBlockProgression progression = OneBlockProgression.getPlayerOneBlock(player); OnePhase phase = progression.getPhase(); OnePhaseLevel level = progression.getLevel(); int currentBlock = progression.getBlockNo(); int maximumBlock = level.getBlockAmount(); int totalBlocks = progression.getTotalBlocks(); rowStrings.add("Phase: " + ChatColor.GREEN + phase.getPhaseName() + " " + level.getLevelName()); rowStrings.add("Block Progress: " + ChatColor.YELLOW + currentBlock + " / " + maximumBlock); rowStrings.add(" "); rowStrings.add("Total Blocks: " + ChatColor.AQUA + Formatters.INT.format(totalBlocks)); rowStrings.add("Earn a free Token"); rowStrings.add("for every 300 Blocks"); rowStrings.add(" "); rowStrings.add("Tokens: " + ChatColor.GOLD + Formatters.INT.format(PlayerCollectionConfigurator.getTokens(player))); rowStrings.add("Use an Ender Chest to Spend"); rowStrings.add(" "); rowStrings.add(ChatColor.LIGHT_PURPLE + "/" + ChatColor.WHITE + "hub " + ChatColor.LIGHT_PURPLE + "/" + ChatColor.WHITE + "spawn"); } }
411
0.891221
1
0.891221
game-dev
MEDIA
0.912365
game-dev
0.884616
1
0.884616
Razcoina/Bully-SE-scripts
20,266
scripts/chap3/3_01A.lua
local bLoop = true local countMax = 3 local CurrentMissionIndex = 0 local CurrentMission local tblRiderData = {} local tblPedModels = { 252, 42, 43, 41, 45, 91, 97 } local lVictim = {} local lVictimBlip = {} local ModelBikes = { 274, 273, 272, 281 } local tblVictimInfo = {} local tblMissionParams = {} local VictimCounter = 0 local VictimMax = 10 local bRudyBusted = false local ACTIONFILE function MissionSetup() print("***************************************** 3_10 Mission setup *************************************") DATLoad("3_01A.DAT", 2) DATInit() if AreaGetVisible() ~= 0 then AreaTransitionPoint(0, POINTLIST._3_10_PLAYERSCENE01) else PlayerSetPosPoint(POINTLIST._3_10_PLAYERSCENE01) end PlayCutsceneWithLoad("3-01AA", true) MissionDontFadeIn() tblMissionParams = { { "3_01A_MOBJ_01", POINTLIST._3_10_LADDER01, POINTLIST._3_10_RUDYMOVE01, POINTLIST._3_10_MISSION01 }, { POINTLIST._3_10_MISSION01FIRE, POINTLIST._3_10_PLAYERWARP, "3_01A_TEXT_01" } } tblVictimInfo = { { TYPE = 0, MODEL = tblPedModels[2], STARTFLG = POINTLIST._3_10_SSSTART01, MOVETO = POINTLIST._3_10_SSMOVE01 }, { TYPE = 0, MODEL = tblPedModels[3], STARTFLG = POINTLIST._3_10_SSSTART02, MOVETO = POINTLIST._3_10_SSMOVE02 }, { TYPE = 1, MODEL = tblPedModels[4], STARTFLG = POINTLIST._3_10_SBSTART01, PATH = PATH._3_10_PATH01, PATHSTART = 0 }, { TYPE = 1, MODEL = tblPedModels[5], STARTFLG = POINTLIST._3_10_SBSTART02, PATH = PATH._3_10_PATH02, PATHSTART = 0 }, { TYPE = 2, MODEL = tblPedModels[6], STARTFLG = POINTLIST._3_10_BIKER01, PATH = PATH._3_10_BIKEPATH01, PATHSTART = 0, BIKESTART = POINTLIST._3_10_BIKE01 }, { TYPE = 2, MODEL = tblPedModels[3], STARTFLG = POINTLIST._3_10_BIKER02, PATH = PATH._3_10_BIKEPATH01, PATHSTART = 3, BIKESTART = POINTLIST._3_10_BIKE02 }, { TYPE = 1, MODEL = tblPedModels[4], STARTFLG = POINTLIST._3_10_SBSTART01, PATH = PATH._3_10_PATH01, PATHSTART = 0 }, { TYPE = 1, MODEL = tblPedModels[5], STARTFLG = POINTLIST._3_10_SBSTART02, PATH = PATH._3_10_PATH02, PATHSTART = 0 }, { TYPE = 2, MODEL = tblPedModels[6], STARTFLG = POINTLIST._3_10_BIKER01, PATH = PATH._3_10_BIKEPATH01, PATHSTART = 0, BIKESTART = POINTLIST._3_10_BIKE01 }, { TYPE = 2, MODEL = tblPedModels[3], STARTFLG = POINTLIST._3_10_BIKER02, PATH = PATH._3_10_BIKEPATH01, PATHSTART = 3, BIKESTART = POINTLIST._3_10_BIKE02 } } LoadPedModels(tblPedModels) LoadAnimationGroup("MINI_BallToss") ACTIONFILE = "Act/Conv/3_01a.act" LoadActionTree(ACTIONFILE) LoadWeaponModels({ 313 }) end function MissionCleanup() SoundFadeWithCamera(false) MusicFadeWithCamera(false) F_KillControls(false) DATUnload(2) PedSetTypeToTypeAttitude(3, 4, 2) PedSetTypeToTypeAttitude(3, 9, 2) PedSetTypeToTypeAttitude(9, 4, 2) lVictim = nil tblVictimInfo = nil UnloadModels(tblPedModels) PlayerSetInvulnerable(false) end function main() print("*************************** 3_10 Main ******************************************") SetPopulation() F_KillControls(true) PedSetWeaponNow(gPlayer, MODELENUM._NOWEAPON, 1) if PedIsOnVehicle(gPlayer) then PlayerDetachFromVehicle() end PedSetWeaponNow(gPlayer, -1, 0) gRudy = PedCreatePoint(252, POINTLIST._3_10_RUDYSCENE01, 1) PedLockTarget(gRudy, gPlayer) PedFaceObject(gRudy, gPlayer, 3, 1) CameraReset() CameraReturnToPlayer() PedIgnoreStimuli(gRudy, true) PedSetStationary(gRudy, true) PedSetMissionCritical(gRudy, true, F_MissionFailed, true) PedMakeTargetable(gRudy, true) F_SetNextMission() end function SetPopulation() SetAmbientPedsIgnoreStimuli(true) DisablePOI() AreaClearAllPeds() AreaOverridePopulation(20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 0, 0) AreaClearAllVehicles() VehicleOverrideAmbient(0, 0, 0, 0) end function F_InitMission() local bTimerExpired = false PedSetMissionCritical(gRudy, true, F_RUDYBUSTED, true) CameraFade(500, 1) Wait(1000) F_KillControls(false) SoundPlayInteractiveStream("MS_XmasBellsRudyLow.rsm", 0.9, 0, 500) SoundSetMidIntensityStream("MS_XmasBellsRudyMid.rsm", 0.9, 0, 500) SoundSetHighIntensityStream("MS_XmasBellsRudyHigh.rsm", 0.9, 0, 500) TextPrint(tblMissionParams[CurrentMissionIndex][1], 5, 1) objId = MissionObjectiveAdd(tblMissionParams[CurrentMissionIndex][1], 1) Mission_blip = BlipAddPoint(tblMissionParams[CurrentMissionIndex][2], 0, 1, 1, 7) while bLoop do Wait(0) if PedIsPlaying(gPlayer, "/Global/Ladder/Ladder_Actions/Climb_ON_BOT", true) then BlipRemove(Mission_blip) PedSetStationary(gRudy, false) PedMoveToPoint(gRudy, 0, tblMissionParams[CurrentMissionIndex][3], 1) break end if F_CheckDist() then bTimerExpired = true break end end if not bTimerExpired then Mission_blip = BlipAddPoint(tblMissionParams[CurrentMissionIndex][4], 0, 1, 1, 7) local bx, by, bz = GetPointList(tblMissionParams[CurrentMissionIndex][4]) while bLoop do Wait(0) if PlayerIsInAreaXYZ(bx, by, bz, 1, 1) then Mission_blip = BlipRemove(Mission_blip) objId = MissionObjectiveRemove(objId) break end if F_CheckDist() then bTimerExpired = true break end end end if not bTimerExpired then F_SetNextMission() end end function F_DistanceBetweenPeds(ped1, ped2) local X1, Y1, _ = PedGetPosXYZ(ped1) local X2, Y2, _ = PedGetPosXYZ(ped2) return DistanceBetweenCoords2d(X1, Y1, X2, Y2) end local bGuyGotHit = false local bEndVictimCheck = false function F_StartMission() local bCompleted = false local bx, by, bz = GetPointList(tblMissionParams[CurrentMissionIndex][1]) local bTimerExpired = false PlayerSetInvulnerable(true) F_SetVictim() F_SetVictim() Wait(100) F_EnterSnowBallCam(true, tblMissionParams[CurrentMissionIndex][1]) TextPrint(tblMissionParams[CurrentMissionIndex][3], 5, 1) objId = MissionObjectiveAdd(tblMissionParams[CurrentMissionIndex][3], 1) SoundFadeWithCamera(true) MusicFadeWithCamera(true) F_SetVictimCounter(VictimMax) BOSTimer(180) Wait(1000) CreateThread("F_CheckVicims") local bCopWasSummoned = false while bLoop do Wait(0) if CounterGetCurrent() >= CounterGetMax() then MissionObjectiveRemove(objId) break else F_RudySpeak() end if bResetPlayer == true then F_ResetPlayer() end PedSetPunishmentPoints(gRudy, PlayerGetPunishmentPoints()) if PlayerGetPunishmentPoints() >= 300 and bCopWasSummoned == false then print("Here Comes the Cops") gCop1 = PedCreatePoint(97, POINTLIST._3_10_BIKER01, 1) PedMoveToPoint(gCop1, 2, POINTLIST._3_10_RudyMove01, 1) bCopWasSummoned = true end if bCopWasSummoned == true and gCop1 ~= nil and F_DistanceBetweenPeds(gCop1, gRudy) < 4 then bRudyBusted = true break end if BOSTimer() then bTimerExpired = true break end if bGuyGotHit == true then F_SetVictim() F_RudyCheer() bGuyGotHit = false end if not PlayerHasWeapon(313) and PlayerIsInAreaXYZ(bx, by, bz, 3, 1) then F_PlayerEquipSnowBall(true) F_RudyBoo() end end bEndVictimCheck = true Wait(1000) F_ClearVictimIcon() F_EnterSnowBallCam(false, tblMissionParams[CurrentMissionIndex][2], true) for i, tped in tblVictimInfo do if tped.lBike ~= nil then VehicleDelete(tped.lBike) end end BOSTimerEnd() if bRudyBusted == true then F_MissionFAILED() elseif bTimerExpired == true then F_MissionFAILEDTimer() else F_SetNextMission() end end local bDistWarning function F_CheckDist() if F_DistanceBetweenPeds(gPlayer, gRudy) > 50 then if bDistWarning == nil then TutorialShowMessage("3_01A_WARNING2", -1, true) BOSTimer(30) bDistWarning = true elseif BOSTimer() == true then F_MissionFAILEDDist() bDistWarning = nil return true end elseif bDistWarning == true then BOSTimerEnd() TutorialRemoveMessage() bDistWarning = nil end return false end function F_MissionFAILEDDist() PedSetMissionCritical(gRudy, false) PedDelete(gRudy) SoundPlayMissionEndMusic(false, 10) MissionFail(false, true, "3_01A_FAIL_03") end function F_MissionFAILEDTimer() PedSetPunishmentPoints(gPlayer, 0) PedSetPunishmentPoints(gRudy, 0) DisablePunishmentSystem(true) AreaClearAllVehicles() PedSetMissionCritical(gRudy, false) PedDelete(gRudy) CameraReturnToPlayer() CameraFade(500, 1) Wait(500) SoundPlayMissionEndMusic(false, 10) MissionFail(false, true, "3_01A_FAIL_02") end function F_MissionFAILED() F_KillControls(true) PedSetPunishmentPoints(gPlayer, 0) PedSetPunishmentPoints(gRudy, 0) DisablePunishmentSystem(true) AreaClearAllVehicles() if gCop1 ~= nil and PedIsValid(gCop1) then PedDelete(gCop1) end PedSetMissionCritical(gRudy, false) PedDelete(gRudy) CameraReturnToPlayer() CameraFade(500, 1) Wait(500) F_KillControls(false) SoundPlayMissionEndMusic(false, 10) MissionFail(false, true, "3_01A_FAIL_01") end function F_MissionEnd() F_KillControls(true) PedSetPunishmentPoints(gPlayer, 0) PedSetPunishmentPoints(gRudy, 0) DisablePunishmentSystem(true) AreaClearAllVehicles() Wait(500) PlayCutsceneWithLoad("3-01AB", true) DisablePunishmentSystem(false) PedSetMissionCritical(gRudy, false) PedDelete(gRudy) PlayerSetPosPoint(POINTLIST._3_10_PLAYERWARP, 1) CameraReturnToPlayer() CameraFade(500, 1) Wait(500) F_KillControls(false) MinigameSetCompletion("M_PASS", true, 2000) SoundPlayScriptedSpeechEvent(gPlayer, "PLAYER_SUCCESS", 0, "jumbo") SoundPlayMissionEndMusic(true, 10) Wait(2000) ClothingGivePlayer("SP_Antlers", 0) MinigameSetCompletion("MEN_BLANK", true, 0, "TUT_301A") MissionSucceed(false, false, false) end function F_KillControls(bOff) if bOff == true then print("**************** KillControl ON ********************") DisablePunishmentSystem(true) PauseGameClock() CameraSetWidescreen(true) PedMakeTargetable(gPlayer, false) PlayerSetControl(0) else print("**************** KillControl OFF ********************") DisablePunishmentSystem(false) UnpauseGameClock() CameraSetWidescreen(false) PedMakeTargetable(gPlayer, true) PlayerSetControl(1) ButtonHistoryIgnoreController(false) PedLockTarget(gPlayer, -1) SoundStopInteractiveStream() SoundEnableInteractiveMusic(true) PlayerWeaponHudLock(false) PlayerIgnoreTargeting(false) end end function EnableHudComponents(bShow) PlayerWeaponHudLock(not bShow) ToggleHUDComponentVisibility(11, bShow) ToggleHUDComponentVisibility(4, bShow) ToggleHUDComponentVisibility(0, bShow) end function F_SetVictimCounter(cMax) bCompleted = false CounterClearText() CounterSetCurrent(0) CounterSetMax(cMax) CounterSetIcon("snowface", "snowface_x") CounterMakeHUDVisible(true) end function F_HitAVictim() CounterIncrementCurrent(1) MissionObjectiveUpdateParam(objId, 1, CounterGetMax() - CounterGetCurrent()) if CounterGetCurrent() >= CounterGetMax() then return true else return false end end function F_ClearVictimIcon(txtMissionText) if txtMissionText ~= nil then MissionObjectiveRemove(objId) objId = MissionObjectiveAdd(txtMissionText) MissionObjectiveComplete(objId) end Wait(100) CounterMakeHUDVisible(false) CounterSetMax(0) CounterSetCurrent(0) CounterClearIcon() end function F_SetVictim() if VictimCounter < VictimMax then VictimCounter = VictimCounter + 1 --DebugPrint(" ************************* Vic Counter = " .. VictimCounter) PedSetTypeToTypeAttitude(3, 9, 4) lVictim[VictimCounter] = PedCreatePoint(tblPedModels[math.random(2, 6)], tblVictimInfo[VictimCounter].STARTFLG) tblVictimInfo[VictimCounter].HasBeenHit = false if tblVictimInfo[VictimCounter].TYPE == 1 then PedFollowPath(lVictim[VictimCounter], tblVictimInfo[VictimCounter].PATH, 1, 0) elseif tblVictimInfo[VictimCounter].TYPE == 2 then tblVictimInfo[VictimCounter].lBike = VehicleCreatePoint(ModelBikes[math.random(1, 4)], tblVictimInfo[VictimCounter].BIKESTART, 1) PedPutOnBike(lVictim[VictimCounter], tblVictimInfo[VictimCounter].lBike) PedFollowPath(lVictim[VictimCounter], tblVictimInfo[VictimCounter].PATH, 1, 0, F_FinishedRide, tblVictimInfo[VictimCounter].PATHSTART) else PedMoveToPoint(lVictim[VictimCounter], 1, tblVictimInfo[VictimCounter].MOVETO, 1) end lVictimBlip[VictimCounter] = AddBlipForChar(lVictim[VictimCounter], 12, 17, 4) PedIgnoreStimuli(lVictim[VictimCounter], true) PedSetStationary(lVictim[VictimCounter], false) PedIgnoreAttacks(lVictim[VictimCounter], true) end end function F_CheckVicims() local GotOne = false while true do for vIndex, vic in lVictim do if PedGetWhoHitMeLast(lVictim[vIndex]) == gPlayer and PedGetLastHitWeapon(lVictim[vIndex]) == 313 and tblVictimInfo[vIndex].HasBeenHit == false then BlipRemove(lVictimBlip[vIndex]) tblVictimInfo[vIndex].HasBeenHit = true CounterIncrementCurrent(1) MissionObjectiveUpdateParam(objId, 1, CounterGetMax() - CounterGetCurrent()) PedClearObjectives(lVictim[vIndex]) PedSetStationary(lVictim[vIndex], false) PedIgnoreAttacks(lVictim[vIndex], false) PedIgnoreStimuli(lVictim[vIndex], false) PedClearHitRecord(lVictim[vIndex]) PedMakeAmbient(lVictim[vIndex], true) PedSetMissionCritical(lVictim[vIndex], false) PedFlee(lVictim[vIndex], gPlayer) bGuyGotHit = true end end if bEndVictimCheck == true then break end Wait(0) end end function F_FinishedRide(pedID, pathID, PathNode) end function F_EnterSnowBallCam(bEnable, flgPlayerPos, bNoFadeIN) if bEnable == true then --print(">>>[RUI]", "++EnterSnowBallCam") CameraFade(500, 0) Wait(501) PlayerSetPosPoint(flgPlayerPos, 1) PedSetActionTree(gPlayer, "/Global/3_01A/SnowBall", ACTIONFILE) Wait(10) F_PlayerEquipSnowBall(true) Wait(10) PedSetFlag(gRudy, 117, true) PedMakeTargetable(gRudy, true) PedMakeTargetable(gPlayer, false) PedSetInvulnerable(gPlayer, true) RegisterPedEventHandler(gPlayer, 0, cbResetPlayer) AreaDisableCameraControlForTransition(false) CameraSetActive(13) Wait(0) CameraAllowChange(false) SoundPlayInteractiveStream("MS_XmasBellsRudyHigh.rsm", 0.9, 0, 500) SoundSetMidIntensityStream("MS_XmasBellsRudyHigh.rsm", 0.9, 0, 500) SoundSetHighIntensityStream("MS_XmasBellsRudyHigh.rsm", 0.9, 0, 500) if not bNoFadeIN then CameraFade(500, 1) Wait(501) end else --print(">>>[RUI]", "--EnterSnowBallCam") CameraFade(500, 0) Wait(501) SoundPlayInteractiveStream("MS_XmasBellsRudyLow.rsm", 0.9, 0, 500) SoundSetMidIntensityStream("MS_XmasBellsRudyMid.rsm", 0.9, 0, 500) SoundSetHighIntensityStream("MS_XmasBellsRudyHigh.rsm", 0.9, 0, 500) RegisterPedEventHandler(gPlayer, 0, nil) F_PlayerEquipSnowBall(false) Wait(200) PedSetActionTree(gPlayer, "/Global/Player", "Act/Player.act") PlayerSetPosPoint(flgPlayerPos, 1) PedSetFlag(gRudy, 117, false) PedMakeTargetable(gRudy, false) PedMakeTargetable(gPlayer, true) PedSetInvulnerable(gPlayer, false) CameraAllowChange(true) EnableHudComponents(true) CameraSetActive(1) AreaDisableCameraControlForTransition(false) CameraClearRotationLimit() CameraReturnToPlayer() CameraReset() if bNoFadeIN ~= true then print(" ******************* fade in worked **********************") CameraFade(500, 1) Wait(501) end end end local bResetPlayer = false function cbResetPlayer() bResetPlayer = true end function F_ResetPlayer() F_EnterSnowBallCam(false, tblMissionParams[CurrentMissionIndex][1]) PlayerSetControl(0) Wait(2000) PlayerSetControl(1) F_EnterSnowBallCam(true, tblMissionParams[CurrentMissionIndex][1]) bResetPlayer = false end function F_PlayerEquipSnowBall(bEquip) if bEquip == true then --print(">>>[RUI]", "++PlayerEquipBaseball") PedSetActionNode(gPlayer, "/Global/3_01A/SnowBall/GiveBall/GiveBall", ACTIONFILE) else --print(">>>[RUI]", "--PlayerEquipBaseball") PedSetActionNode(gPlayer, "/Global/3_01A/SnowBall/RemoveBall", ACTIONFILE) end end local gSpeechPlayed = false local gSpeechTimer = 0 function F_RudySpeak() if gSpeechPlayed == false then SoundStopCurrentSpeechEvent(gRudy) SoundPlayScriptedSpeechEvent(gRudy, "M_3_01A", 9, "jumbo", true) gSpeechPlayed = true gSpeechTimer = GetTimer() elseif GetTimer() - gSpeechTimer > 15000 then gSpeechPlayed = false end end function F_RudyCheer() print(" ********************** Rudy Cheer ******************************* ") SoundStopCurrentSpeechEvent(gRudy) SoundPlayScriptedSpeechEvent(gRudy, "M_3_01A", 10, "jumbo", true) gSpeechTimer = GetTimer() gSpeechPlayed = true end function F_RudyBoo() if gSpeechPlayed == false then SoundStopCurrentSpeechEvent(gRudy) SoundPlayScriptedSpeechEvent(gRudy, "M_3_01A", 11, "jumbo", true) gSpeechPlayed = true gSpeechTimer = GetTimer() elseif GetTimer() - gSpeechTimer > 20000 then gSpeechPlayed = false end end tblMissions = { F_InitMission, F_StartMission, F_MissionEnd } function F_SetNextMission() CurrentMissionIndex = CurrentMissionIndex + 1 CurrentMission = tblMissions[CurrentMissionIndex] CurrentMission() end function F_RUDYBUSTED() print(" *************** Got Busted *************************") bRudyBusted = true end function BOSTimer(cTime) if cTime then MissionTimerStart(cTime) elseif MissionTimerHasFinished() then MissionTimerStop() return true end return false end function BOSTimerEnd() MissionTimerStop() ToggleHUDComponentVisibility(3, false) end
411
0.856962
1
0.856962
game-dev
MEDIA
0.781238
game-dev,testing-qa
0.960108
1
0.960108
hojat72elect/libgdx_games
2,076
Dark_Matter/core/src/main/kotlin/com/github/quillraven/darkmatter/ui/GameOverUI.kt
package com.github.quillraven.darkmatter.ui import com.badlogic.gdx.math.MathUtils import com.badlogic.gdx.scenes.scene2d.ui.TextButton import com.badlogic.gdx.utils.Align import com.badlogic.gdx.utils.I18NBundle import ktx.i18n.get import ktx.scene2d.KTableWidget import ktx.scene2d.label import ktx.scene2d.scene2d import ktx.scene2d.table import ktx.scene2d.textButton private const val OFFSET_TITLE_Y = 15f private const val MENU_ELEMENT_OFFSET_TITLE_Y = 20f private const val MENU_DEFAULT_PADDING = 10f private const val MAX_HIGHSCORE_DISPLAYED = 999 class GameOverUI(private val bundle: I18NBundle) { val table: KTableWidget private val lastScoreButton: TextButton private val highScoreButton: TextButton val backButton: TextButton init { table = scene2d.table { defaults().pad(MENU_DEFAULT_PADDING).expandX().fillX() label(bundle["gameTitle"], SkinLabel.LARGE.name) { cell -> wrap = true setAlignment(Align.center) cell.apply { padTop(OFFSET_TITLE_Y) padBottom(MENU_ELEMENT_OFFSET_TITLE_Y) } } row() lastScoreButton = textButton(bundle["score", 0], SkinTextButton.LABEL.name) row() highScoreButton = textButton(bundle["highscore", 0], SkinTextButton.LABEL.name) row() backButton = textButton(bundle["backToMenu"], SkinTextButton.DEFAULT.name) row() setFillParent(true) top() pack() } } fun updateScores(score: Int, highScore: Int) { lastScoreButton.label.run { text.setLength(0) text.append(bundle["score", MathUtils.clamp(score, 0, MAX_HIGHSCORE_DISPLAYED)]) invalidateHierarchy() } highScoreButton.label.run { text.setLength(0) text.append(bundle["highscore", MathUtils.clamp(highScore, 0, MAX_HIGHSCORE_DISPLAYED)]) invalidateHierarchy() } } }
411
0.800937
1
0.800937
game-dev
MEDIA
0.640162
game-dev
0.849984
1
0.849984
hlrs-vis/covise
3,616
src/OpenCOVER/DrivingSim/TrafficSimulation/VehicleManager.h
/* This file is part of COVISE. You can use it under the terms of the GNU Lesser General Public License version 2.1 or later, see lgpl-2.1.txt. * License: LGPL 2+ */ #ifndef VehicleManager_h #define VehicleManager_h #include "Vehicle.h" #include <VehicleUtil/RoadSystem/RoadSystem.h> #include <map> #include <list> #include "VehicleUtils.h" #include <cover/coTabletUI.h> namespace TrafficSimulation { // forward declarations // // class HumanVehicle; class PorscheFFZ; class TRAFFICSIMULATIONEXPORT VehicleManager { public: static VehicleManager* Instance(); static void Destroy(); void addVehicle(Vehicle*); void removeVehicle(VehicleList::iterator, vehicleUtil::Road*); void removeVehicle(Vehicle*, vehicleUtil::Road*); void removeAllAgents(double maxVel = 1.0); // delete all vehicles slower than maxVel void changeRoad(VehicleList::iterator, vehicleUtil::Road*, vehicleUtil::Road*, int); void changeRoad(Vehicle*, vehicleUtil::Road*, vehicleUtil::Road*, int); void moveVehicle(VehicleList::iterator, int); void moveVehicle(Vehicle*, int); Vehicle* getNextVehicle(VehicleList::iterator, int); Vehicle* getNextVehicle(Vehicle*, int); Vehicle* getNextVehicle(VehicleList::iterator, int, int); Vehicle* getNextVehicle(Vehicle*, int, int); Vehicle* getFirstVehicle(vehicleUtil::Road*); Vehicle* getLastVehicle(vehicleUtil::Road*); Vehicle* getFirstVehicle(vehicleUtil::Road*, int); Vehicle* getLastVehicle(vehicleUtil::Road*, int); Vehicle* getVehicleByID(unsigned int); HumanVehicle* getHumanVehicle(); void setMaximumNumberOfVehicles(unsigned int maxNum) { maximumNumberOfVehicles = maxNum; } unsigned int getMaximumNumberOfVehicles() { return maximumNumberOfVehicles; } void sortVehicleList(vehicleUtil::Road*); const VehicleList& getVehicleList(vehicleUtil::Road*); std::map<double, Vehicle*> getSurroundingVehicles(Vehicle*); std::map<double, Vehicle*> getSurroundingVehicles(VehicleList::iterator); void setCameraVehicle(int); void switchToNextCamera(); void switchToPreviousCamera(); void unbindCamera(); //void brakeCameraVehicle(); bool isJunctionEmpty(vehicleUtil::Junction*); void moveAllVehicles(double); void updateFiddleyards(double, osg::Vec2d); //void sendDataTo(coTUIMap* operatorMap); void sendDataTo(PorscheFFZ* ffzBroadcaster); void receiveDataFrom(PorscheFFZ* ffzBroadcaster); VehicleList getVehicleOverallList(); std::vector<vehicleUtil::Vector3D> acitve_fiddleyards; protected: VehicleManager(); static VehicleManager* __instance; void insertVehicleAtFront(Vehicle*, vehicleUtil::Road*); void insertVehicleAtBack(Vehicle*, vehicleUtil::Road*); void moveVehicleForward(VehicleList::iterator); void moveVehicleBackward(VehicleList::iterator); void showVehicleList(vehicleUtil::Road*); vehicleUtil::RoadSystem* system; std::map<vehicleUtil::Road*, VehicleList> roadVehicleListMap; VehicleList vehicleOverallList; Vehicle* cameraVehicle; VehicleList::iterator cameraVehicleIt; VehicleDeque vehicleDecisionDeque; unsigned int maximumNumberOfVehicles; private: HumanVehicle* humanVehicle; // lazy initialization, so use getHumanVehicle() }; } #endif
411
0.761233
1
0.761233
game-dev
MEDIA
0.237934
game-dev
0.901809
1
0.901809
muddery/muddery
2,232
muddery/common/utils/defines.py
""" This module defines constent constant values. """ from enum import Enum # quest dependencies DEPENDENCY_NONE = "" DEPENDENCY_QUEST_CAN_PROVIDE = "CAN_PROVIDE" DEPENDENCY_QUEST_ACCEPTED = "ACCEPTED" DEPENDENCY_QUEST_NOT_ACCEPTED = "NOT_ACCEPTED" DEPENDENCY_QUEST_IN_PROGRESS = "IN_PROGRESS" DEPENDENCY_QUEST_NOT_IN_PROGRESS = "NOT_IN_PROGRESS" DEPENDENCY_QUEST_ACCOMPLISHED = "ACCOMPLISHED" # quest accomplished DEPENDENCY_QUEST_NOT_ACCOMPLISHED = "NOT_ACCOMPLISHED" # quest accepted but not accomplished DEPENDENCY_QUEST_FINISHED = "FINISHED" # quest finished DEPENDENCY_QUEST_NOT_FINISHED = "NOT_FINISHED" # quest accepted but not finished # quest objective types OBJECTIVE_NONE = "" OBJECTIVE_TALK = "OBJECTIVE_TALK" # finish a dialogue, object: dialogue_id OBJECTIVE_ARRIVE = "OBJECTIVE_ARRIVE" # arrive a room, object: room_id OBJECTIVE_OBJECT = "OBJECTIVE_OBJECT" # get some objects, object: object_id OBJECTIVE_KILL = "OBJECTIVE_KILL" # kill some characters, object: character_id # event types EVENT_NONE = "" EVENT_ATTACK = "EVENT_ATTACK" # event to begin a combat EVENT_DIALOGUE = "EVENT_DIALOGUE" # event to begin a dialogue # combat result COMBAT_WIN = "COMBAT_WIN" # win the combat COMBAT_LOSE = "COMBAT_LOSE" # lose the combat COMBAT_DRAW = "COMBAT_DRAW" # no one wins the combat COMBAT_ESCAPED = "COMBAT_ESCAPED" # escaped from the combat class EventType(str, Enum): # event trigger types EVENT_TRIGGER_ARRIVE = "EVENT_TRIGGER_ARRIVE" # at attriving a room. object: room_id EVENT_TRIGGER_KILL = "EVENT_TRIGGER_KILL" # caller kills one. object: dead_one_id EVENT_TRIGGER_DIE = "EVENT_TRIGGER_DIE" # caller die. object: killer_id EVENT_TRIGGER_TRAVERSE = "EVENT_TRIGGER_TRAVERSE" # before traverse an exit. object: exit_id EVENT_TRIGGER_DIALOGUE = "EVENT_TRIGGER_DIALOGUE" # called when a character finishes a dialogue sentence. class ConversationType(Enum): PRIVATE = "PRIVATE" LOCAL = "LOCAL" CHANNEL = "CHANNEL" class CombatType(Enum): NORMAL = "NORMAL" HONOUR = "HONOUR"
411
0.818046
1
0.818046
game-dev
MEDIA
0.91924
game-dev
0.801975
1
0.801975
Kyushik/DRL
18,910
DQN_GAMES/dot_test.py
# Dot game # By KyushikMin kyushikmin@gmail.com # http://mmc.hanyang.ac.kr import random, pygame, time, sys, copy from pygame.locals import * FPS = 30 WINDOW_WIDTH = 240 WINDOW_HEIGHT = 280 GAME_BOARD_GAP = 20 ############## Automatic setting (later work) GAME_BOARD_SIZE = 40 GAME_BOARD_HORIZONTAL = int((WINDOW_WIDTH - 2*GAME_BOARD_GAP) / GAME_BOARD_SIZE) # 50 is for message GAME_BOARD_VERTICAL = int((WINDOW_HEIGHT - 2*GAME_BOARD_GAP - 30) / GAME_BOARD_SIZE) # Color setting # R G B WHITE = (255, 255, 255) BLACK = ( 0, 0, 0) BRIGHT_RED = (255, 0, 0) RED = (155, 0, 0) BRIGHT_GREEN = ( 0, 255, 0) GREEN = ( 0, 155, 0) BRIGHT_BLUE = ( 0, 0, 255) BLUE = ( 0, 0, 155) BRIGHT_YELLOW = (255, 255, 0) YELLOW = (155, 155, 0) DARK_GRAY = ( 40, 40, 40) LIGHT_GRAY = ( 80, 80, 80) bgColor = BLACK gameboard_Color = BLACK obstacle_Color = LIGHT_GRAY text_Color = WHITE tile_Color = LIGHT_GRAY clicked_tile_Color = RED line_Color = WHITE food_Color = GREEN enemy_Color = RED my_Color = BRIGHT_BLUE def ReturnName(): return 'dot_test' def Return_Num_Action(): return 4 class GameState: def __init__(self): global FPS_CLOCK, DISPLAYSURF, BASIC_FONT # Set the initial variables pygame.init() FPS_CLOCK = pygame.time.Clock() DISPLAYSURF = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) pygame.display.set_caption('Dot Chasing') BASIC_FONT = pygame.font.Font('freesansbold.ttf', 18) Movement_list = ['North', 'South', 'West', 'East', 'Stop'] difficulty = 'Easy' #set up the variables self.score = 0 self.Game_board_state = [] self.Coordinate_info = [] self.My_position = [] self.Enemy_list = [] self.Food_list = [] self.Last_enemy_move = [] self.Game_board_state, self.Coordinate_info = self.drawGameBoard(difficulty) self.checkForQuit() self.drawBasicBoard() # initialize the position of myself, enemy, food self.count_init = 0 self.reward_food = 1 self.reward_enemy = -1 self.count_food = 0 def reinit(self): #set up the variables self.score = 0 self.Last_enemy_move = [] difficulty = 'Easy' self.Game_board_state, self.Coordinate_info = self.drawGameBoard(difficulty) self.checkForQuit() self.drawBasicBoard() self.count_init = 0 self.count_food = 0 # Main function def frame_step(self, input): self.checkForQuit() ###################### Game display ###################### DISPLAYSURF.fill(bgColor) terminal = False scoreSurf = BASIC_FONT.render('Score: ' + str(self.score), 1, WHITE) scoreRect = scoreSurf.get_rect() scoreRect.topleft = (WINDOW_WIDTH - 200, 10) # self.drawBasicBoard() # self.Game_board_state, self.Coordinate_info = self.drawGameBoard(difficulty) self.checkForQuit() # initialize the position of myself, enemy, food # if self.count_init == 0: # self.Game_board_state, self.Coordinate_info = self.drawGameBoard(difficulty) if self.count_init == 0: self.My_position = self.Coordinate_info[0][0] self.Enemy_list = self.Coordinate_info[1] self.Food_list = self.Coordinate_info[2] self.Last_enemy_move = [] for i in range(len(self.Enemy_list)): self.Last_enemy_move.append('Stop') # self.DrawGameBoardState(self.Game_board_state) self.DrawGameBoardState() self.Drawlines() if (input[1] == 1) and ('North' in self.ValidMove_list((self.My_position[0], self.My_position[1]))): self.Game_board_state[self.My_position[1] - 1][self.My_position[0]] = '@' self.Game_board_state[self.My_position[1]][self.My_position[0]] = 0 self.My_position[1] = self.My_position[1] - 1 elif (input[0] == 1) and ('South' in self.ValidMove_list((self.My_position[0], self.My_position[1]))): self.Game_board_state[self.My_position[1] + 1][self.My_position[0]] = '@' self.Game_board_state[self.My_position[1]][self.My_position[0]] = 0 self.My_position[1] = self.My_position[1] + 1 elif (input[2] == 1) and ('East' in self.ValidMove_list((self.My_position[0], self.My_position[1]))): self.Game_board_state[self.My_position[1]][self.My_position[0] + 1] = '@' self.Game_board_state[self.My_position[1]][self.My_position[0]] = 0 self.My_position[0] = self.My_position[0] + 1 elif (input[3] == 1) and ('West' in self.ValidMove_list((self.My_position[0], self.My_position[1]))): self.Game_board_state[self.My_position[1]][self.My_position[0] - 1] = '@' self.Game_board_state[self.My_position[1]][self.My_position[0]] = 0 self.My_position[0] = self.My_position[0] - 1 reward = -0.01 # #move enemy for i in range(len(self.Enemy_list)): valid_move_list = self.ValidMove_list((self.Enemy_list[i][0], self.Enemy_list[i][1])) if self.Last_enemy_move[i] in valid_move_list: valid_move_list.remove(self.Last_enemy_move[i]) valid_move = random.choice(valid_move_list) if valid_move == 'North': self.Game_board_state[self.Enemy_list[i][1] - 1][self.Enemy_list[i][0]] = '-' self.Game_board_state[self.Enemy_list[i][1]][self.Enemy_list[i][0]] = 0 self.Enemy_list[i][1] = self.Enemy_list[i][1] - 1 self.Last_enemy_move[i] = 'South' elif valid_move == 'South': self.Game_board_state[self.Enemy_list[i][1] + 1][self.Enemy_list[i][0]] = '-' self.Game_board_state[self.Enemy_list[i][1]][self.Enemy_list[i][0]] = 0 self.Enemy_list[i][1] = self.Enemy_list[i][1] + 1 self.Last_enemy_move[i] = 'North' elif valid_move == 'East': self.Game_board_state[self.Enemy_list[i][1]][self.Enemy_list[i][0] + 1] = '-' self.Game_board_state[self.Enemy_list[i][1]][self.Enemy_list[i][0]] = 0 self.Enemy_list[i][0] = self.Enemy_list[i][0] + 1 self.Last_enemy_move[i] = 'West' elif valid_move == 'West': self.Game_board_state[self.Enemy_list[i][1]][self.Enemy_list[i][0] - 1] = '-' self.Game_board_state[self.Enemy_list[i][1]][self.Enemy_list[i][0]] = 0 self.Enemy_list[i][0] = self.Enemy_list[i][0] - 1 self.Last_enemy_move[i] = 'East' else: self.Last_enemy_move[i] = 'Stop' self.checkForQuit() # Draw food for i in range(len(self.Food_list)): self.Game_board_state[self.Food_list[i][1]][self.Food_list[i][0]] = '+' # Eat the foods if self.My_position in self.Food_list: self.Food_list.remove(self.My_position) reward = self.reward_food self.score += 1.0 self.count_food += 1 self.Food_list.append(self.Get_random_position()) # if self.count_food == 5: # terminal = True # image_data = pygame.surfarray.array3d(pygame.display.get_surface()) # self.reinit() # pygame.display.update() # return image_data, reward, terminal # Killed by enemy if self.My_position in self.Enemy_list: reward = self.reward_enemy self.score -= self.reward_enemy image_data = pygame.surfarray.array3d(pygame.display.get_surface()) # print('\n') # print('----------------------------------------------------------') # print('your final score is ' + str(self.score)) # print('----------------------------------------------------------') # print('\n') terminal = True self.reinit() return image_data, reward, terminal score_SURF, score_RECT = self.makeText('score: ' + str(self.score) + ' ', WHITE, BLACK, WINDOW_WIDTH - 200, 10) DISPLAYSURF.blit(score_SURF, score_RECT) pygame.display.update() self.checkForQuit() self.count_init = 1 image_data = pygame.surfarray.array3d(pygame.display.get_surface()) return image_data, reward, terminal def terminate(self): pygame.quit() sys.exit() def checkForQuit(self): for event in pygame.event.get(QUIT): # Bring every QUIT event terminate() # Exit then event occured for event in pygame.event.get(KEYUP): # Bring every KEYUP event if event.key == K_ESCAPE: terminate() # if KEYUP event is ESC then quit pygame.event.post(event) # Other KEYUP event object is returned to event que def makeText(self,text, color, bgcolor, top, left): # Show surface object, Rect object textSurf = BASIC_FONT.render(text, True, color, bgcolor) textRect = textSurf.get_rect() textRect.topleft = (top, left) return (textSurf, textRect) def drawBasicBoard(self): for i in range(GAME_BOARD_HORIZONTAL+1): for j in range(GAME_BOARD_VERTICAL+1): pygame.draw.rect(DISPLAYSURF, gameboard_Color, (GAME_BOARD_GAP + i * GAME_BOARD_SIZE, 50 + GAME_BOARD_GAP + j * GAME_BOARD_SIZE, GAME_BOARD_SIZE, GAME_BOARD_SIZE)) # pygame.draw.line(DISPLAYSURF, line_Color, (GAME_BOARD_GAP + i * GAME_BOARD_SIZE, GAME_BOARD_GAP + 50),(GAME_BOARD_GAP + i * GAME_BOARD_SIZE, 50 + GAME_BOARD_GAP + GAME_BOARD_VERTICAL * GAME_BOARD_SIZE),2) # pygame.draw.line(DISPLAYSURF, line_Color, (GAME_BOARD_GAP, 50 + GAME_BOARD_GAP + j * GAME_BOARD_SIZE), (GAME_BOARD_GAP + GAME_BOARD_HORIZONTAL * GAME_BOARD_SIZE, 50 + GAME_BOARD_GAP + j * GAME_BOARD_SIZE),2) def Drawlines(self): for i in range(GAME_BOARD_HORIZONTAL+1): for j in range(GAME_BOARD_VERTICAL+1): pygame.draw.line(DISPLAYSURF, line_Color, (GAME_BOARD_GAP + i * GAME_BOARD_SIZE, GAME_BOARD_GAP + 50),(GAME_BOARD_GAP + i * GAME_BOARD_SIZE, 50 + GAME_BOARD_GAP + GAME_BOARD_VERTICAL * GAME_BOARD_SIZE),2) pygame.draw.line(DISPLAYSURF, line_Color, (GAME_BOARD_GAP, 50 + GAME_BOARD_GAP + j * GAME_BOARD_SIZE), (GAME_BOARD_GAP + GAME_BOARD_HORIZONTAL * GAME_BOARD_SIZE, 50 + GAME_BOARD_GAP + j * GAME_BOARD_SIZE),2) def drawGameBoard(self,difficulty): if difficulty == 'Easy': # Game_board_state = [[ 0, 0, 0, 0, 0, 0, 0 ],\ # [ 0, 0, 0, 0, 0, 0, 0 ],\ # [ 0, 0, 0, 0, 0, 0, 0 ],\ # ['@', 0, 0,'+', 0, 0,'-'],\ # [ 0, 0, 0, 0, 0, 0, 0 ],\ # [ 0, 0, 0, 0, 0, 0, 0 ],\ # [ 0, 0, 0, 0, 0, 0, 0 ]] Game_board_state = [[ 0, 0, 0, 0, 0 ],\ [ 0, 0, 0, 0, 0 ],\ ['@', 0,'+', 0,'-'],\ [ 0, 0, 0, 0, 0 ],\ [ 0, 0, 0, 0, 0 ]] # Game_board_state = [[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '@', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\ # [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\ # [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\ # [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\ # [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\ # [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\ # [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\ # [ 0, 0, '-', 0, 0, 0, '-', 0, 0, 0, 0, 0, '+', 0, 0, 0, 0, 0, '-', 0, 0, 0, '-', 0, 0],\ # [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\ # [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\ # [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\ # [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\ # [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\ # [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] elif difficulty == 'Medium': Game_board_state = [[ 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, '@', 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1],\ [ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],\ [ 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0],\ [ 0, 1, '+','-', 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, '-','+', 1, 0],\ [ 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0],\ [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\ [ 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1],\ [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\ [ 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0],\ [ 0, 1, '+','-', 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, '-','+', 1, 0],\ [ 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0],\ [ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],\ [ 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, '+', 1, 0, 1, '+', 1, 0, 1, 0, 0, 1, 0, 1, 0, 1],\ [ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]] elif difficulty == 'Hard': Game_board_state = [['+', 0, 0, 0, 1, 0, 0, 0, 0, 0, '@', 0, 0, 0, 0, 0, 0, 0, 0, 0, '+', 0, 0, 0, 0],\ [ 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0],\ [ 0, 0, 0, '-', 1, '-', 0, 0, 0, 0, 0, 0, 0, '+', 0, 0, '-', 0, 0, 0, '+', 0, 0, 0, 0],\ [ 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0],\ [ 0, 0, 0, 0, 1, 0, 0, '+', 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0],\ [ 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0],\ [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '+', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\ [ 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0],\ [ 0, 0, 0, 0, 0, 0, '+', 0, 0, 0, '-', 0, 0, 0, 0, 0, 0, '-', 0, 0, '+', 0, 0, 0, 0],\ [ 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0],\ [ 0, 0, 0, '-', 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0],\ [ 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0],\ [ 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0],\ ['+', 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]] # Add coordinate info Coordinate_info = [[],[],[]] for i in range(GAME_BOARD_HORIZONTAL): for j in range(GAME_BOARD_VERTICAL): center_point = (GAME_BOARD_GAP + i * GAME_BOARD_SIZE + GAME_BOARD_SIZE/2 + 1, 50 + GAME_BOARD_GAP + j * GAME_BOARD_SIZE + GAME_BOARD_SIZE/2 + 1) radius = GAME_BOARD_SIZE/2 - 2 if Game_board_state[j][i] == 1: pygame.draw.rect(DISPLAYSURF, obstacle_Color, (GAME_BOARD_GAP + i * GAME_BOARD_SIZE, 50 + GAME_BOARD_GAP + j * GAME_BOARD_SIZE, GAME_BOARD_SIZE, GAME_BOARD_SIZE)) elif Game_board_state[j][i] == '+': pygame.draw.polygon(DISPLAYSURF, food_Color, ((center_point[0], center_point[1] + radius), (center_point[0] + radius, center_point[1]), (center_point[0], center_point[1] - radius), (center_point[0] - radius, center_point[1])), 10) Coordinate_info[2].append([i,j]) elif Game_board_state[j][i] == '-': Coordinate_info[1].append([i,j]) pygame.draw.rect(DISPLAYSURF, enemy_Color, (GAME_BOARD_GAP + i * GAME_BOARD_SIZE + 5, 50 + GAME_BOARD_GAP + j * GAME_BOARD_SIZE + 5, GAME_BOARD_SIZE - 5, GAME_BOARD_SIZE - 5)) elif Game_board_state[j][i] == '@': pygame.draw.rect(DISPLAYSURF, my_Color, (GAME_BOARD_GAP + i * GAME_BOARD_SIZE + 5, 50 + GAME_BOARD_GAP + j * GAME_BOARD_SIZE + 5, GAME_BOARD_SIZE - 5, GAME_BOARD_SIZE - 5)) # pygame.draw.circle(DISPLAYSURF, my_Color, center_point, radius, 10) Coordinate_info[0].append([i,j]) pygame.display.update() return Game_board_state, Coordinate_info def DrawGameBoardState(self): for i in range(GAME_BOARD_HORIZONTAL): for j in range(GAME_BOARD_VERTICAL): center_point = (GAME_BOARD_GAP + i * GAME_BOARD_SIZE + GAME_BOARD_SIZE/2 + 1, 50 + GAME_BOARD_GAP + j * GAME_BOARD_SIZE + GAME_BOARD_SIZE/2 + 1) radius = GAME_BOARD_SIZE/2 - 2 if self.Game_board_state[j][i] == 1: pygame.draw.rect(DISPLAYSURF, obstacle_Color, (GAME_BOARD_GAP + i * GAME_BOARD_SIZE, 50 + GAME_BOARD_GAP + j * GAME_BOARD_SIZE, GAME_BOARD_SIZE, GAME_BOARD_SIZE)) elif self.Game_board_state[j][i] == '+': # pygame.draw.circle(DISPLAYSURF, food_Color, (GAME_BOARD_GAP + i * GAME_BOARD_SIZE + GAME_BOARD_SIZE/2 + 1, 50 + GAME_BOARD_GAP + j * GAME_BOARD_SIZE + GAME_BOARD_SIZE/2 + 1), GAME_BOARD_SIZE/2 - 2, 10) pygame.draw.polygon(DISPLAYSURF, food_Color, ((center_point[0], center_point[1] + radius - 3), (center_point[0] + radius - 3, center_point[1]), (center_point[0], center_point[1] - radius + 3), (center_point[0] - radius + 3, center_point[1])), 10) elif self.Game_board_state[j][i] == '-': pygame.draw.rect(DISPLAYSURF, enemy_Color, (GAME_BOARD_GAP + i * GAME_BOARD_SIZE + 5, 50 + GAME_BOARD_GAP + j * GAME_BOARD_SIZE + 5, GAME_BOARD_SIZE - 10, GAME_BOARD_SIZE - 10)) elif self.Game_board_state[j][i] == '@': pygame.draw.rect(DISPLAYSURF, my_Color, (GAME_BOARD_GAP + i * GAME_BOARD_SIZE + 5, 50 + GAME_BOARD_GAP + j * GAME_BOARD_SIZE + 5, GAME_BOARD_SIZE - 5, GAME_BOARD_SIZE - 5)) # pygame.draw.circle(DISPLAYSURF, my_Color, center_point, radius, 10) pygame.display.update() def ValidMove_list(self, state): # return the valid move( no obstacles and no out of bound) state_x = state[0] state_y = state[1] valid_move = [] if state_y + 1 <= GAME_BOARD_VERTICAL - 1 and self.Game_board_state[state_y + 1][state_x] != 1: valid_move.append('South') if state_y -1 >= 0 and self.Game_board_state[state_y - 1][state_x] != 1: valid_move.append('North') if state_x - 1 >= 0 and self.Game_board_state[state_y][state_x - 1] != 1: valid_move.append('West') if state_x + 1 <= GAME_BOARD_HORIZONTAL - 1 and self.Game_board_state[state_y][state_x + 1] != 1: valid_move.append('East') valid_move.append('Stop') return valid_move def Get_random_position(self): while True: random_x = random.randint(1,GAME_BOARD_HORIZONTAL-1) random_y = random.randint(1,GAME_BOARD_VERTICAL-1) if self.Game_board_state[random_y][random_x] != 1 and \ self.Game_board_state[random_y][random_x] != '-' and \ self.Game_board_state[random_y][random_x] != '@': return [random_x, random_y] break if __name__ == '__main__': main()
411
0.826859
1
0.826859
game-dev
MEDIA
0.536957
game-dev
0.960605
1
0.960605
MinorKeyGames/Eldritch
1,639
Code/Projects/Eldritch/src/BTNodes/rodinbtnodeeldlookat.cpp
#include "core.h" #include "rodinbtnodeeldlookat.h" #include "configmanager.h" #include "Components/wbcomprodinblackboard.h" #include "wbeventmanager.h" RodinBTNodeEldLookAt::RodinBTNodeEldLookAt() : m_LookTargetBlackboardKey() { } RodinBTNodeEldLookAt::~RodinBTNodeEldLookAt() { } void RodinBTNodeEldLookAt::InitializeFromDefinition( const SimpleString& DefinitionName ) { MAKEHASH( DefinitionName ); STATICHASH( LookTargetBlackboardKey ); m_LookTargetBlackboardKey = ConfigManager::GetHash( sLookTargetBlackboardKey, HashedString::NullString, sDefinitionName ); } RodinBTNode::ETickStatus RodinBTNodeEldLookAt::Tick( float DeltaTime ) { Unused( DeltaTime ); WBEntity* const pEntity = GetEntity(); WBCompRodinBlackboard* const pAIBlackboard = GET_WBCOMP( pEntity, RodinBlackboard ); ASSERT( pAIBlackboard ); const WBEvent::EType TargetType = pAIBlackboard->GetType( m_LookTargetBlackboardKey ); if( TargetType == WBEvent::EWBEPT_Vector ) { const Vector LookTarget = pAIBlackboard->GetVector( m_LookTargetBlackboardKey ); WB_MAKE_EVENT( LookAt, pEntity ); WB_SET_AUTO( LookAt, Vector, LookAtLocation, LookTarget ); WB_DISPATCH_EVENT( GetEventManager(), LookAt, pEntity ); return ETS_Success; } else if( TargetType == WBEvent::EWBEPT_Entity ) { WBEntity* const pLookTargetEntity = pAIBlackboard->GetEntity( m_LookTargetBlackboardKey ); if( !pLookTargetEntity ) { return ETS_Fail; } WB_MAKE_EVENT( LookAt, pEntity ); WB_SET_AUTO( LookAt, Entity, LookAtEntity, pLookTargetEntity ); WB_DISPATCH_EVENT( GetEventManager(), LookAt, pEntity ); return ETS_Success; } return ETS_Fail; }
411
0.658888
1
0.658888
game-dev
MEDIA
0.71238
game-dev
0.558292
1
0.558292
Hork-Engine/Hork-Source
2,298
ThirdParty/JoltPhysics/Jolt/Physics/Constraints/Constraint.cpp
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics) // SPDX-FileCopyrightText: 2021 Jorrit Rouwe // SPDX-License-Identifier: MIT #include <Jolt/Jolt.h> #include <Jolt/Physics/Constraints/Constraint.h> #include <Jolt/Physics/StateRecorder.h> #include <Jolt/ObjectStream/TypeDeclarations.h> #include <Jolt/Core/StreamUtils.h> JPH_NAMESPACE_BEGIN JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(ConstraintSettings) { JPH_ADD_BASE_CLASS(ConstraintSettings, SerializableObject) JPH_ADD_ATTRIBUTE(ConstraintSettings, mEnabled) JPH_ADD_ATTRIBUTE(ConstraintSettings, mDrawConstraintSize) JPH_ADD_ATTRIBUTE(ConstraintSettings, mConstraintPriority) JPH_ADD_ATTRIBUTE(ConstraintSettings, mNumVelocityStepsOverride) JPH_ADD_ATTRIBUTE(ConstraintSettings, mNumPositionStepsOverride) JPH_ADD_ATTRIBUTE(ConstraintSettings, mUserData) } void ConstraintSettings::SaveBinaryState(StreamOut &inStream) const { inStream.Write(GetRTTI()->GetHash()); inStream.Write(mEnabled); inStream.Write(mDrawConstraintSize); inStream.Write(mConstraintPriority); inStream.Write(mNumVelocityStepsOverride); inStream.Write(mNumPositionStepsOverride); } void ConstraintSettings::RestoreBinaryState(StreamIn &inStream) { // Type hash read by sRestoreFromBinaryState inStream.Read(mEnabled); inStream.Read(mDrawConstraintSize); inStream.Read(mConstraintPriority); inStream.Read(mNumVelocityStepsOverride); inStream.Read(mNumPositionStepsOverride); } ConstraintSettings::ConstraintResult ConstraintSettings::sRestoreFromBinaryState(StreamIn &inStream) { return StreamUtils::RestoreObject<ConstraintSettings>(inStream, &ConstraintSettings::RestoreBinaryState); } void Constraint::SaveState(StateRecorder &inStream) const { inStream.Write(mEnabled); } void Constraint::RestoreState(StateRecorder &inStream) { inStream.Read(mEnabled); } void Constraint::ToConstraintSettings(ConstraintSettings &outSettings) const { outSettings.mEnabled = mEnabled; outSettings.mConstraintPriority = mConstraintPriority; outSettings.mNumVelocityStepsOverride = mNumVelocityStepsOverride; outSettings.mNumPositionStepsOverride = mNumPositionStepsOverride; outSettings.mUserData = mUserData; #ifdef JPH_DEBUG_RENDERER outSettings.mDrawConstraintSize = mDrawConstraintSize; #endif // JPH_DEBUG_RENDERER } JPH_NAMESPACE_END
411
0.824756
1
0.824756
game-dev
MEDIA
0.17397
game-dev
0.563629
1
0.563629
SinanErmis/HyperTemplate
17,107
Assets/Plugins/Demigiant/DOTween/Modules/DOTweenModuleUnityVersion.cs
// Author: Daniele Giardini - http://www.demigiant.com // Created: 2018/07/13 using System; using UnityEngine; using DG.Tweening.Core; using DG.Tweening.Plugins.Options; #if UNITY_2018_1_OR_NEWER && (NET_4_6 || NET_STANDARD_2_0) using System.Threading.Tasks; #endif #pragma warning disable 1591 namespace DG.Tweening { /// <summary> /// Shortcuts/functions that are not strictly related to specific Modules /// but are available only on some Unity versions /// </summary> public static class DOTweenModuleUnityVersion { #if UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5 || UNITY_2017_1_OR_NEWER #region Unity 4.3 or Newer #region Material /// <summary>Tweens a Material's color using the given gradient /// (NOTE 1: only uses the colors of the gradient, not the alphas - NOTE 2: creates a Sequence, not a Tweener). /// Also stores the image as the tween's target so it can be used for filtered operations</summary> /// <param name="gradient">The gradient to use</param><param name="duration">The duration of the tween</param> public static Sequence DOGradientColor(this Material target, Gradient gradient, float duration) { Sequence s = DOTween.Sequence(); GradientColorKey[] colors = gradient.colorKeys; int len = colors.Length; for (int i = 0; i < len; ++i) { GradientColorKey c = colors[i]; if (i == 0 && c.time <= 0) { target.color = c.color; continue; } float colorDuration = i == len - 1 ? duration - s.Duration(false) // Verifies that total duration is correct : duration * (i == 0 ? c.time : c.time - colors[i - 1].time); s.Append(target.DOColor(c.color, colorDuration).SetEase(Ease.Linear)); } s.SetTarget(target); return s; } /// <summary>Tweens a Material's named color property using the given gradient /// (NOTE 1: only uses the colors of the gradient, not the alphas - NOTE 2: creates a Sequence, not a Tweener). /// Also stores the image as the tween's target so it can be used for filtered operations</summary> /// <param name="gradient">The gradient to use</param> /// <param name="property">The name of the material property to tween (like _Tint or _SpecColor)</param> /// <param name="duration">The duration of the tween</param> public static Sequence DOGradientColor(this Material target, Gradient gradient, string property, float duration) { Sequence s = DOTween.Sequence(); GradientColorKey[] colors = gradient.colorKeys; int len = colors.Length; for (int i = 0; i < len; ++i) { GradientColorKey c = colors[i]; if (i == 0 && c.time <= 0) { target.SetColor(property, c.color); continue; } float colorDuration = i == len - 1 ? duration - s.Duration(false) // Verifies that total duration is correct : duration * (i == 0 ? c.time : c.time - colors[i - 1].time); s.Append(target.DOColor(c.color, property, colorDuration).SetEase(Ease.Linear)); } s.SetTarget(target); return s; } #endregion #endregion #endif #if UNITY_5_3_OR_NEWER || UNITY_2017_1_OR_NEWER #region Unity 5.3 or Newer #region CustomYieldInstructions /// <summary> /// Returns a <see cref="CustomYieldInstruction"/> that waits until the tween is killed or complete. /// It can be used inside a coroutine as a yield. /// <para>Example usage:</para><code>yield return myTween.WaitForCompletion(true);</code> /// </summary> public static CustomYieldInstruction WaitForCompletion(this Tween t, bool returnCustomYieldInstruction) { if (!t.active) { if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); return null; } return new DOTweenCYInstruction.WaitForCompletion(t); } /// <summary> /// Returns a <see cref="CustomYieldInstruction"/> that waits until the tween is killed or rewinded. /// It can be used inside a coroutine as a yield. /// <para>Example usage:</para><code>yield return myTween.WaitForRewind();</code> /// </summary> public static CustomYieldInstruction WaitForRewind(this Tween t, bool returnCustomYieldInstruction) { if (!t.active) { if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); return null; } return new DOTweenCYInstruction.WaitForRewind(t); } /// <summary> /// Returns a <see cref="CustomYieldInstruction"/> that waits until the tween is killed. /// It can be used inside a coroutine as a yield. /// <para>Example usage:</para><code>yield return myTween.WaitForKill();</code> /// </summary> public static CustomYieldInstruction WaitForKill(this Tween t, bool returnCustomYieldInstruction) { if (!t.active) { if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); return null; } return new DOTweenCYInstruction.WaitForKill(t); } /// <summary> /// Returns a <see cref="CustomYieldInstruction"/> that waits until the tween is killed or has gone through the given amount of loops. /// It can be used inside a coroutine as a yield. /// <para>Example usage:</para><code>yield return myTween.WaitForElapsedLoops(2);</code> /// </summary> /// <param name="elapsedLoops">Elapsed loops to wait for</param> public static CustomYieldInstruction WaitForElapsedLoops(this Tween t, int elapsedLoops, bool returnCustomYieldInstruction) { if (!t.active) { if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); return null; } return new DOTweenCYInstruction.WaitForElapsedLoops(t, elapsedLoops); } /// <summary> /// Returns a <see cref="CustomYieldInstruction"/> that waits until the tween is killed /// or has reached the given time position (loops included, delays excluded). /// It can be used inside a coroutine as a yield. /// <para>Example usage:</para><code>yield return myTween.WaitForPosition(2.5f);</code> /// </summary> /// <param name="position">Position (loops included, delays excluded) to wait for</param> public static CustomYieldInstruction WaitForPosition(this Tween t, float position, bool returnCustomYieldInstruction) { if (!t.active) { if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); return null; } return new DOTweenCYInstruction.WaitForPosition(t, position); } /// <summary> /// Returns a <see cref="CustomYieldInstruction"/> that waits until the tween is killed or started /// (meaning when the tween is set in a playing state the first time, after any eventual delay). /// It can be used inside a coroutine as a yield. /// <para>Example usage:</para><code>yield return myTween.WaitForStart();</code> /// </summary> public static CustomYieldInstruction WaitForStart(this Tween t, bool returnCustomYieldInstruction) { if (!t.active) { if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); return null; } return new DOTweenCYInstruction.WaitForStart(t); } #endregion #endregion #endif #if UNITY_2018_1_OR_NEWER #region Unity 2018.1 or Newer #region Material /// <summary>Tweens a Material's named texture offset property with the given ID to the given value. /// Also stores the material as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param> /// <param name="propertyID">The ID of the material property to tween (also called nameID in Unity's manual)</param> /// <param name="duration">The duration of the tween</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOOffset(this Material target, Vector2 endValue, int propertyID, float duration) { if (!target.HasProperty(propertyID)) { if (Debugger.logPriority > 0) Debugger.LogMissingMaterialProperty(propertyID); return null; } TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.GetTextureOffset(propertyID), x => target.SetTextureOffset(propertyID, x), endValue, duration); t.SetTarget(target); return t; } /// <summary>Tweens a Material's named texture scale property with the given ID to the given value. /// Also stores the material as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param> /// <param name="propertyID">The ID of the material property to tween (also called nameID in Unity's manual)</param> /// <param name="duration">The duration of the tween</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOTiling(this Material target, Vector2 endValue, int propertyID, float duration) { if (!target.HasProperty(propertyID)) { if (Debugger.logPriority > 0) Debugger.LogMissingMaterialProperty(propertyID); return null; } TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.GetTextureScale(propertyID), x => target.SetTextureScale(propertyID, x), endValue, duration); t.SetTarget(target); return t; } #endregion #region .NET 4.6 or Newer #if (NET_4_6 || NET_STANDARD_2_0) #region Async Instructions /// <summary> /// Returns an async <see cref="Task"/> that waits until the tween is killed or complete. /// It can be used inside an async operation. /// <para>Example usage:</para><code>await myTween.WaitForCompletion();</code> /// </summary> public static async Task AsyncWaitForCompletion(this Tween t) { if (!t.active) { if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); return; } while (t.active && !t.IsComplete()) await Task.Yield(); } /// <summary> /// Returns an async <see cref="Task"/> that waits until the tween is killed or rewinded. /// It can be used inside an async operation. /// <para>Example usage:</para><code>await myTween.AsyncWaitForRewind();</code> /// </summary> public static async Task AsyncWaitForRewind(this Tween t) { if (!t.active) { if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); return; } while (t.active && (!t.playedOnce || t.position * (t.CompletedLoops() + 1) > 0)) await Task.Yield(); } /// <summary> /// Returns an async <see cref="Task"/> that waits until the tween is killed. /// It can be used inside an async operation. /// <para>Example usage:</para><code>await myTween.AsyncWaitForKill();</code> /// </summary> public static async Task AsyncWaitForKill(this Tween t) { if (!t.active) { if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); return; } while (t.active) await Task.Yield(); } /// <summary> /// Returns an async <see cref="Task"/> that waits until the tween is killed or has gone through the given amount of loops. /// It can be used inside an async operation. /// <para>Example usage:</para><code>await myTween.AsyncWaitForElapsedLoops();</code> /// </summary> /// <param name="elapsedLoops">Elapsed loops to wait for</param> public static async Task AsyncWaitForElapsedLoops(this Tween t, int elapsedLoops) { if (!t.active) { if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); return; } while (t.active && t.CompletedLoops() < elapsedLoops) await Task.Yield(); } /// <summary> /// Returns an async <see cref="Task"/> that waits until the tween is killed or started /// (meaning when the tween is set in a playing state the first time, after any eventual delay). /// It can be used inside an async operation. /// <para>Example usage:</para><code>await myTween.AsyncWaitForPosition();</code> /// </summary> /// <param name="position">Position (loops included, delays excluded) to wait for</param> public static async Task AsyncWaitForPosition(this Tween t, float position) { if (!t.active) { if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); return; } while (t.active && t.position * (t.CompletedLoops() + 1) < position) await Task.Yield(); } /// <summary> /// Returns an async <see cref="Task"/> that waits until the tween is killed. /// It can be used inside an async operation. /// <para>Example usage:</para><code>await myTween.AsyncWaitForKill();</code> /// </summary> public static async Task AsyncWaitForStart(this Tween t) { if (!t.active) { if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); return; } while (t.active && !t.playedOnce) await Task.Yield(); } #endregion #endif #endregion #endregion #endif } // █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ // ███ CLASSES █████████████████████████████████████████████████████████████████████████████████████████████████████████ // █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ #if UNITY_5_3_OR_NEWER || UNITY_2017_1_OR_NEWER public static class DOTweenCYInstruction { public class WaitForCompletion : CustomYieldInstruction { public override bool keepWaiting { get { return t.active && !t.IsComplete(); }} readonly Tween t; public WaitForCompletion(Tween tween) { t = tween; } } public class WaitForRewind : CustomYieldInstruction { public override bool keepWaiting { get { return t.active && (!t.playedOnce || t.position * (t.CompletedLoops() + 1) > 0); }} readonly Tween t; public WaitForRewind(Tween tween) { t = tween; } } public class WaitForKill : CustomYieldInstruction { public override bool keepWaiting { get { return t.active; }} readonly Tween t; public WaitForKill(Tween tween) { t = tween; } } public class WaitForElapsedLoops : CustomYieldInstruction { public override bool keepWaiting { get { return t.active && t.CompletedLoops() < elapsedLoops; }} readonly Tween t; readonly int elapsedLoops; public WaitForElapsedLoops(Tween tween, int elapsedLoops) { t = tween; this.elapsedLoops = elapsedLoops; } } public class WaitForPosition : CustomYieldInstruction { public override bool keepWaiting { get { return t.active && t.position * (t.CompletedLoops() + 1) < position; }} readonly Tween t; readonly float position; public WaitForPosition(Tween tween, float position) { t = tween; this.position = position; } } public class WaitForStart : CustomYieldInstruction { public override bool keepWaiting { get { return t.active && !t.playedOnce; }} readonly Tween t; public WaitForStart(Tween tween) { t = tween; } } } #endif }
411
0.911778
1
0.911778
game-dev
MEDIA
0.609605
game-dev,graphics-rendering
0.900825
1
0.900825
Project-Tactics/Project-Tactics
3,484
src/Libs/Resource/ResourceSystem.cpp
#include "ResourceSystem.h" #include "ResourcePack/ResourcePackManager.h" #include <Libs/Utility/Exception.h> #include <Libs/Utility/Log/Log.h> namespace tactics::resource { ResourceSystem::ResourceSystem(FileSystem& fileSystem) : _resourcePackManager(std::make_unique<ResourcePackManager>(fileSystem, *this)) {} ResourceSystem::~ResourceSystem() {} void ResourceSystem::loadPackDefinition(const std::filesystem::path& definitionPath) { _resourcePackManager->loadPackDefinition(definitionPath); } void ResourceSystem::loadPack(const HashId& packName) { _resourcePackManager->loadPack(packName); } void ResourceSystem::unloadPack(const HashId& packName) { _resourcePackManager->unloadPack(packName); } void ResourceSystem::removePack(const HashId& packName) { _resourcePackManager->removePack(packName); } void ResourceSystem::createManualPack(const HashId& packName) { _resourcePackManager->createPack(packName, true); } void ResourceSystem::forEachManager(std::function<void(const BaseResourceManager&)> callback) { for (auto&& [type, manager] : _resourceManagers) { callback(*manager); } } void ResourceSystem::forEachResource(std::function<void(const Pack&, const PackGroup&, const ResourceInfo&)> callback) { _resourcePackManager->forEachPack([&](const Pack& pack) { pack.forEachResource(callback); }); } void ResourceSystem::forEachPack(std::function<void(const Pack&)> callback) { _resourcePackManager->forEachPack(std::move(callback)); } void ResourceSystem::registerManager(std::unique_ptr<BaseResourceManager> resourceManager) { auto type = resourceManager->getType(); if (_resourceManagers.contains(type)) { LOG_ERROR( Log::Resource, "Can't register a new Resource Type Manager for resource of type {}. A manager is already registered.", type); } _resourceManagers.insert({type, std::move(resourceManager)}); } void ResourceSystem::_unregisterManager(std::unique_ptr<BaseResourceManager> resourceManager) { auto itr = _resourceManagers.find(resourceManager->getType()); if (itr == _resourceManagers.end()) { LOG_ERROR(Log::Resource, "Can't unregister a Resource Type Manager for resource of type {}. No manager is registered.", resourceManager->getType()); return; } _resourceManagers.erase(itr); } BaseResourceManager& ResourceSystem::getManager(ResourceType resourceType) const { auto itr = _resourceManagers.find(resourceType); if (itr == _resourceManagers.end()) { TACTICS_EXCEPTION("Can't find manager for resource type: {}", resourceType); } return *itr->second; } BaseResourceManager& ResourceSystem::getManager(ResourceType resourceType) { return *_getManager(resourceType); } std::shared_ptr<BaseResource> ResourceSystem::getResource(ResourceType resourceType, const HashId& name) const { return _getManager(resourceType)->getResource(name); } std::shared_ptr<BaseResource> ResourceSystem::getResource(ResourceType resourceType, ResourceId id) const { return _getManager(resourceType)->getResource(id); } void ResourceSystem::loadExternalResource(const HashId& packName, std::shared_ptr<BaseResource> resource) { _resourcePackManager->loadExternalResource(packName, resource); } void ResourceSystem::_loadExternalResource(const HashId& packName, const HashId& resourceName, ResourceType resourceType, const json& data) { _resourcePackManager->loadExternalResource(packName, resourceName, resourceType, data); } } // namespace tactics::resource
411
0.873105
1
0.873105
game-dev
MEDIA
0.506239
game-dev
0.756809
1
0.756809
ImLegiitXD/Ambient
4,621
src/main/java/net/minecraft/world/biome/BiomeGenTaiga.java
package net.minecraft.world.biome; import java.util.Random; import net.minecraft.block.BlockDirt; import net.minecraft.block.BlockDoublePlant; import net.minecraft.block.BlockTallGrass; import net.minecraft.entity.passive.EntityWolf; import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; import net.minecraft.world.chunk.ChunkPrimer; import net.minecraft.world.gen.feature.WorldGenAbstractTree; import net.minecraft.world.gen.feature.WorldGenBlockBlob; import net.minecraft.world.gen.feature.WorldGenMegaPineTree; import net.minecraft.world.gen.feature.WorldGenTaiga1; import net.minecraft.world.gen.feature.WorldGenTaiga2; import net.minecraft.world.gen.feature.WorldGenTallGrass; import net.minecraft.world.gen.feature.WorldGenerator; public class BiomeGenTaiga extends BiomeGenBase { private static final WorldGenTaiga1 field_150639_aC = new WorldGenTaiga1(); private static final WorldGenTaiga2 field_150640_aD = new WorldGenTaiga2(false); private static final WorldGenMegaPineTree field_150641_aE = new WorldGenMegaPineTree(false, false); private static final WorldGenMegaPineTree field_150642_aF = new WorldGenMegaPineTree(false, true); private static final WorldGenBlockBlob field_150643_aG = new WorldGenBlockBlob(Blocks.mossy_cobblestone, 0); private final int field_150644_aH; public BiomeGenTaiga(int id, int p_i45385_2_) { super(id); this.field_150644_aH = p_i45385_2_; this.spawnableCreatureList.add(new BiomeGenBase.SpawnListEntry(EntityWolf.class, 8, 4, 4)); this.theBiomeDecorator.treesPerChunk = 10; if (p_i45385_2_ != 1 && p_i45385_2_ != 2) { this.theBiomeDecorator.grassPerChunk = 1; this.theBiomeDecorator.mushroomsPerChunk = 1; } else { this.theBiomeDecorator.grassPerChunk = 7; this.theBiomeDecorator.deadBushPerChunk = 1; this.theBiomeDecorator.mushroomsPerChunk = 3; } } public WorldGenAbstractTree genBigTreeChance(Random rand) { return (this.field_150644_aH == 1 || this.field_150644_aH == 2) && rand.nextInt(3) == 0 ? (this.field_150644_aH != 2 && rand.nextInt(13) != 0 ? field_150641_aE : field_150642_aF) : (rand.nextInt(3) == 0 ? field_150639_aC : field_150640_aD); } public WorldGenerator getRandomWorldGenForGrass(Random rand) { return rand.nextInt(5) > 0 ? new WorldGenTallGrass(BlockTallGrass.EnumType.FERN) : new WorldGenTallGrass(BlockTallGrass.EnumType.GRASS); } public void decorate(World worldIn, Random rand, BlockPos pos) { if (this.field_150644_aH == 1 || this.field_150644_aH == 2) { int i = rand.nextInt(3); for (int j = 0; j < i; ++j) { int k = rand.nextInt(16) + 8; int l = rand.nextInt(16) + 8; BlockPos blockpos = worldIn.getHeight(pos.add(k, 0, l)); field_150643_aG.generate(worldIn, rand, blockpos); } } DOUBLE_PLANT_GENERATOR.setPlantType(BlockDoublePlant.EnumPlantType.FERN); for (int i1 = 0; i1 < 7; ++i1) { int j1 = rand.nextInt(16) + 8; int k1 = rand.nextInt(16) + 8; int l1 = rand.nextInt(worldIn.getHeight(pos.add(j1, 0, k1)).getY() + 32); DOUBLE_PLANT_GENERATOR.generate(worldIn, rand, pos.add(j1, l1, k1)); } super.decorate(worldIn, rand, pos); } public void genTerrainBlocks(World worldIn, Random rand, ChunkPrimer chunkPrimerIn, int x, int z, double noiseVal) { if (this.field_150644_aH == 1 || this.field_150644_aH == 2) { this.topBlock = Blocks.grass.getDefaultState(); this.fillerBlock = Blocks.dirt.getDefaultState(); if (noiseVal > 1.75D) { this.topBlock = Blocks.dirt.getDefaultState().withProperty(BlockDirt.VARIANT, BlockDirt.DirtType.COARSE_DIRT); } else if (noiseVal > -0.95D) { this.topBlock = Blocks.dirt.getDefaultState().withProperty(BlockDirt.VARIANT, BlockDirt.DirtType.PODZOL); } } this.generateBiomeTerrain(worldIn, rand, chunkPrimerIn, x, z, noiseVal); } protected BiomeGenBase createMutatedBiome(int p_180277_1_) { return this.biomeID == BiomeGenBase.megaTaiga.biomeID ? (new BiomeGenTaiga(p_180277_1_, 2)).func_150557_a(5858897, true).setBiomeName("Mega Spruce Taiga").setFillerBlockMetadata(5159473).setTemperatureRainfall(0.25F, 0.8F).setHeight(new BiomeGenBase.Height(this.minHeight, this.maxHeight)) : super.createMutatedBiome(p_180277_1_); } }
411
0.730661
1
0.730661
game-dev
MEDIA
0.988886
game-dev
0.504349
1
0.504349
SwitchGDX/switch-gdx
1,908
switch-gdx/res/switchgdx/bullet/extras/InverseDynamics/MultiBodyTreeCreator.hpp
#ifndef MULTI_BODY_TREE_CREATOR_HPP_ #define MULTI_BODY_TREE_CREATOR_HPP_ #include <string> #include <vector> #include "BulletInverseDynamics/IDConfig.hpp" #include "BulletInverseDynamics/IDMath.hpp" #include "BulletInverseDynamics/MultiBodyTree.hpp" #include "MultiBodyNameMap.hpp" namespace btInverseDynamics { /// Interface class for initializing a MultiBodyTree instance. /// Data to be provided is modeled on the URDF specification. /// The user can derive from this class in order to programmatically /// initialize a system. class MultiBodyTreeCreator { public: /// the dtor virtual ~MultiBodyTreeCreator() {} /// Get the number of bodies in the system /// @param num_bodies write number of bodies here /// @return 0 on success, -1 on error virtual int getNumBodies(int* num_bodies) const = 0; /// Interface for accessing link mass properties. /// For detailed description of data, @sa MultiBodyTree::addBody /// \copydoc MultiBodyTree::addBody virtual int getBody(const int body_index, int* parent_index, JointType* joint_type, vec3* parent_r_parent_body_ref, mat33* body_T_parent_ref, vec3* body_axis_of_motion, idScalar* mass, vec3* body_r_body_com, mat33* body_I_body, int* user_int, void** user_ptr) const = 0; /// @return a pointer to a name mapping utility class, or 0x0 if not available virtual const MultiBodyNameMap* getNameMap() const {return 0x0;} }; /// Create a multibody object. /// @param creator an object implementing the MultiBodyTreeCreator interface /// that returns data defining the system /// @return A pointer to an allocated multibodytree instance, or /// 0x0 if an error occured. MultiBodyTree* CreateMultiBodyTree(const MultiBodyTreeCreator& creator); } // does urdf have gravity direction ?? #endif // MULTI_BODY_TREE_CREATOR_HPP_
411
0.781553
1
0.781553
game-dev
MEDIA
0.849189
game-dev
0.567579
1
0.567579
microsoft/sqltoolsservice
13,062
test/Microsoft.SqlTools.ServiceLayer.UnitTests/ShowPlan/ShowPlanTests.cs
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Reflection; using NUnit.Framework; using Microsoft.SqlTools.ServiceLayer.ExecutionPlan; using Microsoft.SqlTools.ServiceLayer.ExecutionPlan.Contracts; using Microsoft.SqlTools.ServiceLayer.ExecutionPlan.ShowPlan; using Microsoft.SqlTools.ServiceLayer.ExecutionPlan.ShowPlan.Comparison; namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ShowPlan { public class ShowPlanXMLTests { private string queryPlanFileText; [Test] public void ParseXMLFileReturnsValidShowPlanGraph() { ReadFile(".ShowPlan.TestShowPlan.xml"); var showPlanGraphs = ExecutionPlanGraphUtils.CreateShowPlanGraph(queryPlanFileText, "testFile.sql"); Assert.AreEqual(1, showPlanGraphs.Count, "exactly one show plan graph should be returned"); Assert.NotNull(showPlanGraphs[0], "graph should not be null"); Assert.NotNull(showPlanGraphs[0].Root, "graph should have a root"); } [Test] public void CompareShowPlan_CreateSkeleton() { ReadFile(".ShowPlan.TestShowPlan.xml"); var graphs = ShowPlanGraph.ParseShowPlanXML(this.queryPlanFileText, ShowPlanType.Unknown); var rootNode = graphs[0].Root; Assert.NotNull(rootNode, "graph should have a root"); var skeletonManager = new SkeletonManager(); var skeletonNode = skeletonManager.CreateSkeleton(rootNode); Assert.NotNull(skeletonNode, "skeletonNode should not be null"); } [Test] public void CompareShowPlan_CreateSkeletonUsingDefaultConfiguredNode() { var graph = new ShowPlanGraph() { Root = null, Description = new Description() }; var context = new NodeBuilderContext(graph, ShowPlanType.Unknown, null); var node = new Node(default, context); var skeletonManager = new SkeletonManager(); var skeletonNode = skeletonManager.CreateSkeleton(node); Assert.NotNull(skeletonNode, "skeletonNode should not be null"); } [Test] public void CompareShowPlan_DuplicateSkeletons() { ReadFile(".ShowPlan.TestShowPlan.xml"); var graphs = ShowPlanGraph.ParseShowPlanXML(this.queryPlanFileText, ShowPlanType.Unknown); var rootNode = graphs[0].Root; var skeletonManager = new SkeletonManager(); var skeletonNode = skeletonManager.CreateSkeleton(rootNode); var skeletonNode2 = skeletonManager.CreateSkeleton(rootNode); var skeletonCompareResult = skeletonManager.AreSkeletonsEquivalent(skeletonNode, skeletonNode2, ignoreDatabaseName: true); Assert.IsTrue(skeletonCompareResult); } [Test] public void CompareShowPlan_TwoDefaultConfiguredSkeletons() { var graph = new ShowPlanGraph() { Root = null, Description = new Description() }; var context = new NodeBuilderContext(graph, ShowPlanType.Unknown, null); var firstRoot = new Node(default, context); var secondRoot = new Node(default, context); var skeletonManager = new SkeletonManager(); var firstSkeletonNode = skeletonManager.CreateSkeleton(firstRoot); var secondSkeletonNode = skeletonManager.CreateSkeleton(secondRoot); var skeletonCompareResult = skeletonManager.AreSkeletonsEquivalent(firstSkeletonNode, secondSkeletonNode, ignoreDatabaseName: true); Assert.IsTrue(skeletonCompareResult, "The two compared skeleton nodes should be equivalent"); } [Test] public void CompareShowPlan_ComparingSkeletonAgainstNull() { ReadFile(".ShowPlan.TestShowPlan.xml"); var graphs = ShowPlanGraph.ParseShowPlanXML(this.queryPlanFileText, ShowPlanType.Unknown); var rootNode = graphs[0].Root; var skeletonManager = new SkeletonManager(); var skeletonNode = skeletonManager.CreateSkeleton(rootNode); SkeletonNode skeletonNode2 = null; var skeletonCompareResult = skeletonManager.AreSkeletonsEquivalent(skeletonNode, skeletonNode2, ignoreDatabaseName: true); Assert.IsFalse(skeletonCompareResult); } [Test] public void CompareShowPlan_DifferentSkeletonChildCount() { ReadFile(".ShowPlan.TestShowPlan.xml"); var graphs = ShowPlanGraph.ParseShowPlanXML(this.queryPlanFileText, ShowPlanType.Unknown); var rootNode = graphs[0].Root; var skeletonManager = new SkeletonManager(); var skeletonNode = skeletonManager.CreateSkeleton(rootNode); var skeletonNode2 = skeletonManager.CreateSkeleton(rootNode); skeletonNode2.Children.RemoveAt(skeletonNode2.Children.Count - 1); var skeletonCompareResult = skeletonManager.AreSkeletonsEquivalent(skeletonNode, skeletonNode2, ignoreDatabaseName: true); Assert.IsFalse(skeletonCompareResult); } [Test] public void CompareShowPlan_ColorMatchingSectionsWithEquivalentSkeletons() { ReadFile(".ShowPlan.TestShowPlan.xml"); var graphs = ShowPlanGraph.ParseShowPlanXML(this.queryPlanFileText, ShowPlanType.Unknown); var rootNode = graphs[0].Root; var skeletonManager = new SkeletonManager(); var skeletonNode = skeletonManager.CreateSkeleton(rootNode); var skeletonNode2 = skeletonManager.CreateSkeleton(rootNode); Assert.IsFalse(skeletonNode.HasMatch); Assert.IsFalse(skeletonNode2.HasMatch); Assert.Zero(skeletonNode.MatchingNodes.Count); Assert.Zero(skeletonNode2.MatchingNodes.Count); skeletonManager.ColorMatchingSections(skeletonNode, skeletonNode2, ignoreDatabaseName: true); Assert.IsTrue(skeletonNode.HasMatch); Assert.IsTrue(skeletonNode2.HasMatch); Assert.AreEqual(1, skeletonNode.MatchingNodes.Count); Assert.AreEqual(1, skeletonNode2.MatchingNodes.Count); } [Test] public void CompareShowPlan_ColorMatchingSectionsWithNullAndNonNullSkeleton() { ReadFile(".ShowPlan.TestShowPlan.xml"); var graphs = ShowPlanGraph.ParseShowPlanXML(this.queryPlanFileText, ShowPlanType.Unknown); var rootNode = graphs[0].Root; var skeletonManager = new SkeletonManager(); SkeletonNode nullSkeletonNode = null; var skeletonNode2 = skeletonManager.CreateSkeleton(rootNode); skeletonManager.ColorMatchingSections(nullSkeletonNode, skeletonNode2, ignoreDatabaseName: true); Assert.IsNull(nullSkeletonNode); Assert.IsFalse(skeletonNode2.HasMatch); Assert.Zero(skeletonNode2.MatchingNodes.Count); } [Test] public void CompareShowPlan_ColorMatchingSectionsWithTwoNullSKeletons() { var skeletonManager = new SkeletonManager(); SkeletonNode skeletonNode = null; SkeletonNode skeletonNode2 = null; skeletonManager.ColorMatchingSections(skeletonNode, skeletonNode2, ignoreDatabaseName: true); Assert.IsNull(skeletonNode); Assert.IsNull(skeletonNode2); } [Test] public void CompareShowPlan_ColorMatchingSectionsWithNonNullAndNullSkeleton() { ReadFile(".ShowPlan.TestShowPlan.xml"); var graphs = ShowPlanGraph.ParseShowPlanXML(this.queryPlanFileText, ShowPlanType.Unknown); var rootNode = graphs[0].Root; var skeletonManager = new SkeletonManager(); var skeletonNode = skeletonManager.CreateSkeleton(rootNode); SkeletonNode nullSkeletonNode = null; skeletonManager.ColorMatchingSections(skeletonNode, nullSkeletonNode, ignoreDatabaseName: true); Assert.IsFalse(skeletonNode.HasMatch); Assert.Zero(skeletonNode.MatchingNodes.Count); Assert.IsNull(nullSkeletonNode); } [Test] public void CompareShowPlan_ColorMatchingSectionsWithDifferentChildCount() { ReadFile(".ShowPlan.TestShowPlan.xml"); var graphs = ShowPlanGraph.ParseShowPlanXML(this.queryPlanFileText, ShowPlanType.Unknown); var rootNode = graphs[0].Root; var skeletonManager = new SkeletonManager(); var skeletonNode = skeletonManager.CreateSkeleton(rootNode); var skeletonNode2 = skeletonManager.CreateSkeleton(rootNode); skeletonNode2.Children.RemoveAt(skeletonNode2.Children.Count - 1); Assert.IsFalse(skeletonNode.Children[0].HasMatch); Assert.IsFalse(skeletonNode2.Children[0].HasMatch); Assert.Zero(skeletonNode.Children[0].MatchingNodes.Count); Assert.Zero(skeletonNode2.Children[0].MatchingNodes.Count); skeletonManager.ColorMatchingSections(skeletonNode, skeletonNode2, ignoreDatabaseName: true); Assert.IsTrue(skeletonNode.Children[0].HasMatch); Assert.IsTrue(skeletonNode2.Children[0].HasMatch); Assert.AreEqual(1, skeletonNode.Children[0].MatchingNodes.Count); Assert.AreEqual(1, skeletonNode2.Children[0].MatchingNodes.Count); } [Test] public void CompareShowPlan_FindNextNonIgnoreNode() { ReadFile(".ShowPlan.TestShowPlan.xml"); var graphs = ShowPlanGraph.ParseShowPlanXML(this.queryPlanFileText, ShowPlanType.Unknown); var rootNode = graphs[0].Root; var skeletonManager = new SkeletonManager(); var result = skeletonManager.FindNextNonIgnoreNode(rootNode); Assert.NotNull(result); Assert.AreEqual("InnerJoin", result.LogicalOpUnlocName); } [Test] public void CompareShowPlan_FindNextNonIgnoreNodeWithChildlessRoot() { ReadFile(".ShowPlan.TestShowPlan.xml"); var graphs = ShowPlanGraph.ParseShowPlanXML(this.queryPlanFileText, ShowPlanType.Unknown); var rootNode = graphs[0].Root; for (int childIndex = 0; childIndex < rootNode.Children.Count; ++childIndex) { rootNode.Children.RemoveAt(0); } var skeletonManager = new SkeletonManager(); var result = skeletonManager.FindNextNonIgnoreNode(rootNode); Assert.IsNull(result); } [Test] public void CompareShowPlan_FindNextNonIgnoreNodeWithNullNode() { Node rootNode = null; var skeletonManager = new SkeletonManager(); var result = skeletonManager.FindNextNonIgnoreNode(rootNode); Assert.IsNull(result); } [Test] public void ParsingNestedProperties() { ReadFile(".ShowPlan.TestShowPlan.xml"); string[] commonNestedPropertiesNames = { "MemoryGrantInfo", "OptimizerHardwareDependentProperties" }; var showPlanGraphs = ExecutionPlanGraphUtils.CreateShowPlanGraph(queryPlanFileText, "testFile.sql"); ExecutionPlanNode rootNode = showPlanGraphs[0].Root; rootNode.Properties.ForEach(p => { if (Array.FindIndex(commonNestedPropertiesNames, i => i.Equals(p.Name)) != -1 && (NestedExecutionPlanGraphProperty)p != null) { Assert.NotZero(((NestedExecutionPlanGraphProperty)p).Value.Count); } }); } [Test] public void ParseXMLFileWithRecommendations() { //The first graph in this execution plan has 3 recommendations ReadFile(".ShowPlan.TestShowPlanRecommendations.xml"); string[] commonNestedPropertiesNames = { "MemoryGrantInfo", "OptimizerHardwareDependentProperties" }; var showPlanGraphs = ExecutionPlanGraphUtils.CreateShowPlanGraph(queryPlanFileText, "testFile.sql"); List<ExecutionPlanRecommendation> rootNode = showPlanGraphs[0].Recommendations; Assert.AreEqual(3, rootNode.Count, "3 recommendations should be returned by the showplan parser"); } private void ReadFile(string fileName) { Assembly assembly = Assembly.GetAssembly(typeof(ShowPlanXMLTests)); Stream scriptStream = assembly.GetManifestResourceStream(assembly.GetName().Name + fileName); StreamReader reader = new StreamReader(scriptStream); queryPlanFileText = reader.ReadToEnd(); } } }
411
0.70663
1
0.70663
game-dev
MEDIA
0.803887
game-dev
0.508565
1
0.508565
KSP-RO/RP-1
3,143
Source/CC_RP0/Parameter/AvionicsCheckVesselParam.cs
using ContractConfigurator.Parameters; namespace ContractConfigurator.RP0 { public class AvionicsCheckParameter : VesselParameter { protected bool parameterIsSatisified { get; set; } = true; protected bool controlHasLapsed { get; set; } protected bool continuousControlRequired { get; set; } public AvionicsCheckParameter() : base(null) { } public AvionicsCheckParameter(string title, bool continuousControlRequired) : base(title) { this.continuousControlRequired = continuousControlRequired; this.title = GetParameterTitle(); } protected override void OnParameterSave(ConfigNode node) { base.OnParameterSave(node); // Save parameter options on a per-vessel basis node.AddValue("continuousControlRequired", continuousControlRequired); } protected override void OnParameterLoad(ConfigNode node) { base.OnParameterLoad(node); // Save parameter options on a per-vessel basis continuousControlRequired = ConfigNodeUtil.ParseValue<bool>(node, "continuousControlRequired"); } protected override void OnRegister() { base.OnRegister(); // We will only check the status of the parameter when input locks have changed GameEvents.onInputLocksModified.Add(OnInputLocksModified); } protected override void OnUnregister() { base.OnUnregister(); GameEvents.onInputLocksModified.Remove(OnInputLocksModified); } protected override string GetParameterTitle() { // Title will change to reflect the state of the parameter, with special considerations if we // need the user to not lose control at all during flight return continuousControlRequired ? controlHasLapsed ? $"Maintain sufficient avionics (failed, control was lost)" : $"Maintain sufficient avionics (do not lose control)" : $"Have sufficient avionics for control"; } private void OnInputLocksModified(GameEvents.FromToAction<ControlTypes, ControlTypes> data) { // Detect if a control lock is active bool controlIsLocked = InputLockManager.GetControlLock("RP0ControlLocker") != 0; // Keeps track if we've ever lost control controlHasLapsed |= controlIsLocked; // Differing logic depending on parameter properties parameterIsSatisified = continuousControlRequired ? !controlHasLapsed && !controlIsLocked : !controlIsLocked; // Refresh title in contracts screen in case we've had a lapse of control with continousControlRequired true GetTitle(); // Have CC re-evaluate the parameter state (will call VesselMeetsCondition() internally) CheckVessel(FlightGlobals.ActiveVessel); } protected override bool VesselMeetsCondition(Vessel vessel) { return parameterIsSatisified; } } }
411
0.897391
1
0.897391
game-dev
MEDIA
0.924148
game-dev
0.728469
1
0.728469
elBukkit/MagicPlugin
1,044
Magic/src/main/java/com/elmakers/mine/bukkit/protection/AJParkourManager.java
package com.elmakers.mine.bukkit.protection; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import com.elmakers.mine.bukkit.api.magic.Mage; import com.elmakers.mine.bukkit.api.magic.MageController; import us.ajg0702.parkour.api.events.PrePlayerStartParkourEvent; public class AJParkourManager implements Listener { private final MageController controller; public AJParkourManager(MageController controller) { this.controller = controller; controller.getLogger().info("ajParkour found, wands will close when entering parkour"); controller.getPlugin().getServer().getPluginManager().registerEvents(this, controller.getPlugin()); } @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH) public void onStartParkour(PrePlayerStartParkourEvent event) { Player player = event.getPlayer(); Mage mage = controller.getRegisteredMage(player); mage.deactivate(); } }
411
0.774433
1
0.774433
game-dev
MEDIA
0.843575
game-dev
0.71957
1
0.71957
Pokabbie/pokeemerald-rogue
49,434
src/battle_pike.c
#include "global.h" #include "battle_pike.h" #include "event_data.h" #include "frontier_util.h" #include "fieldmap.h" #include "save.h" #include "battle.h" #include "random.h" #include "task.h" #include "battle_tower.h" #include "party_menu.h" #include "malloc.h" #include "palette.h" #include "script.h" #include "battle_setup.h" #include "constants/event_objects.h" #include "constants/battle_frontier.h" #include "constants/frontier_util.h" #include "constants/abilities.h" #include "constants/layouts.h" #include "constants/rgb.h" #include "constants/trainers.h" #include "constants/moves.h" #include "constants/party_menu.h" #include "constants/battle_pike.h" #include "rogue_baked.h" struct PikeRoomNPC { u16 graphicsId; u8 speechId1; u8 speechId2; u8 speechId3; }; struct PikeWildMon { u16 species; u8 levelDelta; u16 moves[MAX_MON_MOVES]; }; // IWRAM bss static u8 sRoomType; static u8 sStatusMon; static bool8 sInWildMonRoom; static u32 sStatusFlags; static u8 sNpcId; // This file's functions. static void SetRoomType(void); static void GetBattlePikeData(void); static void SetBattlePikeData(void); static void IsNextRoomFinal(void); static void SetupRoomObjectEvents(void); static void GetRoomType(void); static void SetInWildMonRoom(void); static void ClearInWildMonRoom(void); static void SavePikeChallenge(void); static void PikeDummy1(void); static void PikeDummy2(void); static void GetRoomInflictedStatus(void); static void GetRoomInflictedStatusMon(void); static void HealOneOrTwoMons(void); static void BufferNPCMessage(void); static void StatusInflictionScreenFlash(void); static void GetInBattlePike(void); static void SetHintedRoom(void); static void GetHintedRoomIndex(void); static void GetRoomTypeHint(void); static void ClearPikeTrainerIds(void); static void BufferTrainerIntro(void); static void GetCurrentRoomPikeQueenFightType(void); static void HealSomeMonsBeforePikeQueen(void); static void SetHealingroomTypesDisabled(void); static void IsPartyFullHealed(void); static void SaveMonHeldItems(void); static void RestoreMonHeldItems(void); static void InitPikeChallenge(void); static u8 GetNextRoomType(void); static void PrepareOneTrainer(bool8 difficult); static u16 GetNPCRoomGraphicsId(void); static void PrepareTwoTrainers(void); static void TryHealMons(u8 healCount); static void Task_DoStatusInflictionScreenFlash(u8 taskId); static bool8 AtLeastTwoAliveMons(void); static u8 SpeciesToPikeMonId(u16 species); static bool8 CanEncounterWildMon(u8 monLevel); static u8 GetPikeQueenFightType(u8); static bool8 StatusInflictionFadeOut(struct Task *task); static bool8 StatusInflictionFadeIn(struct Task *task); // Const rom data. static const struct PikeWildMon sLvl50_Mons1[] = { { .species = SPECIES_SEVIPER, .levelDelta = 4, .moves = {MOVE_TOXIC, MOVE_GLARE, MOVE_BODY_SLAM, MOVE_SLUDGE_BOMB} }, { .species = SPECIES_MILOTIC, .levelDelta = 4, .moves = {MOVE_TOXIC, MOVE_HYPNOSIS, MOVE_BODY_SLAM, MOVE_SURF} }, { .species = SPECIES_DUSCLOPS, .levelDelta = 5, .moves = {MOVE_WILL_O_WISP, MOVE_MEAN_LOOK, MOVE_TOXIC, MOVE_SHADOW_PUNCH} } }; static const struct PikeWildMon sLvl50_Mons2[] = { { .species = SPECIES_SEVIPER, .levelDelta = 4, .moves = {MOVE_TOXIC, MOVE_GLARE, MOVE_BODY_SLAM, MOVE_SLUDGE_BOMB} }, { .species = SPECIES_MILOTIC, .levelDelta = 4, .moves = {MOVE_TOXIC, MOVE_HYPNOSIS, MOVE_BODY_SLAM, MOVE_SURF} }, { .species = SPECIES_ELECTRODE, .levelDelta = 5, .moves = {MOVE_EXPLOSION, MOVE_SELF_DESTRUCT, MOVE_THUNDER, MOVE_TOXIC} } }; static const struct PikeWildMon sLvl50_Mons3[] = { { .species = SPECIES_SEVIPER, .levelDelta = 4, .moves = {MOVE_TOXIC, MOVE_GLARE, MOVE_BODY_SLAM, MOVE_SLUDGE_BOMB} }, { .species = SPECIES_MILOTIC, .levelDelta = 4, .moves = {MOVE_TOXIC, MOVE_HYPNOSIS, MOVE_BODY_SLAM, MOVE_SURF} }, { .species = SPECIES_BRELOOM, .levelDelta = 5, .moves = {MOVE_SPORE, MOVE_STUN_SPORE, MOVE_POISON_POWDER, MOVE_HIDDEN_POWER} } }; static const struct PikeWildMon sLvl50_Mons4[] = { { .species = SPECIES_SEVIPER, .levelDelta = 4, .moves = {MOVE_TOXIC, MOVE_GLARE, MOVE_BODY_SLAM, MOVE_SLUDGE_BOMB} }, { .species = SPECIES_MILOTIC, .levelDelta = 4, .moves = {MOVE_TOXIC, MOVE_HYPNOSIS, MOVE_BODY_SLAM, MOVE_SURF} }, { .species = SPECIES_WOBBUFFET, .levelDelta = 5, .moves = {MOVE_COUNTER, MOVE_MIRROR_COAT, MOVE_SAFEGUARD, MOVE_DESTINY_BOND} } }; static const struct PikeWildMon *const sLvl50Mons[] = { sLvl50_Mons1, sLvl50_Mons2, sLvl50_Mons3, sLvl50_Mons4 }; static const struct PikeWildMon sLvlOpen_Mons1[] = { { .species = SPECIES_SEVIPER, .levelDelta = 4, .moves = {MOVE_TOXIC, MOVE_GLARE, MOVE_POISON_FANG, MOVE_SLUDGE_BOMB} }, { .species = SPECIES_MILOTIC, .levelDelta = 4, .moves = {MOVE_TOXIC, MOVE_HYPNOSIS, MOVE_BODY_SLAM, MOVE_ICE_BEAM} }, { .species = SPECIES_DUSCLOPS, .levelDelta = 5, .moves = {MOVE_WILL_O_WISP, MOVE_MEAN_LOOK, MOVE_TOXIC, MOVE_ICE_BEAM} } }; static const struct PikeWildMon sLvlOpen_Mons2[] = { { .species = SPECIES_SEVIPER, .levelDelta = 4, .moves = {MOVE_TOXIC, MOVE_GLARE, MOVE_POISON_FANG, MOVE_SLUDGE_BOMB} }, { .species = SPECIES_MILOTIC, .levelDelta = 4, .moves = {MOVE_TOXIC, MOVE_HYPNOSIS, MOVE_BODY_SLAM, MOVE_ICE_BEAM} }, { .species = SPECIES_ELECTRODE, .levelDelta = 5, .moves = {MOVE_EXPLOSION, MOVE_SELF_DESTRUCT, MOVE_THUNDER, MOVE_TOXIC} } }; static const struct PikeWildMon sLvlOpen_Mons3[] = { { .species = SPECIES_SEVIPER, .levelDelta = 4, .moves = {MOVE_TOXIC, MOVE_GLARE, MOVE_POISON_FANG, MOVE_SLUDGE_BOMB} }, { .species = SPECIES_MILOTIC, .levelDelta = 4, .moves = {MOVE_TOXIC, MOVE_HYPNOSIS, MOVE_BODY_SLAM, MOVE_ICE_BEAM} }, { .species = SPECIES_BRELOOM, .levelDelta = 5, .moves = {MOVE_SPORE, MOVE_STUN_SPORE, MOVE_POISON_POWDER, MOVE_HIDDEN_POWER} } }; static const struct PikeWildMon sLvlOpen_Mons4[] = { { .species = SPECIES_SEVIPER, .levelDelta = 4, .moves = {MOVE_TOXIC, MOVE_GLARE, MOVE_POISON_FANG, MOVE_SLUDGE_BOMB} }, { .species = SPECIES_MILOTIC, .levelDelta = 4, .moves = {MOVE_TOXIC, MOVE_HYPNOSIS, MOVE_BODY_SLAM, MOVE_ICE_BEAM} }, { .species = SPECIES_WOBBUFFET, .levelDelta = 5, .moves = {MOVE_COUNTER, MOVE_MIRROR_COAT, MOVE_SAFEGUARD, MOVE_ENCORE} } }; static const struct PikeWildMon *const sLvlOpenMons[] = { sLvlOpen_Mons1, sLvlOpen_Mons2, sLvlOpen_Mons3, sLvlOpen_Mons4 }; static const struct PikeWildMon *const *const sWildMons[2] = { [FRONTIER_LVL_50] = sLvl50Mons, [FRONTIER_LVL_OPEN] = sLvlOpenMons }; static const struct PikeRoomNPC sNPCTable[] = { { .graphicsId = OBJ_EVENT_GFX_POKEFAN_F, .speechId1 = 3, .speechId2 = 5, .speechId3 = 6 }, { .graphicsId = OBJ_EVENT_GFX_NINJA_BOY, .speechId1 = 13, .speechId2 = 32, .speechId3 = 37 }, { .graphicsId = OBJ_EVENT_GFX_FAT_MAN, .speechId1 = 8, .speechId2 = 11, .speechId3 = 12 }, { .graphicsId = OBJ_EVENT_GFX_BUG_CATCHER, .speechId1 = 34, .speechId2 = 30, .speechId3 = 33 }, { .graphicsId = OBJ_EVENT_GFX_EXPERT_M, .speechId1 = 0, .speechId2 = 0, .speechId3 = 0 }, { .graphicsId = OBJ_EVENT_GFX_OLD_WOMAN, .speechId1 = 1, .speechId2 = 1, .speechId3 = 1 }, { .graphicsId = OBJ_EVENT_GFX_BLACK_BELT, .speechId1 = 22, .speechId2 = 23, .speechId3 = 27 }, { .graphicsId = OBJ_EVENT_GFX_HIKER, .speechId1 = 8, .speechId2 = 22, .speechId3 = 31 }, { .graphicsId = OBJ_EVENT_GFX_GIRL_3, .speechId1 = 13, .speechId2 = 39, .speechId3 = 21 }, { .graphicsId = OBJ_EVENT_GFX_WOMAN_2, .speechId1 = 2, .speechId2 = 4, .speechId3 = 17 }, { .graphicsId = OBJ_EVENT_GFX_CYCLING_TRIATHLETE_M, .speechId1 = 30, .speechId2 = 20, .speechId3 = 36 }, { .graphicsId = OBJ_EVENT_GFX_MAN_5, .speechId1 = 28, .speechId2 = 34, .speechId3 = 25 }, { .graphicsId = OBJ_EVENT_GFX_SCHOOL_KID_M, .speechId1 = 23, .speechId2 = 38, .speechId3 = 26 }, { .graphicsId = OBJ_EVENT_GFX_FISHERMAN, .speechId1 = 23, .speechId2 = 30, .speechId3 = 11 }, { .graphicsId = OBJ_EVENT_GFX_LASS, .speechId1 = 15, .speechId2 = 19, .speechId3 = 14 }, { .graphicsId = OBJ_EVENT_GFX_MANIAC, .speechId1 = 2, .speechId2 = 29, .speechId3 = 26 }, { .graphicsId = OBJ_EVENT_GFX_RUNNING_TRIATHLETE_M, .speechId1 = 37, .speechId2 = 12, .speechId3 = 32 }, { .graphicsId = OBJ_EVENT_GFX_MAN_3, .speechId1 = 24, .speechId2 = 23, .speechId3 = 38 }, { .graphicsId = OBJ_EVENT_GFX_WOMAN_3, .speechId1 = 5, .speechId2 = 22, .speechId3 = 4 }, { .graphicsId = OBJ_EVENT_GFX_LITTLE_BOY, .speechId1 = 41, .speechId2 = 37, .speechId3 = 35 }, { .graphicsId = OBJ_EVENT_GFX_TUBER_F, .speechId1 = 39, .speechId2 = 14, .speechId3 = 13 }, { .graphicsId = OBJ_EVENT_GFX_GENTLEMAN, .speechId1 = 10, .speechId2 = 7, .speechId3 = 9 }, { .graphicsId = OBJ_EVENT_GFX_LITTLE_GIRL, .speechId1 = 40, .speechId2 = 20, .speechId3 = 16 }, { .graphicsId = OBJ_EVENT_GFX_RUNNING_TRIATHLETE_F, .speechId1 = 18, .speechId2 = 13, .speechId3 = 21 }, { .graphicsId = OBJ_EVENT_GFX_MAN_1, .speechId1 = 22, .speechId2 = 31, .speechId3 = 27 } }; static const u16 sNPCSpeeches[][EASY_CHAT_BATTLE_WORDS_COUNT] = { {EC_WORD_I_AM, EC_WORD_LOST, EC_WORD_I, EC_WORD_NEED, EC_WORD_A, EC_MOVE2(HELPING_HAND)}, {EC_WORD_I_VE, EC_WORD_NO, EC_WORD_SENSE, EC_WORD_OF, EC_WORD_WHERE, EC_WORD_I_AM}, {EC_WORD_WHAT, EC_WORD_SHOULD, EC_WORD_I, EC_WORD_DO, EC_WORD_NOW, EC_WORD_QUES}, {EC_WORD_THIS, EC_WORD_IS, EC_WORD_TOO, EC_WORD_EXCITING, EC_WORD_FOR, EC_WORD_ME}, {EC_WORD_DID, EC_WORD_YOU, EC_WORD_MAKE, EC_WORD_A, EC_WORD_MISTAKE, EC_WORD_QUES}, {EC_WORD_IT_S, EC_WORD_MEAN, EC_WORD_AND, EC_WORD_AWFUL, EC_WORD_IN, EC_WORD_HERE}, {EC_WORD_I_AM, EC_WORD_SO, EC_WORD_TIRED, EC_WORD_OF, EC_WORD_THIS, EC_WORD_PLACE}, {EC_WORD_I, EC_WORD_QUITE, EC_WORD_ENJOY, EC_WORD_THIS, EC_WORD_CHALLENGE, EC_EMPTY_WORD}, {EC_WORD_LOOK, EC_WORD_AT, EC_WORD_HOW, EC_WORD_I, EC_MOVE2(TACKLE), EC_WORD_THIS}, {EC_WORD_READY, EC_WORD_TO, EC_WORD_GIVE_UP, EC_WORD_YET, EC_WORD_QUES, EC_EMPTY_WORD}, {EC_WORD_OH, EC_WORD_NO, EC_WORD_WHO, EC_WORD_ARE, EC_WORD_YOU, EC_WORD_QUES}, {EC_WORD_I_VE, EC_WORD_BEEN, EC_WORD_WANDERING, EC_WORD_ABOUT, EC_WORD_FOREVER, EC_WORD_ELLIPSIS}, {EC_WORD_I, EC_WORD_THINK, EC_WORD_I, EC_WORD_WILL, EC_WORD_GIVE_UP, EC_EMPTY_WORD}, {EC_WORD_WHAT, EC_WORD_SHOULD, EC_WORD_I, EC_WORD_DO, EC_WORD_NEXT, EC_WORD_QUES}, {EC_WORD_I, EC_WORD_CAN_WIN, EC_WORD_WITH, EC_WORD_MY, EC_MOVE(SHEER_COLD), EC_WORD_GENIUS}, {EC_WORD_WON_T, EC_WORD_SOMEONE, EC_WORD_COOL, EC_WORD_SHOW, EC_WORD_UP, EC_WORD_QUES}, {EC_WORD_BATTLE, EC_WORD_GAME, EC_WORD_IS, EC_WORD_AWESOME, EC_WORD_EXCL, EC_EMPTY_WORD}, {EC_WORD_I, EC_WORD_CAN_T, EC_WORD_TAKE, EC_WORD_THIS, EC_WORD_ANY, EC_WORD_MORE}, {EC_WORD_I, EC_WORD_DON_T, EC_WORD_KNOW, EC_WORD_IF, EC_WORD_IT_S, EC_WORD_OKAY}, {EC_WORD_OH, EC_WORD_NO, EC_WORD_EXCL, EC_WORD_NOT, EC_WORD_ANOTHER, EC_WORD_TRAINER}, {EC_WORD_IT, EC_WORD_HAS, EC_WORD_TO, EC_WORD_BE, EC_WORD_LEFT, EC_WORD_NEXT}, {EC_WORD_IT, EC_WORD_MUST_BE, EC_WORD_OVER, EC_WORD_SOON, EC_WORD_RIGHT, EC_WORD_QUES}, {EC_WORD_THIS, EC_WORD_IS, EC_WORD_TOTALLY, EC_WORD_EASY, EC_WORD_ISN_T_IT_QUES, EC_EMPTY_WORD}, {EC_WORD_I_AM, EC_WORD_GOING, EC_WORD_TO, EC_WORD_POWER, EC_WORD_ON, EC_EMPTY_WORD}, {EC_WORD_THERE, EC_WORD_IS, EC_WORD_NO, EC_WORD_GIVE_UP, EC_WORD_IN, EC_WORD_ME}, {EC_WORD_I_AM, EC_WORD_NOT, EC_WORD_GOING, EC_WORD_TO, EC_WORD_MAKE, EC_WORD_IT}, {EC_WORD_GO, EC_WORD_ON, EC_WORD_I, EC_WORD_CAN_T, EC_WORD_ANY, EC_WORD_MORE}, {EC_WORD_A, EC_WORD_TRAINER, EC_WORD_AFTER, EC_WORD_ANOTHER, EC_WORD_ELLIPSIS, EC_EMPTY_WORD}, {EC_WORD_DO, EC_WORD_YOU, EC_WORD_LIKE, EC_WORD_STEEL, EC_WORD_POKEMON, EC_WORD_QUES}, {EC_WORD_EVERY, EC_WORD_TRAINER, EC_WORD_HERE, EC_WORD_IS, EC_WORD_TOO_WEAK, EC_EMPTY_WORD}, {EC_WORD_YOU, EC_WORD_THINK, EC_WORD_THIS, EC_WORD_IS, EC_WORD_EASY, EC_WORD_QUES}, {EC_WORD_WHAT, EC_WORD_WILL, EC_WORD_COME, EC_WORD_AFTER, EC_WORD_THIS, EC_WORD_QUES}, {EC_WORD_I_AM, EC_WORD_JUST, EC_WORD_SO, EC_WORD_CONFUSED, EC_WORD_EXCL, EC_EMPTY_WORD}, {EC_WORD_I, EC_WORD_JUST, EC_WORD_WANT, EC_WORD_TO, EC_WORD_GO_HOME, EC_WORD_ELLIPSIS}, {EC_WORD_YEEHAW_EXCL, EC_WORD_THIS, EC_WORD_PLACE, EC_WORD_IS, EC_WORD_A, EC_WORD_PUSHOVER}, {EC_WORD_I, EC_WORD_HAVEN_T, EC_WORD_BEEN, EC_WORD_IN, EC_WORD_A, EC_WORD_BATTLE}, {EC_WORD_MAYBE, EC_WORD_IT_S, EC_WORD_RIGHT, EC_WORD_NEXT, EC_WORD_I, EC_WORD_THINK}, {EC_WORD_WAAAH, EC_WORD_EXCL, EC_WORD_IT, EC_WORD_WASN_T, EC_WORD_THIS, EC_WORD_WAY}, {EC_WORD_MY, EC_WORD_POKEMON, EC_WORD_ARE, EC_WORD_TOO, EC_WORD_TIRED, EC_WORD_ELLIPSIS}, {EC_WORD_MY, EC_WORD_POKEMON, EC_WORD_ARE, EC_WORD_STRONG, EC_WORD_TO, EC_WORD_POISON}, {EC_WORD_LALALA, EC_WORD_LALALA, EC_WORD_EXCL, EC_WORD_I_AM, EC_WORD_AWESOME, EC_WORD_LALALA}, {EC_MOVE2(TOXIC), EC_WORD_IS, EC_WORD_A, EC_WORD_TERRIBLE, EC_WORD_THING, EC_WORD_ISN_T_IT_QUES}, }; // Table duplicated from frontier_util, only Battle Pike entry used static const u8 sFrontierBrainStreakAppearances[NUM_FRONTIER_FACILITIES][4] = { [FRONTIER_FACILITY_TOWER] = {35, 70, 35, 1}, [FRONTIER_FACILITY_DOME] = { 4, 9, 5, 0}, [FRONTIER_FACILITY_PALACE] = {21, 42, 21, 1}, [FRONTIER_FACILITY_ARENA] = {28, 56, 28, 1}, [FRONTIER_FACILITY_FACTORY] = {21, 42, 21, 1}, [FRONTIER_FACILITY_PIKE] = {28, 140, 56, 1}, [FRONTIER_FACILITY_PYRAMID] = {21, 70, 35, 0}, }; static void (* const sBattlePikeFunctions[])(void) = { [BATTLE_PIKE_FUNC_SET_ROOM_TYPE] = SetRoomType, [BATTLE_PIKE_FUNC_GET_DATA] = GetBattlePikeData, [BATTLE_PIKE_FUNC_SET_DATA] = SetBattlePikeData, [BATTLE_PIKE_FUNC_IS_FINAL_ROOM] = IsNextRoomFinal, [BATTLE_PIKE_FUNC_SET_ROOM_OBJECTS] = SetupRoomObjectEvents, [BATTLE_PIKE_FUNC_GET_ROOM_TYPE] = GetRoomType, [BATTLE_PIKE_FUNC_SET_IN_WILD_MON_ROOM] = SetInWildMonRoom, [BATTLE_PIKE_FUNC_CLEAR_IN_WILD_MON_ROOM] = ClearInWildMonRoom, [BATTLE_PIKE_FUNC_SAVE] = SavePikeChallenge, [BATTLE_PIKE_FUNC_DUMMY_1] = PikeDummy1, [BATTLE_PIKE_FUNC_DUMMY_2] = PikeDummy2, [BATTLE_PIKE_FUNC_GET_ROOM_STATUS] = GetRoomInflictedStatus, [BATTLE_PIKE_FUNC_GET_ROOM_STATUS_MON] = GetRoomInflictedStatusMon, [BATTLE_PIKE_FUNC_HEAL_ONE_TWO_MONS] = HealOneOrTwoMons, [BATTLE_PIKE_FUNC_BUFFER_NPC_MSG] = BufferNPCMessage, [BATTLE_PIKE_FUNC_STATUS_SCREEN_FLASH] = StatusInflictionScreenFlash, [BATTLE_PIKE_FUNC_IS_IN] = GetInBattlePike, [BATTLE_PIKE_FUNC_SET_HINT_ROOM] = SetHintedRoom, [BATTLE_PIKE_FUNC_GET_HINT_ROOM_ID] = GetHintedRoomIndex, [BATTLE_PIKE_FUNC_GET_ROOM_TYPE_HINT] = GetRoomTypeHint, [BATTLE_PIKE_FUNC_CLEAR_TRAINER_IDS] = ClearPikeTrainerIds, [BATTLE_PIKE_FUNC_GET_TRAINER_INTRO] = BufferTrainerIntro, [BATTLE_PIKE_FUNC_GET_QUEEN_FIGHT_TYPE] = GetCurrentRoomPikeQueenFightType, [BATTLE_PIKE_FUNC_HEAL_MONS_BEFORE_QUEEN] = HealSomeMonsBeforePikeQueen, [BATTLE_PIKE_FUNC_SET_HEAL_ROOMS_DISABLED] = SetHealingroomTypesDisabled, [BATTLE_PIKE_FUNC_IS_PARTY_FULL_HEALTH] = IsPartyFullHealed, [BATTLE_PIKE_FUNC_SAVE_HELD_ITEMS] = SaveMonHeldItems, [BATTLE_PIKE_FUNC_RESET_HELD_ITEMS] = RestoreMonHeldItems, [BATTLE_PIKE_FUNC_INIT] = InitPikeChallenge }; static const u8 sRoomTypeHints[] = { PIKE_HINT_PEOPLE, // PIKE_ROOM_SINGLE_BATTLE PIKE_HINT_PEOPLE, // PIKE_ROOM_HEAL_FULL PIKE_HINT_WHISPERING, // PIKE_ROOM_NPC PIKE_HINT_NOSTALGIA, // PIKE_ROOM_STATUS PIKE_HINT_NOSTALGIA, // PIKE_ROOM_HEAL_PART PIKE_HINT_POKEMON, // PIKE_ROOM_WILD_MONS PIKE_HINT_POKEMON, // PIKE_ROOM_HARD_BATTLE PIKE_HINT_WHISPERING, // PIKE_ROOM_DOUBLE_BATTLE PIKE_HINT_BRAIN, // PIKE_ROOM_BRAIN }; static const u8 sNumMonsToHealBeforePikeQueen[][3] = { {2, 1, 0}, {2, 0, 1}, {1, 2, 0}, {1, 0, 2}, {0, 2, 1}, {0, 1, 2}, }; static bool8 (* const sStatusInflictionScreenFlashFuncs[])(struct Task *) = { StatusInflictionFadeOut, StatusInflictionFadeIn }; static const u32 sWinStreakFlags[] = {STREAK_PIKE_50, STREAK_PIKE_OPEN}; // code void CallBattlePikeFunction(void) { sBattlePikeFunctions[gSpecialVar_0x8004](); } static void SetRoomType(void) { u8 roomType = GetNextRoomType(); sRoomType = roomType; } static void SetupRoomObjectEvents(void) { bool32 setObjGfx1, setObjGfx2; u32 objGfx1; u16 objGfx2; VarSet(VAR_OBJ_GFX_ID_0, OBJ_EVENT_GFX_LINK_RECEPTIONIST); VarSet(VAR_OBJ_GFX_ID_1, OBJ_EVENT_GFX_DUSCLOPS); setObjGfx1 = TRUE; setObjGfx2 = FALSE; objGfx1 = 0; objGfx2 = 0; switch (sRoomType) { case PIKE_ROOM_SINGLE_BATTLE: PrepareOneTrainer(FALSE); setObjGfx1 = FALSE; break; case PIKE_ROOM_HEAL_FULL: objGfx1 = OBJ_EVENT_GFX_LINK_RECEPTIONIST; break; case PIKE_ROOM_NPC: objGfx1 = (u8)(GetNPCRoomGraphicsId()); break; case PIKE_ROOM_STATUS: objGfx1 = OBJ_EVENT_GFX_GENTLEMAN; if (sStatusMon == PIKE_STATUSMON_DUSCLOPS) objGfx2 = OBJ_EVENT_GFX_DUSCLOPS; else objGfx2 = OBJ_EVENT_GFX_KIRLIA; setObjGfx2 = TRUE; break; case PIKE_ROOM_HEAL_PART: objGfx1 = OBJ_EVENT_GFX_GENTLEMAN; break; case PIKE_ROOM_WILD_MONS: setObjGfx1 = FALSE; break; case PIKE_ROOM_HARD_BATTLE: PrepareOneTrainer(TRUE); objGfx2 = OBJ_EVENT_GFX_LINK_RECEPTIONIST; setObjGfx1 = FALSE; setObjGfx2 = TRUE; break; case PIKE_ROOM_DOUBLE_BATTLE: PrepareTwoTrainers(); setObjGfx1 = FALSE; break; case PIKE_ROOM_BRAIN: SetFrontierBrainObjEventGfx(FRONTIER_FACILITY_PIKE); objGfx2 = OBJ_EVENT_GFX_LINK_RECEPTIONIST; setObjGfx1 = FALSE; setObjGfx2 = TRUE; break; default: return; } if (setObjGfx1 == TRUE) VarSet(VAR_OBJ_GFX_ID_0, objGfx1); if (setObjGfx2 == TRUE) VarSet(VAR_OBJ_GFX_ID_1, objGfx2); } static void GetBattlePikeData(void) { u32 lvlMode = gSaveBlock2Ptr->frontier.lvlMode; switch (gSpecialVar_0x8005) { case PIKE_DATA_PRIZE: gSpecialVar_Result = gSaveBlock2Ptr->frontier.pikePrize; break; case PIKE_DATA_WIN_STREAK: gSpecialVar_Result = gSaveBlock2Ptr->frontier.pikeWinStreaks[gSaveBlock2Ptr->frontier.lvlMode]; break; case PIKE_DATA_RECORD_STREAK: gSpecialVar_Result = gSaveBlock2Ptr->frontier.pikeRecordStreaks[gSaveBlock2Ptr->frontier.lvlMode]; break; case PIKE_DATA_TOTAL_STREAKS: gSpecialVar_Result = gSaveBlock2Ptr->frontier.pikeTotalStreaks[gSaveBlock2Ptr->frontier.lvlMode]; break; case PIKE_DATA_WIN_STREAK_ACTIVE: if (lvlMode != FRONTIER_LVL_50) gSpecialVar_Result = gSaveBlock2Ptr->frontier.winStreakActiveFlags & STREAK_PIKE_OPEN; else gSpecialVar_Result = gSaveBlock2Ptr->frontier.winStreakActiveFlags & STREAK_PIKE_50; break; } } static void SetBattlePikeData(void) { u32 lvlMode = gSaveBlock2Ptr->frontier.lvlMode; switch (gSpecialVar_0x8005) { case PIKE_DATA_PRIZE: gSaveBlock2Ptr->frontier.pikePrize = gSpecialVar_0x8006; break; case PIKE_DATA_WIN_STREAK: if (gSpecialVar_0x8006 <= MAX_STREAK) gSaveBlock2Ptr->frontier.pikeWinStreaks[gSaveBlock2Ptr->frontier.lvlMode] = gSpecialVar_0x8006; break; case PIKE_DATA_RECORD_STREAK: if (gSpecialVar_0x8006 <= MAX_STREAK && gSaveBlock2Ptr->frontier.pikeRecordStreaks[gSaveBlock2Ptr->frontier.lvlMode] < gSpecialVar_0x8006) gSaveBlock2Ptr->frontier.pikeRecordStreaks[gSaveBlock2Ptr->frontier.lvlMode] = gSpecialVar_0x8006; break; case PIKE_DATA_TOTAL_STREAKS: if (gSpecialVar_0x8006 <= MAX_STREAK) gSaveBlock2Ptr->frontier.pikeTotalStreaks[gSaveBlock2Ptr->frontier.lvlMode] = gSpecialVar_0x8006; break; case PIKE_DATA_WIN_STREAK_ACTIVE: if (lvlMode != FRONTIER_LVL_50) { if (gSpecialVar_0x8006) gSaveBlock2Ptr->frontier.winStreakActiveFlags |= STREAK_PIKE_OPEN; else gSaveBlock2Ptr->frontier.winStreakActiveFlags &= ~(STREAK_PIKE_OPEN); } else { if (gSpecialVar_0x8006) gSaveBlock2Ptr->frontier.winStreakActiveFlags |= STREAK_PIKE_50; else gSaveBlock2Ptr->frontier.winStreakActiveFlags &= ~(STREAK_PIKE_50); } break; } } static void IsNextRoomFinal(void) { if (gSaveBlock2Ptr->frontier.curChallengeBattleNum > NUM_PIKE_ROOMS) gSpecialVar_Result = TRUE; else gSpecialVar_Result = FALSE; } static void GetRoomType(void) { gSpecialVar_Result = sRoomType; } static void SetInWildMonRoom(void) { sInWildMonRoom = TRUE; } static void ClearInWildMonRoom(void) { sInWildMonRoom = FALSE; } static void SavePikeChallenge(void) { gSaveBlock2Ptr->frontier.challengeStatus = gSpecialVar_0x8005; VarSet(VAR_TEMP_0, 0); gSaveBlock2Ptr->frontier.challengePaused = TRUE; SaveMapView(); TrySavingData(SAVE_LINK); } static void PikeDummy1(void) { } static void PikeDummy2(void) { } static void GetRoomInflictedStatus(void) { switch (sStatusFlags) { case STATUS1_FREEZE: gSpecialVar_Result = PIKE_STATUS_FREEZE; break; case STATUS1_BURN: gSpecialVar_Result = PIKE_STATUS_BURN; break; case STATUS1_TOXIC_POISON: gSpecialVar_Result = PIKE_STATUS_TOXIC; break; case STATUS1_PARALYSIS: gSpecialVar_Result = PIKE_STATUS_PARALYSIS; break; case STATUS1_SLEEP: gSpecialVar_Result = PIKE_STATUS_SLEEP; break; } } static void GetRoomInflictedStatusMon(void) { gSpecialVar_Result = sStatusMon; } static void HealOneOrTwoMons(void) { u16 toHeal = (Random() % 2) + 1; TryHealMons(toHeal); gSpecialVar_Result = toHeal; } static void BufferNPCMessage(void) { int speechId; if (gSaveBlock2Ptr->frontier.curChallengeBattleNum <= 4) speechId = sNPCTable[sNpcId].speechId1; else if (gSaveBlock2Ptr->frontier.curChallengeBattleNum <= 10) speechId = sNPCTable[sNpcId].speechId2; else speechId = sNPCTable[sNpcId].speechId3; FrontierSpeechToString(sNPCSpeeches[speechId]); } static void StatusInflictionScreenFlash(void) { CreateTask(Task_DoStatusInflictionScreenFlash, 2); } static void HealMon(struct Pokemon *mon) { u8 i; u16 hp; u8 ppBonuses; u8 data[4]; for (i = 0; i < 4; i++) data[i] = 0; hp = GetMonData(mon, MON_DATA_MAX_HP); data[0] = hp; data[1] = hp >> 8; SetMonData(mon, MON_DATA_HP, data); ppBonuses = GetMonData(mon, MON_DATA_PP_BONUSES); for (i = 0; i < MAX_MON_MOVES; i++) { u16 move = GetMonData(mon, MON_DATA_MOVE1 + i); data[0] = CalculatePPWithBonus(move, ppBonuses, i); SetMonData(mon, MON_DATA_PP1 + i, data); } data[0] = 0; data[1] = 0; data[2] = 0; data[3] = 0; SetMonData(mon, MON_DATA_STATUS, data); } static bool8 DoesAbilityPreventStatus(struct Pokemon *mon, u32 status) { u8 ability = GetMonAbility(mon); bool8 ret = FALSE; switch (status) { case STATUS1_FREEZE: if (ability == ABILITY_MAGMA_ARMOR) ret = TRUE; break; case STATUS1_BURN: if (ability == ABILITY_WATER_VEIL) ret = TRUE; break; case STATUS1_PARALYSIS: if (ability == ABILITY_LIMBER) ret = TRUE; break; case STATUS1_SLEEP: if (ability == ABILITY_INSOMNIA || ability == ABILITY_VITAL_SPIRIT) ret = TRUE; break; case STATUS1_TOXIC_POISON: if (ability == ABILITY_IMMUNITY) ret = TRUE; break; } return ret; } static bool8 DoesTypePreventStatus(u16 species, u32 status) { bool8 ret = FALSE; switch (status) { case STATUS1_TOXIC_POISON: if (gBaseStats[species].type1 == TYPE_STEEL || gBaseStats[species].type1 == TYPE_POISON || gBaseStats[species].type2 == TYPE_STEEL || gBaseStats[species].type2 == TYPE_POISON) ret = TRUE; break; case STATUS1_FREEZE: if (gBaseStats[species].type1 == TYPE_ICE || gBaseStats[species].type2 == TYPE_ICE) ret = TRUE; break; case STATUS1_PARALYSIS: if (gBaseStats[species].type1 == TYPE_GROUND || gBaseStats[species].type1 == TYPE_ELECTRIC || gBaseStats[species].type2 == TYPE_GROUND || gBaseStats[species].type2 == TYPE_ELECTRIC) ret = TRUE; break; case STATUS1_BURN: if (gBaseStats[species].type1 == TYPE_FIRE || gBaseStats[species].type2 == TYPE_FIRE) ret = TRUE; break; case STATUS1_SLEEP: break; } return ret; } static bool8 TryInflictRandomStatus(void) { u8 j, i; u8 count; u8 indices[FRONTIER_PARTY_SIZE]; u32 status; u16 species; bool8 statusChosen; struct Pokemon *mon; for (i = 0; i < FRONTIER_PARTY_SIZE; i++) indices[i] = i; for (j = 0; j < 10; j++) { u8 temp, id; i = Random() % FRONTIER_PARTY_SIZE; id = Random() % FRONTIER_PARTY_SIZE; SWAP(indices[i], indices[id], temp); } if (gSaveBlock2Ptr->frontier.curChallengeBattleNum <= 4) count = 1; else if (gSaveBlock2Ptr->frontier.curChallengeBattleNum <= 9) count = 2; else count = 3; status = 0; do { u8 rand; statusChosen = FALSE; rand = Random() % 100; if (rand < 35) sStatusFlags = STATUS1_TOXIC_POISON; else if (rand < 60) sStatusFlags = STATUS1_FREEZE; else if (rand < 80) sStatusFlags = STATUS1_PARALYSIS; else if (rand < 90) sStatusFlags = STATUS1_SLEEP; else sStatusFlags = STATUS1_BURN; if (status != sStatusFlags) { status = sStatusFlags; j = 0; for (i = 0; i < FRONTIER_PARTY_SIZE; i++) { mon = &gPlayerParty[indices[i]]; if (GetAilmentFromStatus(GetMonData(mon, MON_DATA_STATUS)) == AILMENT_NONE && GetMonData(mon, MON_DATA_HP) != 0) { j++; species = GetMonData(mon, MON_DATA_SPECIES); if (!DoesTypePreventStatus(species, sStatusFlags)) { statusChosen = TRUE; break; } } if (j == count) break; } if (j == 0) return FALSE; } } while (!statusChosen); switch (sStatusFlags) { case STATUS1_FREEZE: sStatusMon = PIKE_STATUSMON_DUSCLOPS; break; case STATUS1_BURN: if (Random() % 2 != 0) sStatusMon = PIKE_STATUSMON_DUSCLOPS; else sStatusMon = PIKE_STATUSMON_KIRLIA; break; case STATUS1_PARALYSIS: case STATUS1_SLEEP: case STATUS1_TOXIC_POISON: default: sStatusMon = PIKE_STATUSMON_KIRLIA; break; } j = 0; for (i = 0; i < FRONTIER_PARTY_SIZE; i++) { mon = &gPlayerParty[indices[i]]; if (GetAilmentFromStatus(GetMonData(mon, MON_DATA_STATUS)) == AILMENT_NONE && GetMonData(mon, MON_DATA_HP) != 0) { j++; species = GetMonData(mon, MON_DATA_SPECIES); if (!DoesAbilityPreventStatus(mon, sStatusFlags) && !DoesTypePreventStatus(species, sStatusFlags)) SetMonData(mon, MON_DATA_STATUS, &sStatusFlags); } if (j == count) break; } return TRUE; } static bool8 AtLeastOneHealthyMon(void) { u8 i; u8 healthyMonsCount; u8 count; if (gSaveBlock2Ptr->frontier.curChallengeBattleNum <= 4) count = 1; else if (gSaveBlock2Ptr->frontier.curChallengeBattleNum <= 9) count = 2; else count = 3; healthyMonsCount = 0; for (i = 0; i < FRONTIER_PARTY_SIZE; i++) { struct Pokemon *mon = &gPlayerParty[i]; if (GetAilmentFromStatus(GetMonData(mon, MON_DATA_STATUS)) == AILMENT_NONE && GetMonData(mon, MON_DATA_HP) != 0) { healthyMonsCount++; } if (healthyMonsCount == count) break; } if (healthyMonsCount == 0) return FALSE; else return TRUE; } static u8 GetNextRoomType(void) { bool8 roomTypesDisabled[NUM_PIKE_ROOM_TYPES - 1]; // excludes Brain room, which cant be disabled u8 i; u8 nextRoomType; u8 roomHint; u8 numRoomCandidates; u8 *roomCandidates; u8 id; if (gSaveBlock2Ptr->frontier.pikeHintedRoomType == PIKE_ROOM_BRAIN) return gSaveBlock2Ptr->frontier.pikeHintedRoomType; // Check if the player walked into the same room that the lady gave a hint about. if (gSpecialVar_0x8007 == gSaveBlock2Ptr->frontier.pikeHintedRoomIndex) { if (gSaveBlock2Ptr->frontier.pikeHintedRoomType == PIKE_ROOM_STATUS) TryInflictRandomStatus(); return gSaveBlock2Ptr->frontier.pikeHintedRoomType; } for (i = 0; i < ARRAY_COUNT(roomTypesDisabled); i++) roomTypesDisabled[i] = FALSE; numRoomCandidates = NUM_PIKE_ROOM_TYPES - 1; // The other two room types cannot be the same type as the one associated with the lady's hint roomHint = sRoomTypeHints[gSaveBlock2Ptr->frontier.pikeHintedRoomType]; for (i = 0; i < ARRAY_COUNT(roomTypesDisabled); i++) { if (sRoomTypeHints[i] == roomHint) { roomTypesDisabled[i] = TRUE; numRoomCandidates--; } } // Remove room type candidates that would have no effect on the player's party. if (roomTypesDisabled[PIKE_ROOM_DOUBLE_BATTLE] != TRUE && !AtLeastTwoAliveMons()) { roomTypesDisabled[PIKE_ROOM_DOUBLE_BATTLE] = TRUE; numRoomCandidates--; } if (roomTypesDisabled[PIKE_ROOM_STATUS] != TRUE && !AtLeastOneHealthyMon()) { roomTypesDisabled[PIKE_ROOM_STATUS] = TRUE; numRoomCandidates--; } // Remove healing room type candidates if healing rooms are disabled. if (gSaveBlock2Ptr->frontier.pikeHealingRoomsDisabled) { if (roomTypesDisabled[PIKE_ROOM_HEAL_FULL] != TRUE) { roomTypesDisabled[PIKE_ROOM_HEAL_FULL] = TRUE; numRoomCandidates--; } if (roomTypesDisabled[PIKE_ROOM_HEAL_PART] != TRUE) { roomTypesDisabled[PIKE_ROOM_HEAL_PART] = TRUE; numRoomCandidates--; } } roomCandidates = AllocZeroed(numRoomCandidates); id = 0; for (i = 0; i < ARRAY_COUNT(roomTypesDisabled); i++) { if (roomTypesDisabled[i] == FALSE) roomCandidates[id++] = i; } nextRoomType = roomCandidates[Random() % numRoomCandidates]; free(roomCandidates); if (nextRoomType == PIKE_ROOM_STATUS) TryInflictRandomStatus(); return nextRoomType; } static u16 GetNPCRoomGraphicsId(void) { sNpcId = Random() % ARRAY_COUNT(sNPCTable); return sNPCTable[sNpcId].graphicsId; } // Unused static u8 GetInWildMonRoom(void) { return sInWildMonRoom; } bool32 TryGenerateBattlePikeWildMon(bool8 checkKeenEyeIntimidate) { s32 i; s32 monLevel; u32 exp; u8 headerId = GetBattlePikeWildMonHeaderId(); u32 lvlMode = gSaveBlock2Ptr->frontier.lvlMode; const struct PikeWildMon *const *const wildMons = sWildMons[lvlMode]; u32 abilityNum; s32 pikeMonId = GetMonData(&gEnemyParty[0], MON_DATA_SPECIES, NULL); pikeMonId = SpeciesToPikeMonId(pikeMonId); if (gSaveBlock2Ptr->frontier.lvlMode != FRONTIER_LVL_50) { monLevel = GetHighestLevelInPlayerParty(); if (monLevel < FRONTIER_MIN_LEVEL_OPEN) { monLevel = FRONTIER_MIN_LEVEL_OPEN; } else { monLevel -= wildMons[headerId][pikeMonId].levelDelta; if (monLevel < FRONTIER_MIN_LEVEL_OPEN) monLevel = FRONTIER_MIN_LEVEL_OPEN; } } else { monLevel = FRONTIER_MAX_LEVEL_50 - wildMons[headerId][pikeMonId].levelDelta; } if (checkKeenEyeIntimidate == TRUE && !CanEncounterWildMon(monLevel)) return FALSE; exp = Rogue_ModifyExperienceTables(gBaseStats[wildMons[headerId][pikeMonId].species].growthRate, monLevel); SetMonData(&gEnemyParty[0], MON_DATA_EXP, &exp); if (gBaseStats[wildMons[headerId][pikeMonId].species].abilities[1]) abilityNum = Random() % 2; else abilityNum = 0; SetMonData(&gEnemyParty[0], MON_DATA_ABILITY_NUM, &abilityNum); for (i = 0; i < MAX_MON_MOVES; i++) SetMonMoveSlot(&gEnemyParty[0], wildMons[headerId][pikeMonId].moves[i], i); CalculateMonStats(&gEnemyParty[0]); return TRUE; } u8 GetBattlePikeWildMonHeaderId(void) { u8 headerId; u8 lvlMode = gSaveBlock2Ptr->frontier.lvlMode; u16 winStreak = gSaveBlock2Ptr->frontier.pikeWinStreaks[lvlMode]; if (winStreak <= 20 * NUM_PIKE_ROOMS) headerId = 0; else if (winStreak <= 40 * NUM_PIKE_ROOMS) headerId = 1; else if (winStreak <= 60 * NUM_PIKE_ROOMS) headerId = 2; else headerId = 3; return headerId; } static void DoStatusInflictionScreenFlash(u8 taskId) { while (sStatusInflictionScreenFlashFuncs[gTasks[taskId].data[0]](&gTasks[taskId])); } static bool8 StatusInflictionFadeOut(struct Task *task) { if (task->data[6] == 0 || --task->data[6] == 0) { task->data[6] = task->data[1]; task->data[7] += task->data[4]; if (task->data[7] > 16) task->data[7] = 16; BlendPalettes(PALETTES_ALL, task->data[7], RGB(11, 11, 11)); } if (task->data[7] >= 16) { task->data[0]++; task->data[6] = task->data[2]; } return FALSE; } static bool8 StatusInflictionFadeIn(struct Task *task) { if (task->data[6] == 0 || --task->data[6] == 0) { task->data[6] = task->data[2]; task->data[7] -= task->data[5]; if (task->data[7] < 0) task->data[7] = 0; BlendPalettes(PALETTES_ALL, task->data[7], RGB(11, 11, 11)); } if (task->data[7] == 0) { if (--task->data[3] == 0) { DestroyTask(FindTaskIdByFunc(DoStatusInflictionScreenFlash)); } else { task->data[6] = task->data[1]; task->data[0] = 0; } } return FALSE; } static void StartStatusInflictionScreenFlash(s16 fadeOutDelay, s16 fadeInDelay, s16 numFades, s16 fadeOutSpeed, s16 fadeInSpped) { u8 taskId = CreateTask(DoStatusInflictionScreenFlash, 3); gTasks[taskId].data[1] = fadeOutDelay; gTasks[taskId].data[2] = fadeInDelay; gTasks[taskId].data[3] = numFades; gTasks[taskId].data[4] = fadeOutSpeed; gTasks[taskId].data[5] = fadeInSpped; gTasks[taskId].data[6] = fadeOutDelay; } static bool8 IsStatusInflictionScreenFlashTaskFinished(void) { if (FindTaskIdByFunc(DoStatusInflictionScreenFlash) == TASK_NONE) return TRUE; else return FALSE; } static void Task_DoStatusInflictionScreenFlash(u8 taskId) { if (gTasks[taskId].data[0] == 0) { gTasks[taskId].data[0]++; StartStatusInflictionScreenFlash(0, 0, 3, 2, 2); } else { if (IsStatusInflictionScreenFlashTaskFinished()) { ScriptContext_Enable(); DestroyTask(taskId); } } } static void TryHealMons(u8 healCount) { u8 j, i, k; u8 indices[FRONTIER_PARTY_SIZE]; if (healCount == 0) return; for (i = 0; i < FRONTIER_PARTY_SIZE; i++) indices[i] = i; for (k = 0; k < 10; k++) { u8 temp; i = Random() % FRONTIER_PARTY_SIZE; j = Random() % FRONTIER_PARTY_SIZE; SWAP(indices[i], indices[j], temp); } for (i = 0; i < FRONTIER_PARTY_SIZE; i++) { bool32 canBeHealed = FALSE; struct Pokemon *mon = &gPlayerParty[indices[i]]; u16 curr = GetMonData(mon, MON_DATA_HP); u16 max = GetMonData(mon, MON_DATA_MAX_HP); if (curr < max) { canBeHealed = TRUE; } else if (GetAilmentFromStatus(GetMonData(mon, MON_DATA_STATUS)) != AILMENT_NONE) { canBeHealed = TRUE; } else { u8 ppBonuses = GetMonData(mon, MON_DATA_PP_BONUSES); for (j = 0; j < MAX_MON_MOVES; j++) { u16 move = GetMonData(mon, MON_DATA_MOVE1 + j); max = CalculatePPWithBonus(move, ppBonuses, j); curr = GetMonData(mon, MON_DATA_PP1 + j); if (curr < max) { canBeHealed = TRUE; break; } } } if (canBeHealed == TRUE) { HealMon(&gPlayerParty[indices[i]]); if (--healCount == 0) break; } } } static void GetInBattlePike(void) { gSpecialVar_Result = InBattlePike(); } bool8 InBattlePike(void) { return FALSE; } static void SetHintedRoom(void) { u8 i, count, id; u8 *roomCandidates; gSpecialVar_Result = FALSE; if (GetPikeQueenFightType(1)) { gSpecialVar_Result = TRUE; gSaveBlock2Ptr->frontier.pikeHintedRoomIndex = Random() % 6; gSaveBlock2Ptr->frontier.pikeHintedRoomType = PIKE_ROOM_BRAIN; } else { gSaveBlock2Ptr->frontier.pikeHintedRoomIndex = Random() % 3; if (gSaveBlock2Ptr->frontier.pikeHealingRoomsDisabled) count = NUM_PIKE_ROOM_TYPES - 3; // exclude healing rooms and Brain room else count = NUM_PIKE_ROOM_TYPES - 1; // exclude Brain room roomCandidates = AllocZeroed(count); for (i = 0, id = 0; i < count; i++) { if (gSaveBlock2Ptr->frontier.pikeHealingRoomsDisabled) { if (i != PIKE_ROOM_HEAL_FULL && i != PIKE_ROOM_HEAL_PART) roomCandidates[id++] = i; } else { roomCandidates[i] = i; } } gSaveBlock2Ptr->frontier.pikeHintedRoomType = roomCandidates[Random() % count]; free(roomCandidates); if (gSaveBlock2Ptr->frontier.pikeHintedRoomType == PIKE_ROOM_STATUS && !AtLeastOneHealthyMon()) gSaveBlock2Ptr->frontier.pikeHintedRoomType = PIKE_ROOM_NPC; if (gSaveBlock2Ptr->frontier.pikeHintedRoomType == PIKE_ROOM_DOUBLE_BATTLE && !AtLeastTwoAliveMons()) gSaveBlock2Ptr->frontier.pikeHintedRoomType = PIKE_ROOM_NPC; } } static void GetHintedRoomIndex(void) { gSpecialVar_Result = gSaveBlock2Ptr->frontier.pikeHintedRoomIndex; } static void GetRoomTypeHint(void) { gSpecialVar_Result = sRoomTypeHints[gSaveBlock2Ptr->frontier.pikeHintedRoomType]; } static void PrepareOneTrainer(bool8 difficult) { int i; u8 lvlMode; u8 battleNum; u16 challengeNum; u16 trainerId; if (!difficult) battleNum = 1; else battleNum = FRONTIER_STAGES_PER_CHALLENGE - 1; lvlMode = gSaveBlock2Ptr->frontier.lvlMode; challengeNum = gSaveBlock2Ptr->frontier.pikeWinStreaks[lvlMode] / NUM_PIKE_ROOMS; do { trainerId = GetRandomScaledFrontierTrainerId(challengeNum, battleNum); for (i = 0; i < gSaveBlock2Ptr->frontier.curChallengeBattleNum - 1; i++) { if (gSaveBlock2Ptr->frontier.trainerIds[i] == trainerId) break; } } while (i != gSaveBlock2Ptr->frontier.curChallengeBattleNum - 1); gTrainerBattleOpponent_A = trainerId; gFacilityTrainers = gBattleFrontierTrainers; SetBattleFacilityTrainerGfxId(gTrainerBattleOpponent_A, 0); if (gSaveBlock2Ptr->frontier.curChallengeBattleNum < NUM_PIKE_ROOMS) gSaveBlock2Ptr->frontier.trainerIds[gSaveBlock2Ptr->frontier.curChallengeBattleNum - 1] = gTrainerBattleOpponent_A; } static void PrepareTwoTrainers(void) { int i; u16 trainerId; u8 lvlMode = gSaveBlock2Ptr->frontier.lvlMode; u16 challengeNum = gSaveBlock2Ptr->frontier.pikeWinStreaks[lvlMode] / NUM_PIKE_ROOMS; gFacilityTrainers = gBattleFrontierTrainers; do { trainerId = GetRandomScaledFrontierTrainerId(challengeNum, 1); for (i = 0; i < gSaveBlock2Ptr->frontier.curChallengeBattleNum - 1; i++) { if (gSaveBlock2Ptr->frontier.trainerIds[i] == trainerId) break; } } while (i != gSaveBlock2Ptr->frontier.curChallengeBattleNum - 1); gTrainerBattleOpponent_A = trainerId; SetBattleFacilityTrainerGfxId(gTrainerBattleOpponent_A, 0); if (gSaveBlock2Ptr->frontier.curChallengeBattleNum <= NUM_PIKE_ROOMS) gSaveBlock2Ptr->frontier.trainerIds[gSaveBlock2Ptr->frontier.curChallengeBattleNum - 1] = gTrainerBattleOpponent_A; do { trainerId = GetRandomScaledFrontierTrainerId(challengeNum, 1); for (i = 0; i < gSaveBlock2Ptr->frontier.curChallengeBattleNum; i++) { if (gSaveBlock2Ptr->frontier.trainerIds[i] == trainerId) break; } } while (i != gSaveBlock2Ptr->frontier.curChallengeBattleNum); gTrainerBattleOpponent_B = trainerId; SetBattleFacilityTrainerGfxId(gTrainerBattleOpponent_B, 1); if (gSaveBlock2Ptr->frontier.curChallengeBattleNum < NUM_PIKE_ROOMS) gSaveBlock2Ptr->frontier.trainerIds[gSaveBlock2Ptr->frontier.curChallengeBattleNum - 2] = gTrainerBattleOpponent_B; } static void ClearPikeTrainerIds(void) { u8 i; for (i = 0; i < NUM_PIKE_ROOMS; i++) gSaveBlock2Ptr->frontier.trainerIds[i] = 0xFFFF; } static void BufferTrainerIntro(void) { if (gSpecialVar_0x8005 == 0) { if (gTrainerBattleOpponent_A < FRONTIER_TRAINERS_COUNT) FrontierSpeechToString(gFacilityTrainers[gTrainerBattleOpponent_A].speechBefore); } else if (gSpecialVar_0x8005 == 1) { if (gTrainerBattleOpponent_B < FRONTIER_TRAINERS_COUNT) FrontierSpeechToString(gFacilityTrainers[gTrainerBattleOpponent_B].speechBefore); } } static bool8 AtLeastTwoAliveMons(void) { struct Pokemon *mon; u8 i, countDead; mon = &gPlayerParty[0]; countDead = 0; for (i = 0; i < FRONTIER_PARTY_SIZE; i++, mon++) { if (GetMonData(mon, MON_DATA_HP) == 0) countDead++; } if (countDead >= 2) return FALSE; else return TRUE; } static u8 GetPikeQueenFightType(u8 nextRoom) { u8 numPikeSymbols; u8 facility = FRONTIER_FACILITY_PIKE; u8 ret = FRONTIER_BRAIN_NOT_READY; u8 lvlMode = gSaveBlock2Ptr->frontier.lvlMode; u16 winStreak = gSaveBlock2Ptr->frontier.pikeWinStreaks[lvlMode]; winStreak += nextRoom; numPikeSymbols = GetPlayerSymbolCountForFacility(FRONTIER_FACILITY_PIKE); switch (numPikeSymbols) { case 0: case 1: if (winStreak == sFrontierBrainStreakAppearances[facility][numPikeSymbols] - sFrontierBrainStreakAppearances[facility][3]) ret = numPikeSymbols + 1; // FRONTIER_BRAIN_SILVER and FRONTIER_BRAIN_GOLD break; case 2: default: if (winStreak == sFrontierBrainStreakAppearances[facility][0] - sFrontierBrainStreakAppearances[facility][3]) ret = FRONTIER_BRAIN_STREAK; else if (winStreak == sFrontierBrainStreakAppearances[facility][1] - sFrontierBrainStreakAppearances[facility][3] || (winStreak > sFrontierBrainStreakAppearances[facility][1] && (winStreak - sFrontierBrainStreakAppearances[facility][1] + sFrontierBrainStreakAppearances[facility][3]) % sFrontierBrainStreakAppearances[facility][2] == 0)) ret = FRONTIER_BRAIN_STREAK_LONG; break; } return ret; } static void GetCurrentRoomPikeQueenFightType(void) { gSpecialVar_Result = GetPikeQueenFightType(0); } static void HealSomeMonsBeforePikeQueen(void) { u8 toHealCount = sNumMonsToHealBeforePikeQueen[gSaveBlock2Ptr->frontier.pikeHintedRoomIndex][gSpecialVar_0x8007]; TryHealMons(toHealCount); gSpecialVar_Result = toHealCount; } static void SetHealingroomTypesDisabled(void) { gSaveBlock2Ptr->frontier.pikeHealingRoomsDisabled = gSpecialVar_0x8005; } static void IsPartyFullHealed(void) { u8 i, j; gSpecialVar_Result = TRUE; for (i = 0; i < FRONTIER_PARTY_SIZE; i++) { bool32 canBeHealed = FALSE; struct Pokemon *mon = &gPlayerParty[i]; u16 curr = GetMonData(mon, MON_DATA_HP); u16 max = GetMonData(mon, MON_DATA_MAX_HP); if (curr >= max && GetAilmentFromStatus(GetMonData(mon, MON_DATA_STATUS)) == AILMENT_NONE) { u8 ppBonuses = GetMonData(mon, MON_DATA_PP_BONUSES); for (j = 0; j < MAX_MON_MOVES; j++) { u16 move = GetMonData(mon, MON_DATA_MOVE1 + j); max = CalculatePPWithBonus(move, ppBonuses, j); curr = GetMonData(mon, MON_DATA_PP1 + j); if (curr < max) { canBeHealed = TRUE; break; } } } else { canBeHealed = TRUE; } if (canBeHealed == TRUE) { gSpecialVar_Result = FALSE; break; } } } static void SaveMonHeldItems(void) { u8 i; for (i = 0; i < FRONTIER_PARTY_SIZE; i++) { int heldItem = GetMonData(&gSaveBlock1Ptr->playerParty[gSaveBlock2Ptr->frontier.selectedPartyMons[i] - 1], MON_DATA_HELD_ITEM); gSaveBlock2Ptr->frontier.pikeHeldItemsBackup[i] = heldItem; } } static void RestoreMonHeldItems(void) { u8 i; for (i = 0; i < FRONTIER_PARTY_SIZE; i++) { SetMonData(&gPlayerParty[gSaveBlock2Ptr->frontier.selectedPartyMons[i] - 1], MON_DATA_HELD_ITEM, &gSaveBlock2Ptr->frontier.pikeHeldItemsBackup[i]); } } static void InitPikeChallenge(void) { u8 lvlMode = gSaveBlock2Ptr->frontier.lvlMode; gSaveBlock2Ptr->frontier.challengeStatus = 0; gSaveBlock2Ptr->frontier.curChallengeBattleNum = 0; gSaveBlock2Ptr->frontier.challengePaused = FALSE; if (!(gSaveBlock2Ptr->frontier.winStreakActiveFlags & sWinStreakFlags[lvlMode])) gSaveBlock2Ptr->frontier.pikeWinStreaks[lvlMode] = 0; gTrainerBattleOpponent_A = 0; gBattleOutcome = 0; } static bool8 CanEncounterWildMon(u8 enemyMonLevel) { if (!GetMonData(&gPlayerParty[0], MON_DATA_SANITY_IS_EGG)) { u8 monAbility = GetMonAbility(&gPlayerParty[0]); if (monAbility == ABILITY_KEEN_EYE || monAbility == ABILITY_INTIMIDATE) { u8 playerMonLevel = GetMonData(&gPlayerParty[0], MON_DATA_LEVEL); if (playerMonLevel > 5 && enemyMonLevel <= playerMonLevel - 5 && Random() % 2 == 0) return FALSE; } } return TRUE; } static u8 SpeciesToPikeMonId(u16 species) { u8 ret; if (species == SPECIES_SEVIPER) ret = 0; else if (species == SPECIES_MILOTIC) ret = 1; else ret = 2; return ret; }
411
0.914005
1
0.914005
game-dev
MEDIA
0.984555
game-dev
0.859357
1
0.859357
ergonomy-joe/u4-decompiled
10,441
SRC/U4_MAP.C
/* * Ultima IV - Quest Of The Avatar * (c) Copyright 1987 Lord British * reverse-coded by Ergonomy Joe in 2012 */ #include "u4.h" #include <stdlib.h> int D_08CE = -1; int D_08D0 = -1; /*load the portion of the map with coordinates in parameter*/ C_2399(bp06, bp04) unsigned bp06; unsigned bp04; { int bp_02; if(D_08CE != -1) { dfree((void far *)D_933A[D_08D0][D_08CE]); D_933A[D_08D0][D_08CE] = 0; } if(D_933A[bp06][bp04] == 0) { if(dlseek(File_MAP, (bp06 * 8 + bp04) * sizeof(tMap32x32)) == -1) exit(1); D_933A[bp06][bp04] = (tMap32x32 far *)dalloc(sizeof(tMap32x32)); if(D_933A[bp06][bp04] == 0) exit(1); bp_02 = dread(File_MAP, D_933A[bp06][bp04], sizeof(tMap32x32)); if(bp_02 != sizeof(tMap32x32)) exit(3); } D_08CE = bp04; D_08D0 = bp06; } C_249C() { register int si, di; C_2399(D_95A5.y / 2, D_95A5.x / 2); for(di = 0; di < 16; di ++) for(si = 0; si < 16; si ++) D_8742._map.x32x32[di][si] = (*(D_933A[D_95A5.y/2][D_95A5.x/2]))[(D_95A5.y&1)*0x10+di][(D_95A5.x&1)*0x10+si]; } #define TMP0 (((D_95A5.x+1)&15)) #define TMP1 (((D_95A5.y+1)&15)) C_2517() { register int si, di; C_2399(D_95A5.y / 2, TMP0 / 2); for(di = 0; di < 16; di ++) for(si = 0; si < 16; si ++) D_8742._map.x32x32[di][si+16] = (*(D_933A[D_95A5.y/2][TMP0/2]))[(D_95A5.y&1)*0x10+di][(TMP0&1)*0x10+si]; } C_259F() { register int si, di; C_2399(TMP1 / 2, D_95A5.x / 2); for(di = 0; di < 16; di ++) for(si = 0; si < 16; si ++) D_8742._map.x32x32[di+16][si] = (*(D_933A[TMP1/2][D_95A5.x/2]))[(TMP1&1)*0x10+di][(D_95A5.x&1)*0x10+si]; } C_2624() { register int si, di; C_2399(TMP1 / 2, TMP0 / 2); for(di = 0; di < 16; di ++) for(si = 0; si < 16; si ++) D_8742._map.x32x32[di+16][si+16] = (*(D_933A[TMP1/2][TMP0/2]))[(TMP1&1)*0x10+di][(TMP0&1)*0x10+si]; } C_26B6() { D_95A5.x = ((Party._loc < 0x11)?Party._x:Party.out_x) >> 4; D_959C.x = ((Party._loc < 0x11)?Party._x:Party.out_x) & 15; if(D_959C.x < 8) { D_959C.x += 0x10; D_95A5.x = (D_95A5.x - 1) & 15; } D_95A5.y = ((Party._loc < 0x11)?Party._y:Party.out_y) >> 4; D_959C.y = ((Party._loc < 0x11)?Party._y:Party.out_y) & 15; if(D_959C.y < 8) { D_959C.y += 0x10; D_95A5.y = (D_95A5.y - 1) & 15; } C_249C(); C_2517(); C_259F(); C_2624(); } /*Leaving...*/ C_2747() { u4_puts("Leaving...\n"); CurMode = MOD_VISION; if(Load("OUTMONST.SAV", sizeof(struct tNPC), &(D_8742._npc)) == -1) exit(3); if(File_TLK) { dclose(File_TLK); File_TLK = 0; } Party._x = Party.out_x; Party._y = Party.out_y; C_26B6(); CurMode = MOD_OUTDOORS; Party._loc = 0; Party.f_1dc = 0; D_9440 = 1; if(Party._x == 0xef && Party._y == 0xf0) { D_8742._npc._tile[31] = D_8742._npc._gtile[31] = TIL_18; D_8742._npc._x[31] = 0xe9; D_8742._npc._y[31] = 0xf2; } u_kbflush(); } /*spawn daemons(if horn not used)*/ C_27D9() { if(spell_sta != 1) { /*horn not in use*/ register int si; for(si = 7; si >= 0; si--) { D_8742._npc._tile[si] = D_8742._npc._gtile[si] = TIL_F0; D_8742._npc._x[si] = 0xe7; D_8742._npc._y[si] = Party._y + 1; } } } unsigned char D_08EC[] = { 0xE0, 0xE0, 0xE2, 0xE3, 0xE4, 0xE5, 0xE5, 0xE4}; unsigned char D_08F4[] = { 0xDC, 0xE4, 0xDC, 0xE4, 0xE3, 0xE1, 0xDF, 0xDE}; unsigned char D_08FC[] = {TIL_82,TIL_82,TIL_82,TIL_82,TIL_83,TIL_83,TIL_81,TIL_81}; /*spawn pirate ships*/ C_280A() { register int si; for(si = 7; si >= 0; si --) { D_8742._npc._x[si] = D_08EC[si]; D_8742._npc._y[si] = D_08F4[si]; D_8742._npc._tile[si] = TIL_80; D_8742._npc._gtile[si] = D_08FC[si]; } } /*GOING NORTH*/ C_2839() { register int si, di; Party._y --; D_959C.y = (D_959C.y - 1) & 0xff; if(D_959C.y < 5) { D_959C.y += 16; D_95A5.y = (D_95A5.y - 1) & 15; for(di = 0; di < 16; di ++) for(si = 0; si < 32; si ++) D_8742._map.x32x32[di+16][si] = D_8742._map.x32x32[di][si]; C_249C(); C_2517(); } } /*GOING SOUTH*/ C_2891() { register int si, di; Party._y ++; D_959C.y = (D_959C.y + 1) & 0xff; if(D_959C.y >= 27) { D_959C.y -= 16; D_95A5.y = (D_95A5.y + 1) & 15; for(di = 0; di < 16; di ++) for(si = 0; si < 32; si ++) D_8742._map.x32x32[di][si] = D_8742._map.x32x32[di+16][si]; C_259F(); C_2624(); } } /*GOING WEST*/ C_28E9() { register int si, di; Party._x --; D_959C.x = (D_959C.x - 1) & 0xff; if(D_959C.x < 5) { D_959C.x += 16; D_95A5.x = (D_95A5.x - 1) & 15; for(di = 0; di < 32; di ++) for(si = 0; si < 16; si ++) D_8742._map.x32x32[di][si+16] = D_8742._map.x32x32[di][si]; C_249C(); C_259F(); } } /*GOING EAST*/ C_2941() { register int si, di; Party._x ++; D_959C.x = (D_959C.x + 1) & 0xff; if(D_959C.x >= 27) { D_959C.x -= 16; D_95A5.x = (D_95A5.x + 1) & 15; for(di = 0; di < 32; di ++) for(si = 0; si < 16; si ++) D_8742._map.x32x32[di][si] = D_8742._map.x32x32[di][si+16]; C_2517(); C_2624(); } } unsigned char D_0904[] = { TIL_03,TIL_04,TIL_05,TIL_06,TIL_07,TIL_09,TIL_0A,TIL_0B,TIL_0C, TIL_10,TIL_11,TIL_12,TIL_13,TIL_14,TIL_15,TIL_16,TIL_17,TIL_18, TIL_19,TIL_1A,TIL_1B,TIL_1C,TIL_1D,TIL_1E,TIL_3C,TIL_3E,TIL_3F, TIL_43,TIL_44,TIL_46,TIL_47,TIL_49,TIL_4A,TIL_4C,TIL_8E,TIL_8F, 0/*End of list*/ }; /*isBrickSolid*/ C_2999(bp04) unsigned char bp04; { register int si; for(si = 0; D_0904[si]; si ++) if(bp04 == D_0904[si]) return 1; return 0; } /*C_29C3*/w_Blocked() { u4_puts("Blocked!\n"); sound(1); u_kbflush(); } /*C_29DE*/w_DriftOnly() { u4_puts("Drift Only!\n"); u_kbflush(); } /*check slow progress*/ C_29EF(bp04) unsigned char bp04; { switch(bp04) { case TIL_03: if(U4_RND1(7) != 0) return 0; break; case TIL_05: case TIL_06: if(U4_RND1(3) != 0) return 0; break; case TIL_07: case TIL_46: if(U4_RND1(1) == 0) return 0; break; default: return 0; } return 1; } C_2A38(bp04) unsigned char bp04; { return (bp04 < TIL_02) || ((bp04 >= TIL_8C) && (bp04 < TIL_90)); } /*check slow progress [boat]*/ C_2A5A(bp04) unsigned int bp04; { if(WindDir == bp04) return !(Party._moves & 3); if(WindDir == ((bp04+2)&3)) return (Party._moves & 3); return 1; } /*enter moongate ?*/ C_2A91(bp04) unsigned char bp04; { if(bp04 != TIL_43) return 0; if(Party._trammel == 4 && Party._felucca == 4) { t_callback(); Gra_09(); Party._loc = 0x1f; sound(9, 0xa0); C_E72C(); return 1; } t_callback(); Party._x = D_0814[Party._felucca]; Party._y = D_081C[Party._felucca]; Gra_09(); sound(9, 0xa0); Gra_09(); C_26B6(); t_callback(); Gra_09(); sound(9, 0xa0); Gra_09(); return 1; } /*move North*/ C_2B19() { /*LB's castle middle wing*/ if(tile_cur == TIL_0E) { w_Blocked(); return 0; } if(tile_north != TIL_0E && !C_2999(tile_north)) { w_Blocked(); return 0; } if(C_29EF(tile_north)) { w_SlowProgress(); return 1; } sound(0); if(CurMode == MOD_OUTDOORS) { C_2839(); if(C_2A91(tile_north)) return 0; return 1; } Party._y --; D_959C.y = Party._y; if(D_959C.y <= 0x1f) { return 1; } C_2747(); return 0; } /*C_2B8C*/CMDDIR_Up() { if(Party._tile == TIL_10 || Party._tile == TIL_12 || Party._tile == TIL_13) { Party._tile = TIL_11; u4_puts("Turn North!\n"); } else if(Party._tile == TIL_11) { u4_puts("Sail North!\n"); if(!C_2A38(tile_north)) { w_Blocked(); } else if(!C_2A5A(DIR_N)) { w_SlowProgress(); } else { C_2839(); } } else if(Party._tile == TIL_18) { w_DriftOnly(); } else { sound(0); u4_puts("North\n"); if(C_2B19() && D_95C6) { t_callback(); sound(0); C_2B19(); } } } /*move South*/ C_2C25() { if(!C_2999(tile_south)) { w_Blocked(); return 0; } if(C_29EF(tile_south)) { w_SlowProgress(); return 1; } sound(0); if(CurMode == MOD_OUTDOORS) { C_2891(); if(C_2A91(tile_south)) return 0; return 1; } Party._y ++; D_959C.y = Party._y; if(D_959C.y <= 0x1f) { return 1; } C_2747(); return 0; } /*C_2C8A*/CMDDIR_Down() { if(Party._tile == TIL_18) { w_DriftOnly(); } else if(Party._tile == TIL_10 || Party._tile == TIL_12 || Party._tile == TIL_11) { Party._tile = TIL_13; u4_puts("Turn South!\n"); } else if(Party._tile == TIL_13) { u4_puts("Sail South!\n"); if(!C_2A38(tile_south)) { w_Blocked(); } else if(!C_2A5A(DIR_S)) { w_SlowProgress(); } else { C_2891(); } } else { sound(0); u4_puts("South\n"); if(C_2C25() && D_95C6) { t_callback(); sound(0); C_2C25(); } /*spawn demons on verity island?*/ if( Party._x >= 0xe5 && Party._x < 0xea && Party._y >= 0xd4 && Party._y < 0xd9 ) C_27D9(); } } /*move West*/ C_2D44() { if(!C_2999(tile_west)) { w_Blocked(); return 0; } if(C_29EF(tile_west)) { w_SlowProgress(); return 1; } sound(0); if(CurMode == MOD_OUTDOORS) { C_28E9(); if(C_2A91(tile_west)) return 0; return 1; } Party._x --; D_959C.x = Party._x; if(D_959C.x <= 0x1f) { return 1; } C_2747(); return 0; } /*C_2DA9*/CMDDIR_Left() { if(Party._tile == TIL_18) { w_DriftOnly(); } else if(Party._tile == TIL_13 || Party._tile == TIL_12 || Party._tile == TIL_11) { Party._tile = TIL_10; u4_puts("Turn West!\n"); } else if(Party._tile == TIL_10) { u4_puts("Sail West!\n"); if(!C_2A38(tile_west)) { w_Blocked(); } else if(!C_2A5A(DIR_W)) { w_SlowProgress(); } else { C_28E9(); } } else { if(Party._tile == TIL_15) Party._tile = TIL_14; sound(0); u4_puts("West\n"); if(C_2D44() && D_95C6) { t_callback(); sound(0); C_2D44(); } } } /*move East*/ C_2E4F() { if(!C_2999(tile_east)) { w_Blocked(); return 0; } if(C_29EF(tile_east)) { w_SlowProgress(); return 1; } sound(0); if(CurMode == MOD_OUTDOORS) { C_2941(); if(Party._y == 0xe0 && Party._x == 0xdd) C_280A(); if(C_2A91(tile_east)) return 0; return 1; } Party._x ++; D_959C.x = Party._x; if(D_959C.x <= 0x1f) { return 1; } C_2747(); return 0; } /*C_2EC5*/CMDDIR_Right() { if(Party._tile == TIL_18) { w_DriftOnly(); } else if(Party._tile == TIL_13 || Party._tile == TIL_10 || Party._tile == TIL_11) { Party._tile = TIL_12; u4_puts("Turn East!\n"); } else if(Party._tile == TIL_12) { u4_puts("Sail East!\n"); if(!C_2A38(tile_east)) { w_Blocked(); } else if(!C_2A5A(DIR_E)) { w_SlowProgress(); } else { C_2941(); if(Party._y == 0xe0 && Party._x == 0xdd) C_280A(); } } else { if(Party._tile == TIL_14) Party._tile = TIL_15; sound(0); u4_puts("East\n"); if(C_2E4F() && D_95C6) { t_callback(); sound(0); C_2E4F(); } } }
411
0.712363
1
0.712363
game-dev
MEDIA
0.53427
game-dev
0.8445
1
0.8445
StellariumMC/zen
7,197
src/main/kotlin/xyz/meowing/zen/api/SlayerTracker.kt
package xyz.meowing.zen.api import xyz.meowing.zen.Zen import xyz.meowing.zen.Zen.Companion.mayorData import xyz.meowing.zen.api.EntityDetection.bossID import xyz.meowing.zen.config.ConfigDelegate import xyz.meowing.zen.events.* import xyz.meowing.zen.features.slayers.SlayerTimer import xyz.meowing.zen.utils.SimpleTimeMark import xyz.meowing.zen.utils.TickUtils import xyz.meowing.zen.utils.TimeUtils import xyz.meowing.zen.utils.TimeUtils.millis import xyz.meowing.zen.utils.Utils.removeFormatting import net.minecraft.entity.item.EntityArmorStand import net.minecraft.entity.monster.EntitySpider import kotlin.time.Duration import kotlin.time.Duration.Companion.milliseconds @Zen.Module object SlayerTracker { private val slayertimer by ConfigDelegate<Boolean>("slayertimer") private val slayerMobRegex = "(?<=☠\\s)[A-Za-z]+\\s[A-Za-z]+(?:\\s[IVX]+)?".toRegex() private val killRegex = " (?<kills>.*)/(?<target>.*) Kills".toRegex() private val tierXp = mapOf("I" to 5, "II" to 25, "III" to 100, "IV" to 500, "V" to 1500) private val serverTickCall = EventBus.register<TickEvent.Server>({ serverTicks++ }, false) private var slayerSpawnedAtTime = TimeUtils.zero private var currentMobKills = 0 private var isFightingBoss = false private var isSpider = false private var serverTicks = 0 private var totalCurrentPaused: Long = 0 var isPaused = false var pauseStart: SimpleTimeMark? = null var totalSessionPaused: Long = 0 var sessionBossKills = 0 var sessionStart = TimeUtils.zero var totalKillTime = Duration.ZERO var totalSpawnTime = Duration.ZERO var questStartedAtTime = TimeUtils.zero var mobLastKilledAt = TimeUtils.zero var bossType = "" var xpPerKill = 0 private fun startFightTimer() { slayerSpawnedAtTime = TimeUtils.now pauseStart = null isPaused = false totalCurrentPaused = 0 } private fun pauseSessionTimer() { if (pauseStart == null) { pauseStart = TimeUtils.now isPaused = true } } private fun resumeSessionTimer() { if(!isPaused || pauseStart == null) return totalSessionPaused += pauseStart!!.since.millis totalCurrentPaused += pauseStart!!.since.millis pauseStart = null isPaused = false } init { EventBus.register<TickEvent.Server> { if (pauseStart == null && mobLastKilledAt != TimeUtils.zero && mobLastKilledAt.since.inWholeSeconds >= 15 && !isFightingBoss ) { pauseSessionTimer() } } EventBus.register<SkyblockEvent.Slayer.QuestStart> { questStartedAtTime = TimeUtils.now } EventBus.register<SidebarUpdateEvent> { event -> event.lines.firstNotNullOfOrNull { killRegex.find(it) }?.let { match -> val killsInt = match.groupValues[1].toIntOrNull() ?: return@register if (killsInt != currentMobKills) { // Start the session timer if it's not already started if (sessionStart.isZero) sessionStart = TimeUtils.now if (questStartedAtTime.isZero) questStartedAtTime = TimeUtils.now mobLastKilledAt = TimeUtils.now currentMobKills = killsInt if (isPaused) { resumeSessionTimer() } } } } EventBus.register<SkyblockEvent.Slayer.Spawn> { _ -> if (!isFightingBoss && !isSpider) { isFightingBoss = true serverTicks = 0 serverTickCall.register() if (!questStartedAtTime.isZero) { val adjustedTime = (questStartedAtTime.since - totalCurrentPaused.milliseconds) if (slayertimer) SlayerTimer.sendBossSpawnMessage(adjustedTime) totalSpawnTime += adjustedTime } questStartedAtTime = TimeUtils.zero mobLastKilledAt = TimeUtils.now totalCurrentPaused = 0 resumeSessionTimer() startFightTimer() } } EventBus.register<EntityEvent.Join> { event -> TickUtils.scheduleServer(2) { if (bossID != null && event.entity.entityId == bossID!! + 1 && event.entity is EntityArmorStand) { val name = event.entity.name.removeFormatting() slayerMobRegex.find(name)?.let { matchResult -> bossType = matchResult.value xpPerKill = getBossXP(bossType) } } } } EventBus.register<SkyblockEvent.Slayer.Death> { event -> if (!isFightingBoss) return@register if (event.entity is EntitySpider && !isSpider) { isSpider = true return@register } val timeToKill = slayerSpawnedAtTime.since sessionBossKills++ totalKillTime += timeToKill if (slayertimer) { SlayerTimer.sendTimerMessage( "You killed your boss", timeToKill, serverTicks ) } resetBossTracker() } EventBus.register<WorldEvent.Change> { mobLastKilledAt = TimeUtils.zero } EventBus.register<SkyblockEvent.Slayer.Fail> { if (!isFightingBoss) return@register if (slayertimer) { SlayerTimer.sendTimerMessage( "Your boss killed you", slayerSpawnedAtTime.since, serverTicks ) } resetBossTracker() } EventBus.register<SkyblockEvent.Slayer.Cleanup> { resetBossTracker() } } private fun resetBossTracker() { slayerSpawnedAtTime = TimeUtils.zero pauseStart = null isFightingBoss = false isPaused = false isSpider = false serverTicks = 0 bossType = "" serverTickCall.unregister() totalCurrentPaused = 0 } private fun getBossXP(bossName: String): Int { val xp = when { bossName.endsWith(" V") -> tierXp["V"]!! bossName.endsWith(" IV") -> tierXp["IV"]!! bossName.endsWith(" III") -> tierXp["III"]!! bossName.endsWith(" II") -> tierXp["II"]!! bossName.endsWith(" I") -> tierXp["I"]!! else -> 0 } val isAatrox = mayorData?.mayor?.perks?.any { it.name == "Slayer XP Buff" } == true || mayorData?.mayor?.minister?.perks?.any { it.name == "Slayer XP Buff" } == true if (isAatrox) return (xp * 1.25).toInt() return xp } fun reset() { sessionBossKills = 0 sessionStart = TimeUtils.now totalKillTime = Duration.ZERO totalSpawnTime = Duration.ZERO totalSessionPaused = 0 } }
411
0.87026
1
0.87026
game-dev
MEDIA
0.774482
game-dev
0.95257
1
0.95257
Admer456/halflife-adm
14,992
external/SDL2/include/SDL2/SDL_scancode.h
/* Simple DirectMedia Layer Copyright (C) 1997-2013 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /** * \file SDL_scancode.h * * Defines keyboard scancodes. */ #ifndef _SDL_scancode_h #define _SDL_scancode_h #include "SDL_stdinc.h" /** * \brief The SDL keyboard scancode representation. * * Values of this type are used to represent keyboard keys, among other places * in the \link SDL_Keysym::scancode key.keysym.scancode \endlink field of the * SDL_Event structure. * * The values in this enumeration are based on the USB usage page standard: * http://www.usb.org/developers/devclass_docs/Hut1_12v2.pdf */ typedef enum { SDL_SCANCODE_UNKNOWN = 0, /** * \name Usage page 0x07 * * These values are from usage page 0x07 (USB keyboard page). */ /*@{*/ SDL_SCANCODE_A = 4, SDL_SCANCODE_B = 5, SDL_SCANCODE_C = 6, SDL_SCANCODE_D = 7, SDL_SCANCODE_E = 8, SDL_SCANCODE_F = 9, SDL_SCANCODE_G = 10, SDL_SCANCODE_H = 11, SDL_SCANCODE_I = 12, SDL_SCANCODE_J = 13, SDL_SCANCODE_K = 14, SDL_SCANCODE_L = 15, SDL_SCANCODE_M = 16, SDL_SCANCODE_N = 17, SDL_SCANCODE_O = 18, SDL_SCANCODE_P = 19, SDL_SCANCODE_Q = 20, SDL_SCANCODE_R = 21, SDL_SCANCODE_S = 22, SDL_SCANCODE_T = 23, SDL_SCANCODE_U = 24, SDL_SCANCODE_V = 25, SDL_SCANCODE_W = 26, SDL_SCANCODE_X = 27, SDL_SCANCODE_Y = 28, SDL_SCANCODE_Z = 29, SDL_SCANCODE_1 = 30, SDL_SCANCODE_2 = 31, SDL_SCANCODE_3 = 32, SDL_SCANCODE_4 = 33, SDL_SCANCODE_5 = 34, SDL_SCANCODE_6 = 35, SDL_SCANCODE_7 = 36, SDL_SCANCODE_8 = 37, SDL_SCANCODE_9 = 38, SDL_SCANCODE_0 = 39, SDL_SCANCODE_RETURN = 40, SDL_SCANCODE_ESCAPE = 41, SDL_SCANCODE_BACKSPACE = 42, SDL_SCANCODE_TAB = 43, SDL_SCANCODE_SPACE = 44, SDL_SCANCODE_MINUS = 45, SDL_SCANCODE_EQUALS = 46, SDL_SCANCODE_LEFTBRACKET = 47, SDL_SCANCODE_RIGHTBRACKET = 48, SDL_SCANCODE_BACKSLASH = 49, /**< Located at the lower left of the return * key on ISO keyboards and at the right end * of the QWERTY row on ANSI keyboards. * Produces REVERSE SOLIDUS (backslash) and * VERTICAL LINE in a US layout, REVERSE * SOLIDUS and VERTICAL LINE in a UK Mac * layout, NUMBER SIGN and TILDE in a UK * Windows layout, DOLLAR SIGN and POUND SIGN * in a Swiss German layout, NUMBER SIGN and * APOSTROPHE in a German layout, GRAVE * ACCENT and POUND SIGN in a French Mac * layout, and ASTERISK and MICRO SIGN in a * French Windows layout. */ SDL_SCANCODE_NONUSHASH = 50, /**< ISO USB keyboards actually use this code * instead of 49 for the same key, but all * OSes I've seen treat the two codes * identically. So, as an implementor, unless * your keyboard generates both of those * codes and your OS treats them differently, * you should generate SDL_SCANCODE_BACKSLASH * instead of this code. As a user, you * should not rely on this code because SDL * will never generate it with most (all?) * keyboards. */ SDL_SCANCODE_SEMICOLON = 51, SDL_SCANCODE_APOSTROPHE = 52, SDL_SCANCODE_GRAVE = 53, /**< Located in the top left corner (on both ANSI * and ISO keyboards). Produces GRAVE ACCENT and * TILDE in a US Windows layout and in US and UK * Mac layouts on ANSI keyboards, GRAVE ACCENT * and NOT SIGN in a UK Windows layout, SECTION * SIGN and PLUS-MINUS SIGN in US and UK Mac * layouts on ISO keyboards, SECTION SIGN and * DEGREE SIGN in a Swiss German layout (Mac: * only on ISO keyboards), CIRCUMFLEX ACCENT and * DEGREE SIGN in a German layout (Mac: only on * ISO keyboards), SUPERSCRIPT TWO and TILDE in a * French Windows layout, COMMERCIAL AT and * NUMBER SIGN in a French Mac layout on ISO * keyboards, and LESS-THAN SIGN and GREATER-THAN * SIGN in a Swiss German, German, or French Mac * layout on ANSI keyboards. */ SDL_SCANCODE_COMMA = 54, SDL_SCANCODE_PERIOD = 55, SDL_SCANCODE_SLASH = 56, SDL_SCANCODE_CAPSLOCK = 57, SDL_SCANCODE_F1 = 58, SDL_SCANCODE_F2 = 59, SDL_SCANCODE_F3 = 60, SDL_SCANCODE_F4 = 61, SDL_SCANCODE_F5 = 62, SDL_SCANCODE_F6 = 63, SDL_SCANCODE_F7 = 64, SDL_SCANCODE_F8 = 65, SDL_SCANCODE_F9 = 66, SDL_SCANCODE_F10 = 67, SDL_SCANCODE_F11 = 68, SDL_SCANCODE_F12 = 69, SDL_SCANCODE_PRINTSCREEN = 70, SDL_SCANCODE_SCROLLLOCK = 71, SDL_SCANCODE_PAUSE = 72, SDL_SCANCODE_INSERT = 73, /**< insert on PC, help on some Mac keyboards (but does send code 73, not 117) */ SDL_SCANCODE_HOME = 74, SDL_SCANCODE_PAGEUP = 75, SDL_SCANCODE_DELETE = 76, SDL_SCANCODE_END = 77, SDL_SCANCODE_PAGEDOWN = 78, SDL_SCANCODE_RIGHT = 79, SDL_SCANCODE_LEFT = 80, SDL_SCANCODE_DOWN = 81, SDL_SCANCODE_UP = 82, SDL_SCANCODE_NUMLOCKCLEAR = 83, /**< num lock on PC, clear on Mac keyboards */ SDL_SCANCODE_KP_DIVIDE = 84, SDL_SCANCODE_KP_MULTIPLY = 85, SDL_SCANCODE_KP_MINUS = 86, SDL_SCANCODE_KP_PLUS = 87, SDL_SCANCODE_KP_ENTER = 88, SDL_SCANCODE_KP_1 = 89, SDL_SCANCODE_KP_2 = 90, SDL_SCANCODE_KP_3 = 91, SDL_SCANCODE_KP_4 = 92, SDL_SCANCODE_KP_5 = 93, SDL_SCANCODE_KP_6 = 94, SDL_SCANCODE_KP_7 = 95, SDL_SCANCODE_KP_8 = 96, SDL_SCANCODE_KP_9 = 97, SDL_SCANCODE_KP_0 = 98, SDL_SCANCODE_KP_PERIOD = 99, SDL_SCANCODE_NONUSBACKSLASH = 100, /**< This is the additional key that ISO * keyboards have over ANSI ones, * located between left shift and Y. * Produces GRAVE ACCENT and TILDE in a * US or UK Mac layout, REVERSE SOLIDUS * (backslash) and VERTICAL LINE in a * US or UK Windows layout, and * LESS-THAN SIGN and GREATER-THAN SIGN * in a Swiss German, German, or French * layout. */ SDL_SCANCODE_APPLICATION = 101, /**< windows contextual menu, compose */ SDL_SCANCODE_POWER = 102, /**< The USB document says this is a status flag, * not a physical key - but some Mac keyboards * do have a power key. */ SDL_SCANCODE_KP_EQUALS = 103, SDL_SCANCODE_F13 = 104, SDL_SCANCODE_F14 = 105, SDL_SCANCODE_F15 = 106, SDL_SCANCODE_F16 = 107, SDL_SCANCODE_F17 = 108, SDL_SCANCODE_F18 = 109, SDL_SCANCODE_F19 = 110, SDL_SCANCODE_F20 = 111, SDL_SCANCODE_F21 = 112, SDL_SCANCODE_F22 = 113, SDL_SCANCODE_F23 = 114, SDL_SCANCODE_F24 = 115, SDL_SCANCODE_EXECUTE = 116, SDL_SCANCODE_HELP = 117, SDL_SCANCODE_MENU = 118, SDL_SCANCODE_SELECT = 119, SDL_SCANCODE_STOP = 120, SDL_SCANCODE_AGAIN = 121, /**< redo */ SDL_SCANCODE_UNDO = 122, SDL_SCANCODE_CUT = 123, SDL_SCANCODE_COPY = 124, SDL_SCANCODE_PASTE = 125, SDL_SCANCODE_FIND = 126, SDL_SCANCODE_MUTE = 127, SDL_SCANCODE_VOLUMEUP = 128, SDL_SCANCODE_VOLUMEDOWN = 129, /* not sure whether there's a reason to enable these */ /* SDL_SCANCODE_LOCKINGCAPSLOCK = 130, */ /* SDL_SCANCODE_LOCKINGNUMLOCK = 131, */ /* SDL_SCANCODE_LOCKINGSCROLLLOCK = 132, */ SDL_SCANCODE_KP_COMMA = 133, SDL_SCANCODE_KP_EQUALSAS400 = 134, SDL_SCANCODE_INTERNATIONAL1 = 135, /**< used on Asian keyboards, see footnotes in USB doc */ SDL_SCANCODE_INTERNATIONAL2 = 136, SDL_SCANCODE_INTERNATIONAL3 = 137, /**< Yen */ SDL_SCANCODE_INTERNATIONAL4 = 138, SDL_SCANCODE_INTERNATIONAL5 = 139, SDL_SCANCODE_INTERNATIONAL6 = 140, SDL_SCANCODE_INTERNATIONAL7 = 141, SDL_SCANCODE_INTERNATIONAL8 = 142, SDL_SCANCODE_INTERNATIONAL9 = 143, SDL_SCANCODE_LANG1 = 144, /**< Hangul/English toggle */ SDL_SCANCODE_LANG2 = 145, /**< Hanja conversion */ SDL_SCANCODE_LANG3 = 146, /**< Katakana */ SDL_SCANCODE_LANG4 = 147, /**< Hiragana */ SDL_SCANCODE_LANG5 = 148, /**< Zenkaku/Hankaku */ SDL_SCANCODE_LANG6 = 149, /**< reserved */ SDL_SCANCODE_LANG7 = 150, /**< reserved */ SDL_SCANCODE_LANG8 = 151, /**< reserved */ SDL_SCANCODE_LANG9 = 152, /**< reserved */ SDL_SCANCODE_ALTERASE = 153, /**< Erase-Eaze */ SDL_SCANCODE_SYSREQ = 154, SDL_SCANCODE_CANCEL = 155, SDL_SCANCODE_CLEAR = 156, SDL_SCANCODE_PRIOR = 157, SDL_SCANCODE_RETURN2 = 158, SDL_SCANCODE_SEPARATOR = 159, SDL_SCANCODE_OUT = 160, SDL_SCANCODE_OPER = 161, SDL_SCANCODE_CLEARAGAIN = 162, SDL_SCANCODE_CRSEL = 163, SDL_SCANCODE_EXSEL = 164, SDL_SCANCODE_KP_00 = 176, SDL_SCANCODE_KP_000 = 177, SDL_SCANCODE_THOUSANDSSEPARATOR = 178, SDL_SCANCODE_DECIMALSEPARATOR = 179, SDL_SCANCODE_CURRENCYUNIT = 180, SDL_SCANCODE_CURRENCYSUBUNIT = 181, SDL_SCANCODE_KP_LEFTPAREN = 182, SDL_SCANCODE_KP_RIGHTPAREN = 183, SDL_SCANCODE_KP_LEFTBRACE = 184, SDL_SCANCODE_KP_RIGHTBRACE = 185, SDL_SCANCODE_KP_TAB = 186, SDL_SCANCODE_KP_BACKSPACE = 187, SDL_SCANCODE_KP_A = 188, SDL_SCANCODE_KP_B = 189, SDL_SCANCODE_KP_C = 190, SDL_SCANCODE_KP_D = 191, SDL_SCANCODE_KP_E = 192, SDL_SCANCODE_KP_F = 193, SDL_SCANCODE_KP_XOR = 194, SDL_SCANCODE_KP_POWER = 195, SDL_SCANCODE_KP_PERCENT = 196, SDL_SCANCODE_KP_LESS = 197, SDL_SCANCODE_KP_GREATER = 198, SDL_SCANCODE_KP_AMPERSAND = 199, SDL_SCANCODE_KP_DBLAMPERSAND = 200, SDL_SCANCODE_KP_VERTICALBAR = 201, SDL_SCANCODE_KP_DBLVERTICALBAR = 202, SDL_SCANCODE_KP_COLON = 203, SDL_SCANCODE_KP_HASH = 204, SDL_SCANCODE_KP_SPACE = 205, SDL_SCANCODE_KP_AT = 206, SDL_SCANCODE_KP_EXCLAM = 207, SDL_SCANCODE_KP_MEMSTORE = 208, SDL_SCANCODE_KP_MEMRECALL = 209, SDL_SCANCODE_KP_MEMCLEAR = 210, SDL_SCANCODE_KP_MEMADD = 211, SDL_SCANCODE_KP_MEMSUBTRACT = 212, SDL_SCANCODE_KP_MEMMULTIPLY = 213, SDL_SCANCODE_KP_MEMDIVIDE = 214, SDL_SCANCODE_KP_PLUSMINUS = 215, SDL_SCANCODE_KP_CLEAR = 216, SDL_SCANCODE_KP_CLEARENTRY = 217, SDL_SCANCODE_KP_BINARY = 218, SDL_SCANCODE_KP_OCTAL = 219, SDL_SCANCODE_KP_DECIMAL = 220, SDL_SCANCODE_KP_HEXADECIMAL = 221, SDL_SCANCODE_LCTRL = 224, SDL_SCANCODE_LSHIFT = 225, SDL_SCANCODE_LALT = 226, /**< alt, option */ SDL_SCANCODE_LGUI = 227, /**< windows, command (apple), meta */ SDL_SCANCODE_RCTRL = 228, SDL_SCANCODE_RSHIFT = 229, SDL_SCANCODE_RALT = 230, /**< alt gr, option */ SDL_SCANCODE_RGUI = 231, /**< windows, command (apple), meta */ SDL_SCANCODE_MODE = 257, /**< I'm not sure if this is really not covered * by any of the above, but since there's a * special KMOD_MODE for it I'm adding it here */ /*@}*//*Usage page 0x07*/ /** * \name Usage page 0x0C * * These values are mapped from usage page 0x0C (USB consumer page). */ /*@{*/ SDL_SCANCODE_AUDIONEXT = 258, SDL_SCANCODE_AUDIOPREV = 259, SDL_SCANCODE_AUDIOSTOP = 260, SDL_SCANCODE_AUDIOPLAY = 261, SDL_SCANCODE_AUDIOMUTE = 262, SDL_SCANCODE_MEDIASELECT = 263, SDL_SCANCODE_WWW = 264, SDL_SCANCODE_MAIL = 265, SDL_SCANCODE_CALCULATOR = 266, SDL_SCANCODE_COMPUTER = 267, SDL_SCANCODE_AC_SEARCH = 268, SDL_SCANCODE_AC_HOME = 269, SDL_SCANCODE_AC_BACK = 270, SDL_SCANCODE_AC_FORWARD = 271, SDL_SCANCODE_AC_STOP = 272, SDL_SCANCODE_AC_REFRESH = 273, SDL_SCANCODE_AC_BOOKMARKS = 274, /*@}*//*Usage page 0x0C*/ /** * \name Walther keys * * These are values that Christian Walther added (for mac keyboard?). */ /*@{*/ SDL_SCANCODE_BRIGHTNESSDOWN = 275, SDL_SCANCODE_BRIGHTNESSUP = 276, SDL_SCANCODE_DISPLAYSWITCH = 277, /**< display mirroring/dual display switch, video mode switch */ SDL_SCANCODE_KBDILLUMTOGGLE = 278, SDL_SCANCODE_KBDILLUMDOWN = 279, SDL_SCANCODE_KBDILLUMUP = 280, SDL_SCANCODE_EJECT = 281, SDL_SCANCODE_SLEEP = 282, SDL_SCANCODE_APP1 = 283, SDL_SCANCODE_APP2 = 284, /*@}*//*Walther keys*/ /* Add any other keys here. */ SDL_NUM_SCANCODES = 512 /**< not a key, just marks the number of scancodes for array bounds */ } SDL_Scancode; #endif /* _SDL_scancode_h */ /* vi: set ts=4 sw=4 expandtab: */
411
0.746558
1
0.746558
game-dev
MEDIA
0.472339
game-dev
0.571321
1
0.571321
open-gunz/ogz-source
4,519
src/MatchServer/MMatchServer_Admin.cpp
#include "stdafx.h" #include "MMatchServer.h" #include "MSharedCommandTable.h" #include "MErrorTable.h" #include "MBlobArray.h" #include "MObject.h" #include "MMatchObject.h" #include "MMatchItem.h" #include "MAgentObject.h" #include "MMatchNotify.h" #include "MMatchObjCache.h" #include "MMatchStage.h" #include "MMatchTransDataType.h" #include "MMatchFormula.h" #include "MMatchConfig.h" #include "MCommandCommunicator.h" #include "MMatchShop.h" #include "MMatchTransDataType.h" #include "MDebug.h" #include "MMatchAuth.h" #include "MMatchStatus.h" #include "MAsyncDBJob.h" #include "MMatchTransDataType.h" #include "MMatchAntiHack.h" void MMatchServer::OnAdminTerminal(const MUID& uidAdmin, const char* szText) { MMatchObject* pObj = GetObject(uidAdmin); if (pObj == NULL) return; if (!IsAdminGrade(pObj)) { return; } char szOut[32768]; szOut[0] = 0; if (m_Admin.Execute(uidAdmin, szText)) { MCommand* pNew = CreateCommand(MC_ADMIN_TERMINAL, MUID(0,0)); pNew->AddParameter(new MCmdParamUID(MUID(0,0))); pNew->AddParameter(new MCmdParamStr(szOut)); RouteToListener(pObj, pNew); } } void MMatchServer::OnAdminAnnounce(const MUID& uidAdmin, const char* szChat, u32 nType) { MMatchObject* pObj = GetObject(uidAdmin); if (pObj == NULL) return; if (!IsAdminGrade(pObj)) { return; } char szMsg[256]; strcpy_safe(szMsg, szChat); MCommand* pCmd = CreateCommand(MC_ADMIN_ANNOUNCE, MUID(0,0)); pCmd->AddParameter(new MCmdParamUID(uidAdmin)); pCmd->AddParameter(new MCmdParamStr(szMsg)); pCmd->AddParameter(new MCmdParamUInt(nType)); RouteToAllClient(pCmd); } void MMatchServer::OnAdminRequestServerInfo(const MUID& uidAdmin) { MMatchObject* pObj = GetObject(uidAdmin); if (pObj == NULL) return; if (!IsAdminGrade(pObj)) { return; } } void MMatchServer::OnAdminServerHalt(const MUID& uidAdmin) { MMatchObject* pObj = GetObject(uidAdmin); if (pObj == NULL) return; MMatchUserGradeID nGrade = pObj->GetAccountInfo()->m_nUGrade; if ((nGrade != MMUG_ADMIN) && (nGrade != MMUG_DEVELOPER)) return; m_MatchShutdown.Start(GetGlobalClockCount()); } void MMatchServer::OnAdminServerHalt() { m_MatchShutdown.Start(GetGlobalClockCount()); } void MMatchServer::OnAdminRequestBanPlayer(const MUID& uidAdmin, const char* szPlayer) { MMatchObject* pObj = GetObject(uidAdmin); if (pObj == NULL) return; if (!IsAdminGrade(pObj)) { return; } int nRet = MOK; if ((strlen(szPlayer)) < 2) return; MMatchObject* pTargetObj = GetPlayerByName(szPlayer); if (pTargetObj != NULL) { DisconnectObject(pTargetObj->GetUID()); GetDBMgr()->BanPlayer(pTargetObj->GetAccountInfo()->m_nAID, "", 0); } else { nRet = MERR_NO_TARGET; } MCommand* pNew = CreateCommand(MC_ADMIN_RESPONSE_BAN_PLAYER, MUID(0,0)); pNew->AddParameter(new MCmdParamInt(nRet)); RouteToListener(pObj, pNew); } void MMatchServer::OnAdminRequestUpdateAccountUGrade(const MUID& uidAdmin, const char* szPlayer) { MMatchObject* pObj = GetObject(uidAdmin); if (pObj == NULL) return; if (!IsAdminGrade(pObj)) { return; } int nRet = MOK; if ((strlen(szPlayer)) < 2) return; MMatchObject* pTargetObj = GetPlayerByName(szPlayer); if (pTargetObj == NULL) return; } void MMatchServer::OnAdminPingToAll(const MUID& uidAdmin) { MMatchObject* pObj = GetObject(uidAdmin); if (pObj == NULL) return; if (!IsAdminGrade(pObj)) { return; } MCommand* pNew = CreateCommand(MC_NET_PING, MUID(0,0)); pNew->AddParameter(new MCmdParamUInt(static_cast<u32>(GetGlobalClockCount()))); RouteToAllConnection(pNew); } void MMatchServer::OnAdminRequestSwitchLadderGame(const MUID& uidAdmin, const bool bEnabled) { MMatchObject* pObj = GetObject(uidAdmin); if (!IsEnabledObject(pObj)) return; if (!IsAdminGrade(pObj)) { return; } MGetServerConfig()->SetEnabledCreateLadderGame(bEnabled); char szMsg[256] = "Ǿϴ."; Announce(pObj, szMsg); } void MMatchServer::OnAdminHide(const MUID& uidAdmin) { MMatchObject* pObj = GetObject(uidAdmin); if (!IsEnabledObject(pObj)) return; if (!IsAdminGrade(pObj)) { return; } if (pObj->CheckPlayerFlags(MTD_PlayerFlags_AdminHide)) { pObj->SetPlayerFlag(MTD_PlayerFlags_AdminHide, false); Announce(pObj, "Now Revealing..."); } else { pObj->SetPlayerFlag(MTD_PlayerFlags_AdminHide, true); Announce(pObj, "Now Hiding..."); } } void MMatchServer::OnAdminResetAllHackingBlock( const MUID& uidAdmin ) { MMatchObject* pObj = GetObject( uidAdmin ); if( (0 != pObj) && IsAdminGrade(pObj) ) { GetDBMgr()->AdminResetAllHackingBlock(); } }
411
0.643153
1
0.643153
game-dev
MEDIA
0.563968
game-dev
0.721216
1
0.721216
hugerte/hugerte
2,231
modules/alloy/src/main/ts/ephox/alloy/behaviour/sandboxing/SandboxingTypes.ts
import { Optional } from '@ephox/katamari'; import { SugarElement } from '@ephox/sugar'; import * as Behaviour from '../../api/behaviour/Behaviour'; import { AlloyComponent } from '../../api/component/ComponentApi'; import { AlloySpec } from '../../api/component/SpecTypes'; import { BehaviourState } from '../common/BehaviourState'; export interface SandboxingBehaviour extends Behaviour.AlloyBehaviour<SandboxingConfigSpec, SandboxingConfig> { config: (config: SandboxingConfigSpec) => Behaviour.NamedConfiguredBehaviour<SandboxingConfigSpec, SandboxingConfig>; cloak: (sandbox: AlloyComponent) => void; decloak: (sandbox: AlloyComponent) => void; open: (sandbox: AlloyComponent, thing: AlloySpec) => AlloyComponent; openWhileCloaked: (sandbox: AlloyComponent, thing: AlloySpec, transaction: () => void) => AlloyComponent; close: (sandbox: AlloyComponent) => void; isOpen: (sandbox: AlloyComponent) => boolean; isPartOf: (sandbox: AlloyComponent, candidate: SugarElement<Node>) => boolean; getState: (sandbox: AlloyComponent) => Optional<AlloyComponent>; setContent: (sandbox: AlloyComponent, thing: AlloySpec) => Optional<AlloyComponent>; closeSandbox: (sandbox: AlloyComponent) => void; } export interface SandboxingConfigSpec extends Behaviour.BehaviourConfigSpec { getAttachPoint: (sandbox: AlloyComponent) => AlloyComponent; isPartOf: (sandbox: AlloyComponent, data: AlloyComponent, queryElem: SugarElement<Node>) => boolean; onOpen?: (sandbox: AlloyComponent, menu: AlloyComponent) => void; onClose?: (sandbox: AlloyComponent, menu: AlloyComponent) => void; cloakVisibilityAttr?: string; } export interface SandboxingConfig extends Behaviour.BehaviourConfigDetail { cloakVisibilityAttr: string; getAttachPoint: (sandbox: AlloyComponent) => AlloyComponent; onOpen: (sandbox: AlloyComponent, thing: AlloyComponent) => void; onClose: (sandbox: AlloyComponent, thing: AlloyComponent) => void; isPartOf: (sandbox: AlloyComponent, data: AlloyComponent, queryElem: SugarElement<Node>) => boolean; } export interface SandboxingState extends BehaviourState { get: () => Optional<AlloyComponent>; set: (comp: AlloyComponent) => void; isOpen: () => boolean; clear: () => void; }
411
0.73954
1
0.73954
game-dev
MEDIA
0.840657
game-dev
0.545427
1
0.545427
MethanePowered/MethaneKit
3,661
Apps/08-ConsoleCompute/ConsoleApp.h
/****************************************************************************** Copyright 2023 Evgeny Gorodetskiy Licensed under the Apache License, Version 2.0 (the "License"), you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ******************************************************************************* FILE: ConsoleApp.h Console UI application base class implemented using FTXUI framework ******************************************************************************/ #pragma once #include <Methane/Data/Types.h> #include <ftxui/component/component.hpp> #include <ftxui/component/event.hpp> #include <ftxui/component/screen_interactive.hpp> #include <ftxui/dom/elements.hpp> #include <mutex> #include <atomic> namespace Methane::Tutorials { namespace data = Methane::Data; class ConsoleApp { public: ConsoleApp() = default; virtual ~ConsoleApp() = default; const data::FrameSize& GetFieldSize() const { return m_field_size; } const data::FrameRect& GetVisibleFrameRect() const { return m_frame_rect; } double GetInitialCellsRatio() const { return static_cast<double>(m_initial_cells_percent) / 100.0; } bool IsScreenRefreshEnabled() const { return m_screen_refresh_enabled; } void ToggleScreenRefresh(); // ConsoleApp virtual interface virtual int Run(); virtual std::string_view GetGraphicsApiName() const = 0; virtual const std::string& GetComputeDeviceName() const = 0; virtual const std::vector<std::string>& GetComputeDeviceNames() const = 0; virtual uint32_t GetFramesCountPerSecond() const = 0; virtual uint32_t GetVisibleCellsCount() const = 0; protected: virtual void Init() = 0; virtual void Release() = 0; virtual void Compute() = 0; virtual void Present(ftxui::Canvas& canvas) = 0; virtual void Restart() = 0; virtual void ResetRules() = 0; int GetComputeDeviceIndex() const { return m_compute_device_index; } int GetGameRuleIndex() const { return m_game_rule_index; } std::mutex& GetScreenRefreshMutex() { return m_screen_refresh_mutex; } void InitUserInterface(); private: void UpdateFrameSize(int width, int height); bool HandleInputEvent(ftxui::Event& e); ftxui::ScreenInteractive m_screen{ ftxui::ScreenInteractive::Fullscreen() }; ftxui::RadioboxOption m_compute_device_option{ ftxui::RadioboxOption::Simple() }; ftxui::RadioboxOption m_game_rule_option{ ftxui::RadioboxOption::Simple() }; ftxui::Component m_root; std::mutex m_screen_refresh_mutex; std::atomic<bool> m_screen_refresh_enabled{ true }; bool m_30fps_screen_refresh_limit_enabled{ true }; int m_compute_device_index = 0; int m_game_rule_index = 0; data::FrameSize m_field_size{ 2048U, 2048U }; data::FrameRect m_frame_rect; std::optional<data::Point2I> m_mouse_pressed_pos; std::optional<data::Point2I> m_frame_pressed_pos; int m_initial_cells_percent = 50U; }; } // namespace Methane::Tutorials
411
0.909272
1
0.909272
game-dev
MEDIA
0.304903
game-dev
0.555993
1
0.555993
ChengF3ng233/Aluminium
4,677
src/main/java/net/minecraft/entity/monster/EntitySnowman.java
package net.minecraft.entity.monster; import net.minecraft.block.material.Material; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.IRangedAttackMob; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.*; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.projectile.EntitySnowball; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.pathfinding.PathNavigateGround; import net.minecraft.util.BlockPos; import net.minecraft.util.DamageSource; import net.minecraft.util.MathHelper; import net.minecraft.world.World; public class EntitySnowman extends EntityGolem implements IRangedAttackMob { public EntitySnowman(World worldIn) { super(worldIn); this.setSize(0.7F, 1.9F); ((PathNavigateGround) this.getNavigator()).setAvoidsWater(true); this.tasks.addTask(1, new EntityAIArrowAttack(this, 1.25D, 20, 10.0F)); this.tasks.addTask(2, new EntityAIWander(this, 1.0D)); this.tasks.addTask(3, new EntityAIWatchClosest(this, EntityPlayer.class, 6.0F)); this.tasks.addTask(4, new EntityAILookIdle(this)); this.targetTasks.addTask(1, new EntityAINearestAttackableTarget(this, EntityLiving.class, 10, true, false, IMob.mobSelector)); } protected void applyEntityAttributes() { super.applyEntityAttributes(); this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(4.0D); this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.20000000298023224D); } /** * Called frequently so the entity can update its state every tick as required. For example, zombies and skeletons * use this to react to sunlight and start to burn. */ public void onLivingUpdate() { super.onLivingUpdate(); if (!this.worldObj.isRemote) { int i = MathHelper.floor_double(this.posX); int j = MathHelper.floor_double(this.posY); int k = MathHelper.floor_double(this.posZ); if (this.isWet()) { this.attackEntityFrom(DamageSource.drown, 1.0F); } if (this.worldObj.getBiomeGenForCoords(new BlockPos(i, 0, k)).getFloatTemperature(new BlockPos(i, j, k)) > 1.0F) { this.attackEntityFrom(DamageSource.onFire, 1.0F); } for (int l = 0; l < 4; ++l) { i = MathHelper.floor_double(this.posX + (double) ((float) (l % 2 * 2 - 1) * 0.25F)); j = MathHelper.floor_double(this.posY); k = MathHelper.floor_double(this.posZ + (double) ((float) (l / 2 % 2 * 2 - 1) * 0.25F)); BlockPos blockpos = new BlockPos(i, j, k); if (this.worldObj.getBlockState(blockpos).getBlock().getMaterial() == Material.air && this.worldObj.getBiomeGenForCoords(new BlockPos(i, 0, k)).getFloatTemperature(blockpos) < 0.8F && Blocks.snow_layer.canPlaceBlockAt(this.worldObj, blockpos)) { this.worldObj.setBlockState(blockpos, Blocks.snow_layer.getDefaultState()); } } } } protected Item getDropItem() { return Items.snowball; } /** * Drop 0-2 items of this living's type * * @param wasRecentlyHit true if this this entity was recently hit by appropriate entity (generally only if player * or tameable) * @param lootingModifier level of enchanment to be applied to this drop */ protected void dropFewItems(boolean wasRecentlyHit, int lootingModifier) { int i = this.rand.nextInt(16); for (int j = 0; j < i; ++j) { this.dropItem(Items.snowball, 1); } } /** * Attack the specified entity using a ranged attack. */ public void attackEntityWithRangedAttack(EntityLivingBase target, float p_82196_2_) { EntitySnowball entitysnowball = new EntitySnowball(this.worldObj, this); double d0 = target.posY + (double) target.getEyeHeight() - 1.100000023841858D; double d1 = target.posX - this.posX; double d2 = d0 - entitysnowball.posY; double d3 = target.posZ - this.posZ; float f = MathHelper.sqrt_double(d1 * d1 + d3 * d3) * 0.2F; entitysnowball.setThrowableHeading(d1, d2 + (double) f, d3, 1.6F, 12.0F); this.playSound("random.bow", 1.0F, 1.0F / (this.getRNG().nextFloat() * 0.4F + 0.8F)); this.worldObj.spawnEntityInWorld(entitysnowball); } public float getEyeHeight() { return 1.7F; } }
411
0.731001
1
0.731001
game-dev
MEDIA
0.995158
game-dev
0.94231
1
0.94231
Xiao-MoMi/Custom-Crops
15,219
api/src/main/java/net/momirealms/customcrops/api/action/AbstractActionManager.java
/* * Copyright (C) <2024> <XiaoMoMi> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package net.momirealms.customcrops.api.action; import dev.dejvokep.boostedyaml.block.implementation.Section; import net.momirealms.customcrops.api.BukkitCustomCropsPlugin; import net.momirealms.customcrops.api.action.builtin.*; import net.momirealms.customcrops.api.misc.value.MathValue; import net.momirealms.customcrops.common.util.ClassUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public abstract class AbstractActionManager<T> implements ActionManager<T> { protected final BukkitCustomCropsPlugin plugin; private final HashMap<String, ActionFactory<T>> actionFactoryMap = new HashMap<>(); private static final String EXPANSION_FOLDER = "expansions/action"; public AbstractActionManager(BukkitCustomCropsPlugin plugin) { this.plugin = plugin; this.registerBuiltInActions(); } protected void registerBuiltInActions() { this.registerCommandAction(); this.registerBroadcastAction(); this.registerConsumeWater(); this.registerNearbyMessage(); this.registerNearbyActionBar(); this.registerNearbyTitle(); this.registerParticleAction(); this.registerQualityCropsAction(); this.registerDropItemsAction(); this.registerLegacyDropItemsAction(); this.registerFakeItemAction(); this.registerHologramAction(); this.registerPlantAction(); this.registerBreakAction(); this.registerSpawnEntityAction(); this.registerVariationAction(); } @Override public boolean registerAction(ActionFactory<T> actionFactory, String... types) { for (String type : types) { if (this.actionFactoryMap.containsKey(type)) return false; } for (String type : types) { this.actionFactoryMap.put(type, actionFactory); } return true; } @Override public boolean unregisterAction(String type) { return this.actionFactoryMap.remove(type) != null; } @Override public boolean hasAction(@NotNull String type) { return actionFactoryMap.containsKey(type); } @Nullable @Override public ActionFactory<T> getActionFactory(@NotNull String type) { return actionFactoryMap.get(type); } @Override public Action<T> parseAction(Section section) { if (section == null) return Action.empty(); ActionFactory<T> factory = getActionFactory(section.getString("type")); if (factory == null) { plugin.getPluginLogger().warn("Action type: " + section.getString("type") + " doesn't exist."); return Action.empty(); } return factory.process(section.get("value"), section.contains("chance") ? MathValue.auto(section.get("chance")) : MathValue.plain(1d)); } @NotNull @Override @SuppressWarnings("unchecked") public Action<T>[] parseActions(Section section) { ArrayList<Action<T>> actionList = new ArrayList<>(); if (section != null) for (Map.Entry<String, Object> entry : section.getStringRouteMappedValues(false).entrySet()) { if (entry.getValue() instanceof Section innerSection) { Action<T> action = parseAction(innerSection); if (action != null) actionList.add(action); } } return actionList.toArray(new Action[0]); } @Override public Action<T> parseAction(@NotNull String type, @NotNull Object args) { ActionFactory<T> factory = getActionFactory(type); if (factory == null) { plugin.getPluginLogger().warn("Action type: " + type + " doesn't exist."); return Action.empty(); } return factory.process(args, MathValue.plain(1)); } @SuppressWarnings({"ResultOfMethodCallIgnored", "unchecked"}) protected void loadExpansions(Class<T> tClass) { File expansionFolder = new File(plugin.getDataFolder(), EXPANSION_FOLDER); if (!expansionFolder.exists()) expansionFolder.mkdirs(); List<Class<? extends ActionExpansion<T>>> classes = new ArrayList<>(); File[] expansionJars = expansionFolder.listFiles(); if (expansionJars == null) return; for (File expansionJar : expansionJars) { if (expansionJar.getName().endsWith(".jar")) { try { Class<? extends ActionExpansion<T>> expansionClass = (Class<? extends ActionExpansion<T>>) ClassUtils.findClass(expansionJar, ActionExpansion.class, tClass); classes.add(expansionClass); } catch (IOException | ClassNotFoundException e) { plugin.getPluginLogger().warn("Failed to load expansion: " + expansionJar.getName(), e); } } } try { for (Class<? extends ActionExpansion<T>> expansionClass : classes) { ActionExpansion<T> expansion = expansionClass.getDeclaredConstructor().newInstance(); unregisterAction(expansion.getActionType()); registerAction(expansion.getActionFactory(), expansion.getActionType()); plugin.getPluginLogger().info("Loaded action expansion: " + expansion.getActionType() + "[" + expansion.getVersion() + "]" + " by " + expansion.getAuthor() ); } } catch (InvocationTargetException | InstantiationException | IllegalAccessException | NoSuchMethodException e) { plugin.getPluginLogger().warn("Error occurred when creating expansion instance.", e); } } protected void registerConsumeWater() { registerAction((args, chance) -> { if (args instanceof Section section) { return new ActionConsumeWater<>(plugin, section, chance); } else { plugin.getPluginLogger().warn("Invalid value type: " + args.getClass().getSimpleName() + " found at consume-water action which should be Section"); return Action.empty(); } }, "consume-water"); } protected void registerBroadcastAction() { registerAction((args, chance) -> new ActionBroadcast<>(plugin, args, chance), "broadcast"); } protected void registerNearbyMessage() { registerAction((args, chance) -> { if (args instanceof Section section) { return new ActionMessageNearby<>(plugin, section, chance); } else { plugin.getPluginLogger().warn("Invalid value type: " + args.getClass().getSimpleName() + " found at message-nearby action which should be Section"); return Action.empty(); } }, "message-nearby"); } protected void registerNearbyActionBar() { registerAction((args, chance) -> { if (args instanceof Section section) { return new ActionActionbarNearby<>(plugin, section, chance); } else { plugin.getPluginLogger().warn("Invalid value type: " + args.getClass().getSimpleName() + " found at actionbar-nearby action which should be Section"); return Action.empty(); } }, "actionbar-nearby"); } protected void registerCommandAction() { registerAction((args, chance) -> new ActionCommand<>(plugin, args, chance), "command"); registerAction((args, chance) -> new ActionRandomCommand<>(plugin, args, chance), "random-command"); registerAction((args, chance) -> { if (args instanceof Section section) { return new ActionCommandNearby<>(plugin, section, chance); } else { plugin.getPluginLogger().warn("Invalid value type: " + args.getClass().getSimpleName() + " found at command-nearby action which should be Section"); return Action.empty(); } }, "command-nearby"); } protected void registerBundleAction(Class<T> tClass) { registerAction((args, chance) -> new ActionChain<>(plugin, this, args, chance), "chain"); registerAction((args, chance) -> new ActionDelay<>(plugin, this, args, chance), "delay"); registerAction((args, chance) -> new ActionTimer<>(plugin, this, args, chance), "timer"); registerAction((args, chance) -> { if (args instanceof Section section) { return new ActionConditional<>(plugin, this, tClass, section, chance); } else { plugin.getPluginLogger().warn("Invalid value type: " + args.getClass().getSimpleName() + " found at conditional action which is expected to be `Section`"); return Action.empty(); } }, "conditional"); registerAction((args, chance) -> { if (args instanceof Section section) { return new ActionPriority<>(plugin, this, tClass, section, chance); } else { plugin.getPluginLogger().warn("Invalid value type: " + args.getClass().getSimpleName() + " found at priority action which is expected to be `Section`"); return Action.empty(); } }, "priority"); } protected void registerNearbyTitle() { registerAction((args, chance) -> { if (args instanceof Section section) { return new ActionTitleNearby<>(plugin, section, chance); } else { plugin.getPluginLogger().warn("Invalid value type: " + args.getClass().getSimpleName() + " found at title-nearby action which is expected to be `Section`"); return Action.empty(); } }, "title-nearby"); } protected void registerParticleAction() { registerAction((args, chance) -> { if (args instanceof Section section) { return new ActionParticle<>(plugin, section, chance); } else { plugin.getPluginLogger().warn("Invalid value type: " + args.getClass().getSimpleName() + " found at particle action which is expected to be `Section`"); return Action.empty(); } }, "particle"); } protected void registerQualityCropsAction() { registerAction((args, chance) -> { if (args instanceof Section section) { return new ActionQualityCrops<>(plugin, section, chance); } else { plugin.getPluginLogger().warn("Invalid value type: " + args.getClass().getSimpleName() + " found at quality-crops action which is expected to be `Section`"); return Action.empty(); } }, "quality-crops"); } protected void registerDropItemsAction() { registerAction((args, chance) -> { if (args instanceof Section section) { return new ActionDropItem<>(plugin, section, chance); } else { plugin.getPluginLogger().warn("Invalid value type: " + args.getClass().getSimpleName() + " found at drop-item action which is expected to be `Section`"); return Action.empty(); } }, "drop-item"); } protected void registerLegacyDropItemsAction() { registerAction((args, chance) -> { if (args instanceof Section section) { return new ActionDropItemLegacy<>(plugin, this, section, chance); } else { plugin.getPluginLogger().warn("Invalid value type: " + args.getClass().getSimpleName() + " found at drop-items action which is expected to be `Section`"); return Action.empty(); } }, "drop-items"); } protected void registerHologramAction() { registerAction(((args, chance) -> { if (args instanceof Section section) { return new ActionHologram<>(plugin, section, chance); } else { plugin.getPluginLogger().warn("Invalid value type: " + args.getClass().getSimpleName() + " found at hologram action which is expected to be `Section`"); return Action.empty(); } }), "hologram"); } protected void registerFakeItemAction() { registerAction(((args, chance) -> { if (args instanceof Section section) { return new ActionFakeItem<>(plugin, section, chance); } else { plugin.getPluginLogger().warn("Invalid value type: " + args.getClass().getSimpleName() + " found at fake-item action which is expected to be `Section`"); return Action.empty(); } }), "fake-item"); } protected void registerPlantAction() { this.registerAction((args, chance) -> { if (args instanceof Section section) { return new ActionPlant<>(plugin, section, chance); } else { plugin.getPluginLogger().warn("Invalid value type: " + args.getClass().getSimpleName() + " found at plant action which is expected to be `Section`"); return Action.empty(); } }, "plant", "replant"); } protected void registerBreakAction() { this.registerAction((args, chance) -> new ActionBreak<>(plugin, args, chance), "break"); } protected void registerSpawnEntityAction() { this.registerAction((args, chance) -> { if (args instanceof Section section) { return new ActionSpawnEntity<>(plugin, section, chance); } else { plugin.getPluginLogger().warn("Invalid value type: " + args.getClass().getSimpleName() + " found at spawn-entity action which is expected to be `Section`"); return Action.empty(); } }, "spawn-entity", "spawn-mob"); } protected void registerVariationAction() { this.registerAction((args, chance) -> { if (args instanceof Section section) { return new ActionVariation<>(plugin, section, chance); } else { plugin.getPluginLogger().warn("Invalid value type: " + args.getClass().getSimpleName() + " found at spawn-entity action which is expected to be `Section`"); return Action.empty(); } }, "variation"); } }
411
0.892022
1
0.892022
game-dev
MEDIA
0.706368
game-dev
0.981653
1
0.981653
RyFiction/casino-reboot
2,073
casino-walls/server/casino.lua
local QBCore = exports['qb-core']:GetCoreObject() local quantity = 0 local ItemList = { ["casino_chip"] = 1, } RegisterNetEvent("ry::server:purchaseMembership", function() local src = source local Player = QBCore.Functions.GetPlayer(src) local MembershipCheck = Player.Functions.GetItemByName('casino_members') if MembershipCheck ~= nil then TriggerClientEvent('ry::casinoMembershipMenu', src) TriggerClientEvent('QBCore:Notify', src, 'You already have a Membership', 'error') else if Player.Functions.AddItem('casino_members', 1, false, info) then TriggerClientEvent('inventory:client:ItemBox', src, QBCore.Shared.Items['casino_members'], "add", 1) TriggerClientEvent('ry::casinoMembershipMenu', src) end end end) RegisterNetEvent("ry::server:purchaseVIPMembership", function() local src = source local Player = QBCore.Functions.GetPlayer(src) local VIPMembershipCheck = Player.Functions.GetItemByName('casino_vip') if VIPMembershipCheck ~= nil then TriggerClientEvent('ry::casinoMembershipMenu', src) TriggerClientEvent('QBCore:Notify', src, 'You already have a Membership', 'error') else if Player.Functions.AddItem('casino_vip', 1, false, info) then TriggerClientEvent('inventory:client:ItemBox', src, QBCore.Shared.Items['casino_vip'], "add", 1) TriggerClientEvent('ry::casinoMembershipMenu', src) end end end) QBCore.Functions.CreateCallback('ry::server:HasCasinoMembership', function(source, cb) local Player = QBCore.Functions.GetPlayer(source) local Item = Player.Functions.GetItemByName("casino_members") if Item ~= nil then cb(true) else cb(false) end end) QBCore.Functions.CreateCallback('ry::server:HasVIPMembership', function(source, cb) local Player = QBCore.Functions.GetPlayer(source) local Item = Player.Functions.GetItemByName("casino_vip") if Item ~= nil then cb(true) else cb(false) end end)
411
0.695723
1
0.695723
game-dev
MEDIA
0.71879
game-dev
0.840685
1
0.840685
GIScience/ohsome-planet
2,429
osm-geometry/src/main/java/org/heigit/ohsome/osm/geometry/Segment.java
package org.heigit.ohsome.osm.geometry; import org.locationtech.jts.geom.Coordinate; import java.util.ArrayList; import java.util.List; class Segment { private List<Coordinate> coordinates; long wayId; private boolean isReversed = false; public Segment(List<Coordinate> coordinates, long wayId) { this.coordinates = new ArrayList<>(coordinates); this.wayId = wayId; } public void reverse() { this.isReversed = !this.isReversed; } public Coordinate getFirstCoordinate() { return isReversed ? this.coordinates.getLast() : this.coordinates.getFirst(); } public Coordinate getLastCoordinate() { return isReversed ? this.coordinates.getFirst() : this.coordinates.getLast(); } public Coordinate getOtherCoordinate(Coordinate nodeId) { return this.getFirstCoordinate().equals2D(nodeId) ? this.getLastCoordinate() : this.getFirstCoordinate(); } public Segment setFirstCoordinate(Coordinate nodeId) { if (!this.getFirstCoordinate().equals2D(nodeId)) reverse(); return this; } public List<Coordinate> toCoordinates() { return getCoordinates(); } public List<Coordinate> getCoordinates() { return isReversed ? coordinates.reversed() : coordinates; } @Override public int hashCode() { int h = 0; for (var coordinate : coordinates) { if (coordinate != null) { h += coordinate.hashCode(); } } return h; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } Segment other = (Segment) obj; return isSame(other); } public boolean isSame(Segment other) { List<Coordinate> otherNodes = new ArrayList<>(other.getCoordinates()); if (coordinates.size() != otherNodes.size()) return false; if (!coordinates.getFirst().equals2D(otherNodes.getFirst())) { if (!coordinates.getFirst().equals2D(otherNodes.getLast())) { return false; } if (!coordinates.getLast().equals2D(otherNodes.getFirst())) { return false; } otherNodes = otherNodes.reversed(); } if (!coordinates.getLast().equals2D(otherNodes.getLast())) { return false; } for (int i = 1; i < coordinates.size() - 1; i++) { if (!coordinates.get(i).equals2D(otherNodes.get(i))) { return false; } } return true; } }
411
0.724487
1
0.724487
game-dev
MEDIA
0.179757
game-dev
0.939834
1
0.939834
Sigma-Skidder-Team/SigmaRebase
6,924
src/main/java/net/minecraft/entity/passive/horse/AbstractChestedHorseEntity.java
package net.minecraft.entity.passive.horse; import net.minecraft.block.Blocks; import net.minecraft.entity.EntityType; import net.minecraft.entity.ai.attributes.AttributeModifierMap; import net.minecraft.entity.ai.attributes.Attributes; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.nbt.CompoundNBT; import net.minecraft.nbt.ListNBT; import net.minecraft.network.datasync.DataParameter; import net.minecraft.network.datasync.DataSerializers; import net.minecraft.network.datasync.EntityDataManager; import net.minecraft.util.ActionResultType; import net.minecraft.util.Hand; import net.minecraft.util.SoundEvents; import net.minecraft.world.World; public abstract class AbstractChestedHorseEntity extends AbstractHorseEntity { private static final DataParameter<Boolean> DATA_ID_CHEST = EntityDataManager.createKey(AbstractChestedHorseEntity.class, DataSerializers.BOOLEAN); protected AbstractChestedHorseEntity(EntityType <? extends AbstractChestedHorseEntity > type, World worldIn) { super(type, worldIn); this.canGallop = false; } protected void func_230273_eI_() { this.getAttribute(Attributes.MAX_HEALTH).setBaseValue((double)this.getModifiedMaxHealth()); } protected void registerData() { super.registerData(); this.dataManager.register(DATA_ID_CHEST, false); } public static AttributeModifierMap.MutableAttribute func_234234_eJ_() { return func_234237_fg_().createMutableAttribute(Attributes.MOVEMENT_SPEED, (double)0.175F).createMutableAttribute(Attributes.HORSE_JUMP_STRENGTH, 0.5D); } public boolean hasChest() { return this.dataManager.get(DATA_ID_CHEST); } public void setChested(boolean chested) { this.dataManager.set(DATA_ID_CHEST, chested); } protected int getInventorySize() { return this.hasChest() ? 17 : super.getInventorySize(); } /** * Returns the Y offset from the entity's position for any entity riding this one. */ public double getMountedYOffset() { return super.getMountedYOffset() - 0.25D; } protected void dropInventory() { super.dropInventory(); if (this.hasChest()) { if (!this.world.isRemote) { this.entityDropItem(Blocks.CHEST); } this.setChested(false); } } public void writeAdditional(CompoundNBT compound) { super.writeAdditional(compound); compound.putBoolean("ChestedHorse", this.hasChest()); if (this.hasChest()) { ListNBT listnbt = new ListNBT(); for (int i = 2; i < this.horseChest.getSizeInventory(); ++i) { ItemStack itemstack = this.horseChest.getStackInSlot(i); if (!itemstack.isEmpty()) { CompoundNBT compoundnbt = new CompoundNBT(); compoundnbt.putByte("Slot", (byte)i); itemstack.write(compoundnbt); listnbt.add(compoundnbt); } } compound.put("Items", listnbt); } } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ public void readAdditional(CompoundNBT compound) { super.readAdditional(compound); this.setChested(compound.getBoolean("ChestedHorse")); if (this.hasChest()) { ListNBT listnbt = compound.getList("Items", 10); this.initHorseChest(); for (int i = 0; i < listnbt.size(); ++i) { CompoundNBT compoundnbt = listnbt.getCompound(i); int j = compoundnbt.getByte("Slot") & 255; if (j >= 2 && j < this.horseChest.getSizeInventory()) { this.horseChest.setInventorySlotContents(j, ItemStack.read(compoundnbt)); } } } this.func_230275_fc_(); } public boolean replaceItemInInventory(int inventorySlot, ItemStack itemStackIn) { if (inventorySlot == 499) { if (this.hasChest() && itemStackIn.isEmpty()) { this.setChested(false); this.initHorseChest(); return true; } if (!this.hasChest() && itemStackIn.getItem() == Blocks.CHEST.asItem()) { this.setChested(true); this.initHorseChest(); return true; } } return super.replaceItemInInventory(inventorySlot, itemStackIn); } public ActionResultType func_230254_b_(PlayerEntity p_230254_1_, Hand p_230254_2_) { ItemStack itemstack = p_230254_1_.getHeldItem(p_230254_2_); if (!this.isChild()) { if (this.isTame() && p_230254_1_.isSecondaryUseActive()) { this.openGUI(p_230254_1_); return ActionResultType.func_233537_a_(this.world.isRemote); } if (this.isBeingRidden()) { return super.func_230254_b_(p_230254_1_, p_230254_2_); } } if (!itemstack.isEmpty()) { if (this.isBreedingItem(itemstack)) { return this.func_241395_b_(p_230254_1_, itemstack); } if (!this.isTame()) { this.makeMad(); return ActionResultType.func_233537_a_(this.world.isRemote); } if (!this.hasChest() && itemstack.getItem() == Blocks.CHEST.asItem()) { this.setChested(true); this.playChestEquipSound(); if (!p_230254_1_.abilities.isCreativeMode) { itemstack.shrink(1); } this.initHorseChest(); return ActionResultType.func_233537_a_(this.world.isRemote); } if (!this.isChild() && !this.isHorseSaddled() && itemstack.getItem() == Items.SADDLE) { this.openGUI(p_230254_1_); return ActionResultType.func_233537_a_(this.world.isRemote); } } if (this.isChild()) { return super.func_230254_b_(p_230254_1_, p_230254_2_); } else { this.mountTo(p_230254_1_); return ActionResultType.func_233537_a_(this.world.isRemote); } } protected void playChestEquipSound() { this.playSound(SoundEvents.ENTITY_DONKEY_CHEST, 1.0F, (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F + 1.0F); } public int getInventoryColumns() { return 5; } }
411
0.871786
1
0.871786
game-dev
MEDIA
0.993124
game-dev
0.963415
1
0.963415
sagirilover/AnimeSoftware
1,573
AnimeSoftware/Hack/Features/WeaponSpammer.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using AnimeSoftware.Hack.Models; using AnimeSoftware.Injections; using AnimeSoftware.Objects; using AnimeSoftware.Offsets; namespace AnimeSoftware.Hacks { internal class WeaponSpammer { public static void Start() { while (Properties.Settings.Default.weaponspammer) { Thread.Sleep(10); if (!Engine.InGame) continue; var lp = new LocalPlayer(); if(lp.Ptr == IntPtr.Zero) continue; if (lp.Health <= 0) continue; var weapon = lp.ActiveWeapon.Id; if (Structs.SpamWeaponList.Contains(weapon)) { if (weapon == 64 || weapon == 262208) { Memory.Write<int>(Memory.Client + Signatures.dwForceAttack, 5); Thread.Sleep(100); Memory.Write<int>(Memory.Client + Signatures.dwForceAttack, 4); Thread.Sleep(100); } else { ClientCMD.Exec("+attack2"); Thread.Sleep(10); ClientCMD.Exec("-attack2"); } } } ClientCMD.Exec("-attack2"); } } }
411
0.764738
1
0.764738
game-dev
MEDIA
0.864771
game-dev
0.507156
1
0.507156
tastybento/askyblock
11,415
src/com/wasteofplastic/askyblock/util/teleport/SafeSpotTeleport.java
package com.wasteofplastic.askyblock.util.teleport; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.bukkit.ChunkSnapshot; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitTask; import org.bukkit.util.Vector; import com.wasteofplastic.askyblock.ASkyBlock; import com.wasteofplastic.askyblock.Island; import com.wasteofplastic.askyblock.Settings; import com.wasteofplastic.askyblock.util.Pair; /** * A class that calculates finds a safe spot asynchronously and then teleports the player there. * @author tastybento * */ public class SafeSpotTeleport { private static final int MAX_CHUNKS = 200; private static final long SPEED = 1; private static final int MAX_RADIUS = 200; private boolean checking = true; private BukkitTask task; // Parameters private final Entity entity; private final Location location; private boolean portal; private final int homeNumber; // Locations private Location bestSpot; private ASkyBlock plugin; private List<Pair<Integer, Integer>> chunksToScan; /** * Teleports and entity to a safe spot on island * @param plugin - ASkyBlock plugin object * @param entity * @param location * @param failureMessage - already translated failure message * @param portal * @param homeNumber */ protected SafeSpotTeleport(ASkyBlock plugin, final Entity entity, final Location location, final String failureMessage, boolean portal, int homeNumber) { this.plugin = plugin; this.entity = entity; this.location = location; this.portal = portal; this.homeNumber = homeNumber; // Put player into spectator mode if (!plugin.getServer().getVersion().contains("1.7") && entity instanceof Player && ((Player)entity).getGameMode().equals(GameMode.SURVIVAL)) { ((Player)entity).setGameMode(GameMode.SPECTATOR); } // Get chunks to scan chunksToScan = getChunksToScan(); // Start checking checking = true; // Start a recurring task until done or cancelled task = plugin.getServer().getScheduler().runTaskTimer(plugin, new Runnable() { @Override public void run() { List<ChunkSnapshot> chunkSnapshot = new ArrayList<>(); if (checking) { Iterator<Pair<Integer, Integer>> it = chunksToScan.iterator(); if (!it.hasNext()) { // Nothing left tidyUp(entity, failureMessage); return; } // Add chunk snapshots to the list while (it.hasNext() && chunkSnapshot.size() < MAX_CHUNKS) { Pair<Integer, Integer> pair = it.next(); chunkSnapshot.add(location.getWorld().getChunkAt(pair.x, pair.z).getChunkSnapshot()); it.remove(); } // Move to next step checking = false; checkChunks(chunkSnapshot); } } }, 0L, SPEED); } private void tidyUp(Entity entity, String failureMessage) { // Nothing left to check and still not canceled task.cancel(); // Check portal if (portal && bestSpot != null) { // No portals found, teleport to the best spot we found teleportEntity(bestSpot); } else if (entity instanceof Player && !failureMessage.isEmpty()) { // Failed, no safe spot entity.sendMessage(failureMessage); } if (entity instanceof Player && (plugin.getServer().getVersion().contains("1.7") || ((Player)entity).getGameMode().equals(GameMode.SPECTATOR))) { ((Player)entity).setGameMode(GameMode.SURVIVAL); } if (entity instanceof Player) { plugin.getPlayers().setInTeleport(entity.getUniqueId(), false); } } /** * Gets a set of chunk coords that will be scanned. * @param entity * @param location * @return */ private List<Pair<Integer, Integer>> getChunksToScan() { List<Pair<Integer, Integer>> result = new ArrayList<>(); // Get island if available Island island = plugin.getGrid().getIslandAt(location); int maxRadius = island == null ? Settings.islandProtectionRange/2 : island.getProtectionSize()/2; maxRadius = maxRadius > MAX_RADIUS ? MAX_RADIUS : maxRadius; int x = location.getBlockX(); int z = location.getBlockZ(); // Create ever increasing squares around the target location int radius = 0; do { for (int i = x - radius; i <= x + radius; i+=16) { for (int j = z - radius; j <= z + radius; j+=16) { addChunk(result, island, new Pair<>(i,j), new Pair<>(i/16, j/16)); } } radius++; } while (radius < maxRadius); return result; } private void addChunk(List<Pair<Integer, Integer>> result, Island island, Pair<Integer, Integer> blockCoord, Pair<Integer, Integer> chunkCoord) { if (!result.contains(chunkCoord)) { // Add the chunk coord if (island == null) { // If there is no island, just add it result.add(chunkCoord); } else { // If there is an island, only add it if the coord is in island space if (island.inIslandSpace(blockCoord.x, blockCoord.z)) { result.add(chunkCoord); } } } } /** * Loops through the chunks and if a safe spot is found, fires off the teleportation * @param chunkSnapshot */ private void checkChunks(final List<ChunkSnapshot> chunkSnapshot) { // Run async task to scan chunks plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() { @Override public void run() { for (ChunkSnapshot chunk: chunkSnapshot) { if (scanChunk(chunk)) { task.cancel(); return; } } // Nothing happened, change state checking = true; } }); } /** * @param chunk * @return true if a safe spot was found */ private boolean scanChunk(ChunkSnapshot chunk) { // Max height int maxHeight = location.getWorld().getMaxHeight() - 20; // Run through the chunk for (int x = 0; x< 16; x++) { for (int z = 0; z < 16; z++) { // Work down from the entry point up for (int y = Math.min(chunk.getHighestBlockYAt(x, z), maxHeight); y >= 0; y--) { if (checkBlock(chunk, x,y,z, maxHeight)) { return true; } } // end y } //end z } // end x return false; } /** * Teleports entity to the safe spot */ private void teleportEntity(final Location loc) { task.cancel(); // Return to main thread and teleport the player plugin.getServer().getScheduler().runTask(plugin, new Runnable() { @Override public void run() { if (!portal && entity instanceof Player) { // Set home plugin.getPlayers().setHomeLocation(entity.getUniqueId(), loc, homeNumber); } Vector velocity = entity.getVelocity(); entity.teleport(loc); // Exit spectator mode if in it if (entity instanceof Player) { Player player = (Player)entity; if (plugin.getServer().getVersion().contains("1.7")) { player.setGameMode(GameMode.SURVIVAL); } else if (player.getGameMode().equals(GameMode.SPECTATOR)) { player.setGameMode(GameMode.SURVIVAL); } } else { entity.setVelocity(velocity); } } }); } /** * Returns true if the location is a safe one. * @param chunk * @param x * @param y * @param z * @param worldHeight * @return true if this is a safe spot, false if this is a portal scan */ @SuppressWarnings("deprecation") private boolean checkBlock(ChunkSnapshot chunk, int x, int y, int z, int worldHeight) { World world = location.getWorld(); Material type = Material.getMaterial(chunk.getBlockTypeId(x, y, z)); if (!type.equals(Material.AIR)) { // AIR Material space1 = Material.getMaterial(chunk.getBlockTypeId(x, Math.min(y + 1, worldHeight), z)); Material space2 = Material.getMaterial(chunk.getBlockTypeId(x, Math.min(y + 2, worldHeight), z)); if ((space1.equals(Material.AIR) && space2.equals(Material.AIR)) || (space1.equals(Material.PORTAL) && space2.equals(Material.PORTAL)) && (!type.toString().contains("FENCE") && !type.toString().contains("DOOR") && !type.toString().contains("GATE") && !type.toString().contains("PLATE"))) { switch (type) { // Unsafe case ANVIL: case BARRIER: case BOAT: case CACTUS: case DOUBLE_PLANT: case ENDER_PORTAL: case FIRE: case FLOWER_POT: case LADDER: case LAVA: case LEVER: case LONG_GRASS: case PISTON_EXTENSION: case PISTON_MOVING_PIECE: case SIGN_POST: case SKULL: case STANDING_BANNER: case STATIONARY_LAVA: case STATIONARY_WATER: case STONE_BUTTON: case TORCH: case TRIPWIRE: case WATER: case WEB: case WOOD_BUTTON: //Block is dangerous break; case PORTAL: if (portal) { // A portal has been found, switch to non-portal mode now portal = false; } break; default: return safe(chunk, x, y, z, world); } } } return false; } private boolean safe(ChunkSnapshot chunk, int x, int y, int z, World world) { Vector newSpot = new Vector(chunk.getX() * 16 + x + 0.5D, y + 1, chunk.getZ() * 16 + z + 0.5D); if (portal) { if (bestSpot == null) { // Stash the best spot bestSpot = newSpot.toLocation(world); } return false; } else { teleportEntity(newSpot.toLocation(world)); return true; } } }
411
0.962635
1
0.962635
game-dev
MEDIA
0.940008
game-dev
0.978073
1
0.978073
dreamanlan/Cs2Lua
14,967
Test/TestUnity/Assets/Slua/LuaObject/Unity/Lua_UnityEngine_ParticleSystem_LimitVelocityOverLifetimeModule.cs
using System; using SLua; using System.Collections.Generic; [UnityEngine.Scripting.Preserve] public class Lua_UnityEngine_ParticleSystem_LimitVelocityOverLifetimeModule : LuaObject { [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int ctor_s(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule o; o=new UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule(); pushValue(l,true); pushValue(l,o); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_enabled(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.enabled); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_enabled(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); bool v; checkType(l,2,out v); self.enabled=v; setBack(l,(object)self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_limitX(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.limitX); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_limitX(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); UnityEngine.ParticleSystem.MinMaxCurve v; checkValueType(l,2,out v); self.limitX=v; setBack(l,(object)self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_limitXMultiplier(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.limitXMultiplier); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_limitXMultiplier(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); float v; checkType(l,2,out v); self.limitXMultiplier=v; setBack(l,(object)self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_limitY(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.limitY); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_limitY(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); UnityEngine.ParticleSystem.MinMaxCurve v; checkValueType(l,2,out v); self.limitY=v; setBack(l,(object)self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_limitYMultiplier(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.limitYMultiplier); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_limitYMultiplier(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); float v; checkType(l,2,out v); self.limitYMultiplier=v; setBack(l,(object)self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_limitZ(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.limitZ); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_limitZ(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); UnityEngine.ParticleSystem.MinMaxCurve v; checkValueType(l,2,out v); self.limitZ=v; setBack(l,(object)self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_limitZMultiplier(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.limitZMultiplier); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_limitZMultiplier(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); float v; checkType(l,2,out v); self.limitZMultiplier=v; setBack(l,(object)self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_limit(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.limit); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_limit(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); UnityEngine.ParticleSystem.MinMaxCurve v; checkValueType(l,2,out v); self.limit=v; setBack(l,(object)self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_limitMultiplier(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.limitMultiplier); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_limitMultiplier(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); float v; checkType(l,2,out v); self.limitMultiplier=v; setBack(l,(object)self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_dampen(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.dampen); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_dampen(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); float v; checkType(l,2,out v); self.dampen=v; setBack(l,(object)self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_separateAxes(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.separateAxes); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_separateAxes(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); bool v; checkType(l,2,out v); self.separateAxes=v; setBack(l,(object)self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_space(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); pushValue(l,true); pushEnum(l,(int)self.space); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_space(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); UnityEngine.ParticleSystemSimulationSpace v; checkEnum(l,2,out v); self.space=v; setBack(l,(object)self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_drag(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.drag); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_drag(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); UnityEngine.ParticleSystem.MinMaxCurve v; checkValueType(l,2,out v); self.drag=v; setBack(l,(object)self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_dragMultiplier(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.dragMultiplier); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_dragMultiplier(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); float v; checkType(l,2,out v); self.dragMultiplier=v; setBack(l,(object)self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_multiplyDragByParticleSize(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.multiplyDragByParticleSize); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_multiplyDragByParticleSize(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); bool v; checkType(l,2,out v); self.multiplyDragByParticleSize=v; setBack(l,(object)self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_multiplyDragByParticleVelocity(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.multiplyDragByParticleVelocity); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_multiplyDragByParticleVelocity(IntPtr l) { try { UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule self; checkValueType(l,1,out self); bool v; checkType(l,2,out v); self.multiplyDragByParticleVelocity=v; setBack(l,(object)self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [UnityEngine.Scripting.Preserve] static public void reg(IntPtr l) { getTypeTable(l,"UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule"); addMember(l,ctor_s); addMember(l,"enabled",get_enabled,set_enabled,true); addMember(l,"limitX",get_limitX,set_limitX,true); addMember(l,"limitXMultiplier",get_limitXMultiplier,set_limitXMultiplier,true); addMember(l,"limitY",get_limitY,set_limitY,true); addMember(l,"limitYMultiplier",get_limitYMultiplier,set_limitYMultiplier,true); addMember(l,"limitZ",get_limitZ,set_limitZ,true); addMember(l,"limitZMultiplier",get_limitZMultiplier,set_limitZMultiplier,true); addMember(l,"limit",get_limit,set_limit,true); addMember(l,"limitMultiplier",get_limitMultiplier,set_limitMultiplier,true); addMember(l,"dampen",get_dampen,set_dampen,true); addMember(l,"separateAxes",get_separateAxes,set_separateAxes,true); addMember(l,"space",get_space,set_space,true); addMember(l,"drag",get_drag,set_drag,true); addMember(l,"dragMultiplier",get_dragMultiplier,set_dragMultiplier,true); addMember(l,"multiplyDragByParticleSize",get_multiplyDragByParticleSize,set_multiplyDragByParticleSize,true); addMember(l,"multiplyDragByParticleVelocity",get_multiplyDragByParticleVelocity,set_multiplyDragByParticleVelocity,true); createTypeMetatable(l,null, typeof(UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule),typeof(System.ValueType)); } }
411
0.825816
1
0.825816
game-dev
MEDIA
0.94332
game-dev
0.723573
1
0.723573
HomerJohnston/Yap
1,456
Source/YapEditor/Public/YapEditor/YapTransactions.h
// Copyright Ghost Pepper Games, Inc. All Rights Reserved. // This work is MIT-licensed. Feel free to use it however you wish, within the confines of the MIT license. #pragma once #include "UObject/NameTypes.h" #include "UObject/WeakObjectPtr.h" class UFlowGraphNode_YapBase; #define LOCTEXT_NAMESPACE "YapEditor" #define YAP_DECLARE_TRANSACTION(NAME) static FName NAME = "NAME" namespace YapTransactions { YAP_DECLARE_TRANSACTION(RefreshCharacterPortraitList); YAP_DECLARE_TRANSACTION(AddMoodTagPortrait); YAP_DECLARE_TRANSACTION(FixupOldPortraitsMap); } /** Helper class. I ran into a few odd issues using FScopedTransaction so I made this, seems to work more reliably. */ class FYapTransactions { public: static void BeginModify(const FText& TransactionText, UObject* Object); static void EndModify(); }; /** * The purpose of this is to make it more reliable to develop this plugin with less human errors, by: * * 1) Automatically calling Modify on UObject. * 2) Automatically broadcasting a simple named event delegate. This makes it easier for widgets to reliably update their state. */ class FYapScopedTransaction { FName Event; TWeakObjectPtr<UFlowGraphNode_YapBase> PrimaryObject; public: FYapScopedTransaction(FName InEvent, const FText& TransactionText, UObject* Object); void AbortAndUndo(); void Cancel(); bool IsOutstanding() const; ~FYapScopedTransaction(); int32 Index = -1; }; #undef LOCTEXT_NAMESPACE
411
0.871442
1
0.871442
game-dev
MEDIA
0.277687
game-dev
0.740687
1
0.740687
AXiX-official/CrossCoreLuascripts
2,176
ios/Others/DungeonInfoButton2.lua
local cfg = nil local data = nil local sectionData = nil local isSweepOpen = false local buyFunc = nil function Awake() eventMgr = ViewEvent.New(); eventMgr:AddListener(EventType.Sweep_Show_Panel, ShowSweep) eventMgr:AddListener(EventType.Player_HotChange, ShowCost) eventMgr:AddListener(EventType.Bag_Update, ShowCost) end function OnDestroy() eventMgr:ClearListener() end function Refresh(tab) cfg = tab.cfg data = tab.data sectionData = tab.sectionData if cfg then ShowCost() ShowSweep() end end function ShowCost() if cfg then local _cost = DungeonUtil.GetCost(cfg) if _cost~=nil then local cur = BagMgr:GetCount(_cost[1]) ResUtil.IconGoods:Load(costImg, _cost[1] .. "_3") CSAPI.SetAnchor(costImg,-153,0) CSAPI.SetText(cost,"-" .. _cost[2]) local cfg = Cfgs.ItemInfo:GetByID(_cost[1]) if cfg then CSAPI.SetText(txt_cost, cfg.name) end else ResUtil.IconGoods:Load(costImg, ITEM_ID.Hot .. "_3") local costNum = DungeonUtil.GetHot(cfg) costNum = StringUtil:SetByColor(costNum .. "", math.abs(costNum) <= PlayerClient:Hot() and "191919" or "CD333E") CSAPI.SetText(cost," " .. costNum) LanguageMgr:SetText(txt_cost, 15004) end end end --扫荡状态 function ShowSweep() if cfg == nil then return end if cfg.diff and cfg.diff == 3 then CSAPI.SetGOActive(btnSweep,false) CSAPI.SetAnchor(btnEnter,0,58) return end CSAPI.SetGOActive(btnSweep,cfg.modUpCnt ~= nil) if cfg.modUpCnt == nil then CSAPI.SetAnchor(btnEnter,0,58) return end CSAPI.SetAnchor(btnEnter,59,58) isSweepOpen = false local sweepData = SweepMgr:GetData(cfg.id) if sweepData then isSweepOpen = sweepData:IsOpen() end CSAPI.SetGOActive(sweepLock,not isSweepOpen) CSAPI.SetImgColor(sweepImg,255,255,255,isSweepOpen and 255 or 76) end function OnClickEnter() end function OnClickSweep() end function IsSweepOpen() return isSweepOpen end
411
0.880688
1
0.880688
game-dev
MEDIA
0.805988
game-dev
0.893368
1
0.893368
project-topaz/topaz
1,242
scripts/zones/AlTaieu/mobs/Qnhpemde.lua
----------------------------------- -- Area: Al'Taieu -- Mob: Qn'hpemde -- Jailor of Love Pet version ----------------------------------- local ID = require("scripts/zones/AlTaieu/IDs") ----------------------------------- function onMobSpawn(mob) mob:AnimationSub(6) -- Mouth Closed end function onMobFight(mob, target) local changeTime = mob:getLocalVar("changeTime") if (mob:AnimationSub() == 6 and mob:getBattleTime() - changeTime > 30) then mob:AnimationSub(3) -- Mouth Open mob:addMod(tpz.mod.ATTP, 100) mob:addMod(tpz.mod.DEFP, -50) mob:addMod(tpz.mod.DMGMAGIC, -50) mob:setLocalVar("changeTime", mob:getBattleTime()) elseif (mob:AnimationSub() == 3 and mob:getBattleTime() - changeTime > 30) then mob:AnimationSub(6) -- Mouth Closed mob:addMod(tpz.mod.ATTP, -100) mob:addMod(tpz.mod.DEFP, 50) mob:addMod(tpz.mod.DMGMAGIC, 50) mob:setLocalVar("changeTime", mob:getBattleTime()) end end function onMobDeath(mob, player, isKiller) end function onMobDespawn(mob) local JoL = GetMobByID(ID.mob.JAILER_OF_LOVE) local HPEMDES = JoL:getLocalVar("JoL_Qn_hpemde_Killed") JoL:setLocalVar("JoL_Qn_hpemde_Killed", HPEMDES+1) end
411
0.702712
1
0.702712
game-dev
MEDIA
0.974238
game-dev
0.888883
1
0.888883
mastercomfig/tf2-patches-old
6,302
src/game/server/hl2/weapon_thumper.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: 'weapon' what lets the player controll the rollerbuddy. // // $Revision: $ // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "basehlcombatweapon.h" #include "NPCevent.h" #include "basecombatcharacter.h" #include "ai_basenpc.h" #include "player.h" #include "entitylist.h" #include "ndebugoverlay.h" #include "soundent.h" #include "engine/IEngineSound.h" #include "rotorwash.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" ConVar thumpFrequency( "thumpfrequency", "2" ); ConVar thumpRadius( "thumpradius", "512" ); //========================================================= //========================================================= class CPortableThumper : public CBaseAnimating { DECLARE_CLASS( CPortableThumper, CBaseAnimating ); private: void ThumpThink( void ); void ThumperUse( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); void Precache( void ); void Spawn( void ); int ObjectCaps( void ) { return FCAP_IMPULSE_USE; } DECLARE_DATADESC(); }; LINK_ENTITY_TO_CLASS( portable_thumper, CPortableThumper ); void CPortableThumper::Precache( void ) { PrecacheModel( "models/fire_equipment/w_firehydrant.mdl" ); } void CPortableThumper::Spawn( void ) { m_takedamage = DAMAGE_NO; SetModel( "models/fire_equipment/w_firehydrant.mdl" ); Vector vecBBMin, vecBBMax; vecBBMin.z = 0; vecBBMin.x = -16; vecBBMin.y = -16; vecBBMax.z = 32; vecBBMax.x = 16; vecBBMax.y = 16; SetSolid( SOLID_BBOX ); UTIL_SetSize( this, vecBBMin, vecBBMax ); SetThink( ThumpThink ); SetUse( ThumperUse ); SetNextThink( gpGlobals->curtime + thumpFrequency.GetFloat() ); } void CPortableThumper::ThumperUse( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { if( !pActivator->IsPlayer() ) { return; } CBasePlayer *pPlayer; pPlayer = (CBasePlayer *)pActivator; pPlayer->GiveNamedItem( "weapon_thumper" ); UTIL_Remove( this ); } void CPortableThumper::ThumpThink( void ) { EmitSound( "PortableThumper.ThumpSound" ); UTIL_RotorWash( GetAbsOrigin() + Vector( 0, 0, 32 ), Vector( 0, 0, -1 ), 512 ); SetNextThink( gpGlobals->curtime + thumpFrequency.GetFloat() ); CSoundEnt::InsertSound( SOUND_THUMPER, GetAbsOrigin(), thumpRadius.GetInt(), 0.2, this ); } BEGIN_DATADESC( CPortableThumper ) DEFINE_FUNCTION( ThumpThink ), DEFINE_FUNCTION( ThumperUse ), END_DATADESC() class CWeaponThumper: public CBaseHLCombatWeapon { DECLARE_CLASS( CWeaponThumper, CBaseHLCombatWeapon ); public: DECLARE_SERVERCLASS(); void Spawn( void ); void Precache( void ); int CapabilitiesGet( void ) { return bits_CAP_WEAPON_RANGE_ATTACK1; } void PrimaryAttack( void ); bool Reload( void ); void DecrementAmmo( CBaseCombatCharacter *pOwner ); }; IMPLEMENT_SERVERCLASS_ST(CWeaponThumper, DT_WeaponThumper) END_SEND_TABLE() LINK_ENTITY_TO_CLASS( weapon_thumper, CWeaponThumper ); PRECACHE_WEAPON_REGISTER(weapon_thumper); void CWeaponThumper::Spawn( ) { BaseClass::Spawn(); Precache( ); UTIL_SetSize(this, Vector(-4,-4,-2),Vector(4,4,2)); FallInit();// get ready to fall down } void CWeaponThumper::Precache( void ) { BaseClass::Precache(); UTIL_PrecacheOther( "portable_thumper" ); PrecacheScriptSound( "PortableThumper.ThumpSound" ); } bool CWeaponThumper::Reload( void ) { WeaponIdle(); return true; } void CWeaponThumper::PrimaryAttack( void ) { CBasePlayer *pPlayer = ToBasePlayer( GetOwner() ); if ( !pPlayer ) return; DecrementAmmo( pPlayer ); trace_t tr; Vector vecStart, vecDir; Vector vecForward; Vector vecSpot; pPlayer->GetVectors( &vecForward, NULL, NULL ); vecForward.z = 0.0; vecStart = pPlayer->WorldSpaceCenter() + vecForward * 64; UTIL_TraceLine( vecStart, vecStart - Vector( 0, 0, 128 ), MASK_SHOT, pPlayer, COLLISION_GROUP_NONE, &tr ); if( tr.fraction != 1.0 ) { Create( "portable_thumper", tr.endpos, vec3_angle, NULL ); m_flNextPrimaryAttack = gpGlobals->curtime + 0.5; } m_flNextPrimaryAttack = gpGlobals->curtime + 0.5; } void CWeaponThumper::DecrementAmmo( CBaseCombatCharacter *pOwner ) { pOwner->RemoveAmmo( 1, m_iPrimaryAmmoType ); if (pOwner->GetAmmoCount(m_iPrimaryAmmoType) <= 0) { pOwner->Weapon_Drop( this ); UTIL_Remove(this); } } /* //========================================================= //========================================================= class CWeaponThumper : public CBaseHLCombatWeapon { public: DECLARE_CLASS( CWeaponThumper, CBaseHLCombatWeapon ); CWeaponThumper(); DECLARE_SERVERCLASS(); void Precache( void ); bool Deploy( void ); int CapabilitiesGet( void ) { return bits_CAP_WEAPON_RANGE_ATTACK1; } void PrimaryAttack( void ); void SecondaryAttack( void ); DECLARE_ACTTABLE(); }; IMPLEMENT_SERVERCLASS_ST(CWeaponThumper, DT_WeaponThumper) END_SEND_TABLE() LINK_ENTITY_TO_CLASS( weapon_thumper, CWeaponThumper ); PRECACHE_WEAPON_REGISTER(weapon_thumper); acttable_t CWeaponThumper::m_acttable[] = { { ACT_RANGE_ATTACK1, ACT_RANGE_ATTACK_AR1, true }, }; IMPLEMENT_ACTTABLE(CWeaponThumper); CWeaponThumper::CWeaponThumper( ) { } void CWeaponThumper::Precache( void ) { UTIL_PrecacheOther( "portable_thumper" ); BaseClass::Precache(); } bool CWeaponThumper::Deploy( void ) { bool fReturn; fReturn = BaseClass::Deploy(); m_flNextPrimaryAttack = gpGlobals->curtime; m_flNextSecondaryAttack = gpGlobals->curtime; m_hOwner->m_flNextAttack = gpGlobals->curtime + 0.0; return fReturn; } void CWeaponThumper::PrimaryAttack( void ) { trace_t tr; Vector vecStart, vecDir; Vector vecForward; Vector vecSpot; m_hOwner->GetVectors( &vecForward, NULL, NULL ); vecForward.z = 0.0; vecStart = m_hOwner->Center() + vecForward * 64; UTIL_TraceLine( vecStart, vecStart - Vector( 0, 0, 128 ), MASK_SHOT, m_hOwner, COLLISION_GROUP_NONE, &tr ); if( tr.fraction != 1.0 ) { Create( "portable_thumper", tr.endpos, vec3_origin, NULL ); m_flNextPrimaryAttack = gpGlobals->curtime + 0.5; } m_hOwner->m_iAmmo[m_iPrimaryAmmoType]++; } void CWeaponThumper::SecondaryAttack( void ) { m_flNextSecondaryAttack = gpGlobals->curtime + 0.5; } */
411
0.982485
1
0.982485
game-dev
MEDIA
0.986344
game-dev
0.95111
1
0.95111
ParrotDevelopers/WebOasis
82,524
src/arcade/chess/js/AI/garbochess_unclean.js
"use strict"; // Perf TODO: // Merge material updating with psq values // Put move scoring inline in generator // Remove need for fliptable in psq tables. Access them by color // Optimize pawn move generation // Non-perf todo: // Checks in first q? // Pawn eval. // Better king evaluation // Better move sorting in PV nodes (especially root) var g_debug = true; var g_timeout = 40; function GetFen(){ var result = ""; for (var row = 0; row < 8; row++) { if (row != 0) result += '/'; var empty = 0; for (var col = 0; col < 8; col++) { var piece = g_board[((row + 2) << 4) + col + 4]; if (piece == 0) { empty++; } else { if (empty != 0) result += empty; empty = 0; var pieceChar = [" ", "p", "n", "b", "r", "q", "k", " "][(piece & 0x7)]; result += ((piece & colorWhite) != 0) ? pieceChar.toUpperCase() : pieceChar; } } if (empty != 0) { result += empty; } } result += g_toMove == colorWhite ? " w" : " b"; result += " "; if (g_castleRights == 0) { result += "-"; } else { if ((g_castleRights & 1) != 0) result += "K"; if ((g_castleRights & 2) != 0) result += "Q"; if ((g_castleRights & 4) != 0) result += "k"; if ((g_castleRights & 8) != 0) result += "q"; } result += " "; if (g_enPassentSquare == -1) { result += '-'; } else { result += FormatSquare(g_enPassentSquare); } return result; } function GetMoveSAN(move, validMoves) { var from = move & 0xFF; var to = (move >> 8) & 0xFF; if (move & moveflagCastleKing) return "O-O"; if (move & moveflagCastleQueen) return "O-O-O"; var pieceType = g_board[from] & 0x7; var result = ["", "", "N", "B", "R", "Q", "K", ""][pieceType]; var dupe = false, rowDiff = true, colDiff = true; if (validMoves == null) { validMoves = GenerateValidMoves(); } for (var i = 0; i < validMoves.length; i++) { var moveFrom = validMoves[i] & 0xFF; var moveTo = (validMoves[i] >> 8) & 0xFF; if (moveFrom != from && moveTo == to && (g_board[moveFrom] & 0x7) == pieceType) { dupe = true; if ((moveFrom & 0xF0) == (from & 0xF0)) { rowDiff = false; } if ((moveFrom & 0x0F) == (from & 0x0F)) { colDiff = false; } } } if (dupe) { if (colDiff) { result += FormatSquare(from).charAt(0); } else if (rowDiff) { result += FormatSquare(from).charAt(1); } else { result += FormatSquare(from); } } else if (pieceType == piecePawn && (g_board[to] != 0 || (move & moveflagEPC))) { result += FormatSquare(from).charAt(0); } if (g_board[to] != 0 || (move & moveflagEPC)) { result += "x"; } result += FormatSquare(to); if (move & moveflagPromotion) { if (move & moveflagPromoteBishop) result += "=B"; else if (move & moveflagPromoteKnight) result += "=N"; else if (move & moveflagPromoteQueen) result += "=Q"; else result += "=R"; } MakeMove(move); if (g_inCheck) { result += GenerateValidMoves().length == 0 ? "#" : "+"; } UnmakeMove(move); return result; } function FormatSquare(square) { var letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']; return letters[(square & 0xF) - 4] + ((9 - (square >> 4)) + 1); } function FormatMove(move) { var result = FormatSquare(move & 0xFF) + FormatSquare((move >> 8) & 0xFF); if (move & moveflagPromotion) { if (move & moveflagPromoteBishop) result += "b"; else if (move & moveflagPromoteKnight) result += "n"; else if (move & moveflagPromoteQueen) result += "q"; else result += "r"; } return result; } function GetMoveFromString(moveString) { var moves = GenerateValidMoves(); for (var i = 0; i < moves.length; i++) { if (FormatMove(moves[i]) == moveString) { return moves[i]; } } alert("busted! ->" + moveString + " fen:" + GetFen()); } function PVFromHash(move, ply) { if (ply == 0) return ""; if (move == 0) { if (g_inCheck) return "checkmate"; return "stalemate"; } var pvString = " " + GetMoveSAN(move); MakeMove(move); var hashNode = g_hashTable[g_hashKeyLow & g_hashMask]; if (hashNode != null && hashNode.lock == g_hashKeyHigh && hashNode.bestMove != null) { pvString += PVFromHash(hashNode.bestMove, ply - 1); } UnmakeMove(move); return pvString; } // // Searching code // var g_startTime; var g_nodeCount; var g_qNodeCount; var g_searchValid; var g_globalPly = 0; function Search(finishMoveCallback, maxPly, finishPlyCallback) { var lastEval; var alpha = minEval; var beta = maxEval; g_globalPly++; g_nodeCount = 0; g_qNodeCount = 0; g_searchValid = true; var bestMove = 0; var value; g_startTime = (new Date()).getTime(); var i; for (i = 1; i <= maxPly && g_searchValid; i++) { var tmp = AlphaBeta(i, 0, alpha, beta); if (!g_searchValid) break; value = tmp; if (value > alpha && value < beta) { alpha = value - 500; beta = value + 500; if (alpha < minEval) alpha = minEval; if (beta > maxEval) beta = maxEval; } else if (alpha != minEval) { alpha = minEval; beta = maxEval; i--; } if (g_hashTable[g_hashKeyLow & g_hashMask] != null) { bestMove = g_hashTable[g_hashKeyLow & g_hashMask].bestMove; } if (finishPlyCallback != null) { finishPlyCallback(bestMove, value, (new Date()).getTime() - g_startTime, i); } } if (finishMoveCallback != null) { finishMoveCallback(bestMove, value, (new Date()).getTime() - g_startTime, i - 1); } } var minEval = -2000000; var maxEval = +2000000; var minMateBuffer = minEval + 2000; var maxMateBuffer = maxEval - 2000; var materialTable = [0, 800, 3350, 3450, 5000, 9750, 600000]; var pawnAdj = [ 0, 0, 0, 0, 0, 0, 0, 0, -25, 105, 135, 270, 270, 135, 105, -25, -80, 0, 30, 176, 176, 30, 0, -80, -85, -5, 25, 175, 175, 25, -5, -85, -90, -10, 20, 125, 125, 20, -10, -90, -95, -15, 15, 75, 75, 15, -15, -95, -100, -20, 10, 70, 70, 10, -20, -100, 0, 0, 0, 0, 0, 0, 0, 0 ]; var knightAdj = [-200, -100, -50, -50, -50, -50, -100, -200, -100, 0, 0, 0, 0, 0, 0, -100, -50, 0, 60, 60, 60, 60, 0, -50, -50, 0, 30, 60, 60, 30, 0, -50, -50, 0, 30, 60, 60, 30, 0, -50, -50, 0, 30, 30, 30, 30, 0, -50, -100, 0, 0, 0, 0, 0, 0, -100, -200, -50, -25, -25, -25, -25, -50, -200 ]; var bishopAdj = [ -50,-50,-25,-10,-10,-25,-50,-50, -50,-25,-10, 0, 0,-10,-25,-50, -25,-10, 0, 25, 25, 0,-10,-25, -10, 0, 25, 40, 40, 25, 0,-10, -10, 0, 25, 40, 40, 25, 0,-10, -25,-10, 0, 25, 25, 0,-10,-25, -50,-25,-10, 0, 0,-10,-25,-50, -50,-50,-25,-10,-10,-25,-50,-50 ]; var rookAdj = [ -60, -30, -10, 20, 20, -10, -30, -60, 40, 70, 90,120,120, 90, 70, 40, -60, -30, -10, 20, 20, -10, -30, -60, -60, -30, -10, 20, 20, -10, -30, -60, -60, -30, -10, 20, 20, -10, -30, -60, -60, -30, -10, 20, 20, -10, -30, -60, -60, -30, -10, 20, 20, -10, -30, -60, -60, -30, -10, 20, 20, -10, -30, -60 ]; var kingAdj = [ 50, 150, -25, -125, -125, -25, 150, 50, 50, 150, -25, -125, -125, -25, 150, 50, 50, 150, -25, -125, -125, -25, 150, 50, 50, 150, -25, -125, -125, -25, 150, 50, 50, 150, -25, -125, -125, -25, 150, 50, 50, 150, -25, -125, -125, -25, 150, 50, 50, 150, -25, -125, -125, -25, 150, 50, 150, 250, 75, -25, -25, 75, 250, 150 ]; var emptyAdj = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; var pieceSquareAdj = new Array(8); // Returns the square flipped var flipTable = new Array(256); function PawnEval(color) { var pieceIdx = (color | 1) << 4; var from = g_pieceList[pieceIdx++]; while (from != 0) { from = g_pieceList[pieceIdx++]; } } function Mobility(color) { var result = 0; var from, to, mob, pieceIdx; var enemy = color == 8 ? 0x10 : 0x8 var mobUnit = color == 8 ? g_mobUnit[0] : g_mobUnit[1]; // Knight mobility mob = -3; pieceIdx = (color | 2) << 4; from = g_pieceList[pieceIdx++]; while (from != 0) { mob += mobUnit[g_board[from + 31]]; mob += mobUnit[g_board[from + 33]]; mob += mobUnit[g_board[from + 14]]; mob += mobUnit[g_board[from - 14]]; mob += mobUnit[g_board[from - 31]]; mob += mobUnit[g_board[from - 33]]; mob += mobUnit[g_board[from + 18]]; mob += mobUnit[g_board[from - 18]]; from = g_pieceList[pieceIdx++]; } result += 65 * mob; // Bishop mobility mob = -4; pieceIdx = (color | 3) << 4; from = g_pieceList[pieceIdx++]; while (from != 0) { to = from - 15; while (g_board[to] == 0) { to -= 15; mob++; } if (g_board[to] & enemy) { mob++; if (!(g_board[to] & piecePawn)) { to -= 15; while (g_board[to] == 0) to -= 15; mob += mobUnit[g_board[to]] << 2; } } to = from - 17; while (g_board[to] == 0) { to -= 17; mob++; } if (g_board[to] & enemy) { mob++; if (!(g_board[to] & piecePawn)) { to -= 17; while (g_board[to] == 0) to -= 17; mob += mobUnit[g_board[to]] << 2; } } to = from + 15; while (g_board[to] == 0) { to += 15; mob++; } if (g_board[to] & enemy) { mob++; if (!(g_board[to] & piecePawn)) { to += 15; while (g_board[to] == 0) to += 15; mob += mobUnit[g_board[to]] << 2; } } to = from + 17; while (g_board[to] == 0) { to += 17; mob++; } if (g_board[to] & enemy) { mob++; if (!(g_board[to] & piecePawn)) { to += 17; while (g_board[to] == 0) to += 17; mob += mobUnit[g_board[to]] << 2; } } from = g_pieceList[pieceIdx++]; } result += 44 * mob; // Rook mobility mob = -4; pieceIdx = (color | 4) << 4; from = g_pieceList[pieceIdx++]; while (from != 0) { to = from - 1; while (g_board[to] == 0) { to--; mob++;} if (g_board[to] & enemy) mob++; to = from + 1; while (g_board[to] == 0) { to++; mob++; } if (g_board[to] & enemy) mob++; to = from + 16; while (g_board[to] == 0) { to += 16; mob++; } if (g_board[to] & enemy) mob++; to = from - 16; while (g_board[to] == 0) { to -= 16; mob++; } if (g_board[to] & enemy) mob++; from = g_pieceList[pieceIdx++]; } result += 25 * mob; // Queen mobility mob = -2; pieceIdx = (color | 5) << 4; from = g_pieceList[pieceIdx++]; while (from != 0) { to = from - 15; while (g_board[to] == 0) { to -= 15; mob++; } if (g_board[to] & enemy) mob++; to = from - 17; while (g_board[to] == 0) { to -= 17; mob++; } if (g_board[to] & enemy) mob++; to = from + 15; while (g_board[to] == 0) { to += 15; mob++; } if (g_board[to] & enemy) mob++; to = from + 17; while (g_board[to] == 0) { to += 17; mob++; } if (g_board[to] & enemy) mob++; to = from - 1; while (g_board[to] == 0) { to--; mob++; } if (g_board[to] & enemy) mob++; to = from + 1; while (g_board[to] == 0) { to++; mob++; } if (g_board[to] & enemy) mob++; to = from + 16; while (g_board[to] == 0) { to += 16; mob++; } if (g_board[to] & enemy) mob++; to = from - 16; while (g_board[to] == 0) { to -= 16; mob++; } if (g_board[to] & enemy) mob++; from = g_pieceList[pieceIdx++]; } result += 22 * mob; return result; } function Evaluate() { var curEval = g_baseEval; var evalAdjust = 0; // Black queen gone, then cancel white's penalty for king movement if (g_pieceList[pieceQueen << 4] == 0) evalAdjust -= pieceSquareAdj[pieceKing][g_pieceList[(colorWhite | pieceKing) << 4]]; // White queen gone, then cancel black's penalty for king movement if (g_pieceList[(colorWhite | pieceQueen) << 4] == 0) evalAdjust += pieceSquareAdj[pieceKing][flipTable[g_pieceList[pieceKing << 4]]]; // Black bishop pair if (g_pieceCount[pieceBishop] >= 2) evalAdjust -= 500; // White bishop pair if (g_pieceCount[pieceBishop | colorWhite] >= 2) evalAdjust += 500; var mobility = Mobility(8) - Mobility(0); if (g_toMove == 0) { // Black curEval -= mobility; curEval -= evalAdjust; } else { curEval += mobility; curEval += evalAdjust; } return curEval; } function ScoreMove(move){ var moveTo = (move >> 8) & 0xFF; var captured = g_board[moveTo] & 0x7; var piece = g_board[move & 0xFF]; var score; if (captured != 0) { var pieceType = piece & 0x7; score = (captured << 5) - pieceType; } else { score = historyTable[piece & 0xF][moveTo]; } return score; } function QSearch(alpha, beta, ply) { g_qNodeCount++; var realEval = g_inCheck ? (minEval + 1) : Evaluate(); if (realEval >= beta) return realEval; if (realEval > alpha) alpha = realEval; var moves = new Array(); var moveScores = new Array(); var wasInCheck = g_inCheck; if (wasInCheck) { // TODO: Fast check escape generator and fast checking moves generator GenerateCaptureMoves(moves, null); GenerateAllMoves(moves); for (var i = 0; i < moves.length; i++) { moveScores[i] = ScoreMove(moves[i]); } } else { GenerateCaptureMoves(moves, null); for (var i = 0; i < moves.length; i++) { var captured = g_board[(moves[i] >> 8) & 0xFF] & 0x7; var pieceType = g_board[moves[i] & 0xFF] & 0x7; moveScores[i] = (captured << 5) - pieceType; } } for (var i = 0; i < moves.length; i++) { var bestMove = i; for (var j = moves.length - 1; j > i; j--) { if (moveScores[j] > moveScores[bestMove]) { bestMove = j; } } { var tmpMove = moves[i]; moves[i] = moves[bestMove]; moves[bestMove] = tmpMove; var tmpScore = moveScores[i]; moveScores[i] = moveScores[bestMove]; moveScores[bestMove] = tmpScore; } if (!wasInCheck && !See(moves[i])) { continue; } if (!MakeMove(moves[i])) { continue; } var value = -QSearch(-beta, -alpha, ply - 1); UnmakeMove(moves[i]); if (value > realEval) { if (value >= beta) return value; if (value > alpha) alpha = value; realEval = value; } } /* Disable checks... Too slow currently if (ply == 0 && !wasInCheck) { moves = new Array(); GenerateAllMoves(moves); for (var i = 0; i < moves.length; i++) { moveScores[i] = ScoreMove(moves[i]); } for (var i = 0; i < moves.length; i++) { var bestMove = i; for (var j = moves.length - 1; j > i; j--) { if (moveScores[j] > moveScores[bestMove]) { bestMove = j; } } { var tmpMove = moves[i]; moves[i] = moves[bestMove]; moves[bestMove] = tmpMove; var tmpScore = moveScores[i]; moveScores[i] = moveScores[bestMove]; moveScores[bestMove] = tmpScore; } if (!MakeMove(moves[i])) { continue; } var checking = g_inCheck; UnmakeMove(moves[i]); if (!checking) { continue; } if (!See(moves[i])) { continue; } MakeMove(moves[i]); var value = -QSearch(-beta, -alpha, ply - 1); UnmakeMove(moves[i]); if (value > realEval) { if (value >= beta) return value; if (value > alpha) alpha = value; realEval = value; } } } */ return realEval; } function StoreHash(value, flags, ply, move, depth) { if (value >= maxMateBuffer) value += depth; else if (value <= minMateBuffer) value -= depth; g_hashTable[g_hashKeyLow & g_hashMask] = new HashEntry(g_hashKeyHigh, value, flags, ply, move); } function IsHashMoveValid(hashMove) { var from = hashMove & 0xFF; var to = (hashMove >> 8) & 0xFF; var ourPiece = g_board[from]; var pieceType = ourPiece & 0x7; if (pieceType < piecePawn || pieceType > pieceKing) return false; // Can't move a piece we don't control if (g_toMove != (ourPiece & 0x8)) return false; // Can't move to a square that has something of the same color if (g_board[to] != 0 && (g_toMove == (g_board[to] & 0x8))) return false; if (pieceType == piecePawn) { if (hashMove & moveflagEPC) { return false; } // Valid moves are push, capture, double push, promotions var dir = to - from; if ((g_toMove == colorWhite) != (dir < 0)) { // Pawns have to move in the right direction return false; } var row = to & 0xF0; if (((row == 0x90 && !g_toMove) || (row == 0x20 && g_toMove)) != (hashMove & moveflagPromotion)) { // Handle promotions return false; } if (dir == -16 || dir == 16) { // White/Black push return g_board[to] == 0; } else if (dir == -15 || dir == -17 || dir == 15 || dir == 17) { // White/Black capture return g_board[to] != 0; } else if (dir == -32) { // Double white push if (row != 0x60) return false; if (g_board[to] != 0) return false; if (g_board[from - 16] != 0) return false; } else if (dir == 32) { // Double black push if (row != 0x50) return false; if (g_board[to] != 0) return false; if (g_board[from + 16] != 0) return false; } else { return false; } return true; } else { // This validates that this piece type can actually make the attack if (hashMove >> 16) return false; return IsSquareAttackableFrom(to, from); } } function IsRepDraw() { var stop = g_moveCount - 1 - g_move50; stop = stop < 0 ? 0 : stop; for (var i = g_moveCount - 5; i >= stop; i -= 2) { if (g_repMoveStack[i] == g_hashKeyLow) return true; } return false; } function MovePicker(hashMove, depth, killer1, killer2) { this.hashMove = hashMove; this.depth = depth; this.killer1 = killer1; this.killer2 = killer2; this.moves = new Array(); this.losingCaptures = null; this.moveCount = 0; this.atMove = -1; this.moveScores = null; this.stage = 0; this.nextMove = function () { if (++this.atMove == this.moveCount) { this.stage++; if (this.stage == 1) { if (this.hashMove != null && IsHashMoveValid(hashMove)) { this.moves[0] = hashMove; this.moveCount = 1; } if (this.moveCount != 1) { this.hashMove = null; this.stage++; } } if (this.stage == 2) { GenerateCaptureMoves(this.moves, null); this.moveCount = this.moves.length; this.moveScores = new Array(this.moveCount); // Move ordering for (var i = this.atMove; i < this.moveCount; i++) { var captured = g_board[(this.moves[i] >> 8) & 0xFF] & 0x7; var pieceType = g_board[this.moves[i] & 0xFF] & 0x7; this.moveScores[i] = (captured << 5) - pieceType; } // No moves, onto next stage if (this.atMove == this.moveCount) this.stage++; } if (this.stage == 3) { if (IsHashMoveValid(this.killer1) && this.killer1 != this.hashMove) { this.moves[this.moves.length] = this.killer1; this.moveCount = this.moves.length; } else { this.killer1 = 0; this.stage++; } } if (this.stage == 4) { if (IsHashMoveValid(this.killer2) && this.killer2 != this.hashMove) { this.moves[this.moves.length] = this.killer2; this.moveCount = this.moves.length; } else { this.killer2 = 0; this.stage++; } } if (this.stage == 5) { GenerateAllMoves(this.moves); this.moveCount = this.moves.length; // Move ordering for (var i = this.atMove; i < this.moveCount; i++) this.moveScores[i] = ScoreMove(this.moves[i]); // No moves, onto next stage if (this.atMove == this.moveCount) this.stage++; } if (this.stage == 6) { // Losing captures if (this.losingCaptures != null) { for (var i = 0; i < this.losingCaptures.length; i++) { this.moves[this.moves.length] = this.losingCaptures[i]; } for (var i = this.atMove; i < this.moveCount; i++) this.moveScores[i] = ScoreMove(this.moves[i]); this.moveCount = this.moves.length; } // No moves, onto next stage if (this.atMove == this.moveCount) this.stage++; } if (this.stage == 7) return 0; } var bestMove = this.atMove; for (var j = this.atMove + 1; j < this.moveCount; j++) { if (this.moveScores[j] > this.moveScores[bestMove]) { bestMove = j; } } if (bestMove != this.atMove) { var tmpMove = this.moves[this.atMove]; this.moves[this.atMove] = this.moves[bestMove]; this.moves[bestMove] = tmpMove; var tmpScore = this.moveScores[this.atMove]; this.moveScores[this.atMove] = this.moveScores[bestMove]; this.moveScores[bestMove] = tmpScore; } var candidateMove = this.moves[this.atMove]; if ((this.stage > 1 && candidateMove == this.hashMove) || (this.stage > 3 && candidateMove == this.killer1) || (this.stage > 4 && candidateMove == this.killer2)) { return this.nextMove(); } if (this.stage == 2 && !See(candidateMove)) { if (this.losingCaptures == null) { this.losingCaptures = new Array(); } this.losingCaptures[this.losingCaptures.length] = candidateMove; return this.nextMove(); } return this.moves[this.atMove]; } } function AllCutNode(ply, depth, beta, allowNull) { if (ply <= 0) { return QSearch(beta - 1, beta, 0); } if ((g_nodeCount & 127) == 127) { if ((new Date()).getTime() - g_startTime > g_timeout) { // Time cutoff g_searchValid = false; return beta - 1; } } g_nodeCount++; if (IsRepDraw()) return 0; // Mate distance pruning if (minEval + depth >= beta) return beta; if (maxEval - (depth + 1) < beta) return beta - 1; var hashMove = null; var hashNode = g_hashTable[g_hashKeyLow & g_hashMask]; if (hashNode != null && hashNode.lock == g_hashKeyHigh) { hashMove = hashNode.bestMove; if (hashNode.hashDepth >= ply) { var hashValue = hashNode.value; // Fixup mate scores if (hashValue >= maxMateBuffer) hashValue -= depth; else if (hashValue <= minMateBuffer) hashValue += depth; if (hashNode.flags == hashflagExact) return hashValue; if (hashNode.flags == hashflagAlpha && hashValue < beta) return hashValue; if (hashNode.flags == hashflagBeta && hashValue >= beta) return hashValue; } } // TODO - positional gain? if (!g_inCheck && allowNull && beta > minMateBuffer && beta < maxMateBuffer) { // Try some razoring if (hashMove == null && ply < 4) { var razorMargin = 2500 + 200 * ply; if (g_baseEval < beta - razorMargin) { var razorBeta = beta - razorMargin; var v = QSearch(razorBeta - 1, razorBeta, 0); if (v < razorBeta) return v; } } // TODO - static null move // Null move if (ply > 1 && g_baseEval >= beta - (ply >= 4 ? 2500 : 0) && // Disable null move if potential zugzwang (no big pieces) (g_pieceCount[pieceBishop | g_toMove] != 0 || g_pieceCount[pieceKnight | g_toMove] != 0 || g_pieceCount[pieceRook | g_toMove] != 0 || g_pieceCount[pieceQueen | g_toMove] != 0)) { var r = 3 + (ply >= 5 ? 1 : ply / 4); if (g_baseEval - beta > 1500) r++; g_toMove = 8 - g_toMove; g_baseEval = -g_baseEval; g_hashKeyLow ^= g_zobristBlackLow; g_hashKeyHigh ^= g_zobristBlackHigh; var value = -AllCutNode(ply - r, depth + 1, -(beta - 1), false); g_hashKeyLow ^= g_zobristBlackLow; g_hashKeyHigh ^= g_zobristBlackHigh; g_toMove = 8 - g_toMove; g_baseEval = -g_baseEval; if (value >= beta) return beta; } } var moveMade = false; var realEval = minEval - 1; var inCheck = g_inCheck; var movePicker = new MovePicker(hashMove, depth, g_killers[depth][0], g_killers[depth][1]); for (;;) { var currentMove = movePicker.nextMove(); if (currentMove == 0) { break; } var plyToSearch = ply - 1; if (!MakeMove(currentMove)) { continue; } var value; var doFullSearch = true; if (g_inCheck) { // Check extensions plyToSearch++; } else { var reduced = plyToSearch - (movePicker.atMove > 14 ? 2 : 1); // Futility pruning /* if (movePicker.stage == 5 && !inCheck) { if (movePicker.atMove >= (15 + (1 << (5 * ply) >> 2)) && realEval > minMateBuffer) { UnmakeMove(currentMove); continue; } if (ply < 7) { var reducedPly = reduced <= 0 ? 0 : reduced; var futilityValue = -g_baseEval + (900 * (reducedPly + 2)) - (movePicker.atMove * 10); if (futilityValue < beta) { if (futilityValue > realEval) { realEval = futilityValue; } UnmakeMove(currentMove); continue; } } }*/ // Late move reductions if (movePicker.stage == 5 && movePicker.atMove > 5 && ply >= 3) { value = -AllCutNode(reduced, depth + 1, -(beta - 1), true); doFullSearch = (value >= beta); } } if (doFullSearch) { value = -AllCutNode(plyToSearch, depth + 1, -(beta - 1), true); } moveMade = true; UnmakeMove(currentMove); if (!g_searchValid) { return beta - 1; } if (value > realEval) { if (value >= beta) { var histTo = (currentMove >> 8) & 0xFF; if (g_board[histTo] == 0) { var histPiece = g_board[currentMove & 0xFF] & 0xF; historyTable[histPiece][histTo] += ply * ply; if (historyTable[histPiece][histTo] > 32767) { historyTable[histPiece][histTo] >>= 1; } if (g_killers[depth][0] != currentMove) { g_killers[depth][1] = g_killers[depth][0]; g_killers[depth][0] = currentMove; } } StoreHash(value, hashflagBeta, ply, currentMove, depth); return value; } realEval = value; hashMove = currentMove; } } if (!moveMade) { // If we have no valid moves it's either stalemate or checkmate if (g_inCheck) // Checkmate. return minEval + depth; else // Stalemate return 0; } StoreHash(realEval, hashflagAlpha, ply, hashMove, depth); return realEval; } function AlphaBeta(ply, depth, alpha, beta) { if (ply <= 0) { return QSearch(alpha, beta, 0); } g_nodeCount++; if (depth > 0 && IsRepDraw()) return 0; // Mate distance pruning var oldAlpha = alpha; alpha = alpha < minEval + depth ? alpha : minEval + depth; beta = beta > maxEval - (depth + 1) ? beta : maxEval - (depth + 1); if (alpha >= beta) return alpha; var hashMove = null; var hashFlag = hashflagAlpha; var hashNode = g_hashTable[g_hashKeyLow & g_hashMask]; if (hashNode != null && hashNode.lock == g_hashKeyHigh) { hashMove = hashNode.bestMove; } var inCheck = g_inCheck; var moveMade = false; var realEval = minEval; var movePicker = new MovePicker(hashMove, depth, g_killers[depth][0], g_killers[depth][1]); for (;;) { var currentMove = movePicker.nextMove(); if (currentMove == 0) { break; } var plyToSearch = ply - 1; if (!MakeMove(currentMove)) { continue; } if (g_inCheck) { // Check extensions plyToSearch++; } var value; if (moveMade) { value = -AllCutNode(plyToSearch, depth + 1, -alpha, true); if (value > alpha) { value = -AlphaBeta(plyToSearch, depth + 1, -beta, -alpha); } } else { value = -AlphaBeta(plyToSearch, depth + 1, -beta, -alpha); } moveMade = true; UnmakeMove(currentMove); if (!g_searchValid) { return alpha; } if (value > realEval) { if (value >= beta) { var histTo = (currentMove >> 8) & 0xFF; if (g_board[histTo] == 0) { var histPiece = g_board[currentMove & 0xFF] & 0xF; historyTable[histPiece][histTo] += ply * ply; if (historyTable[histPiece][histTo] > 32767) { historyTable[histPiece][histTo] >>= 1; } if (g_killers[depth][0] != currentMove) { g_killers[depth][1] = g_killers[depth][0]; g_killers[depth][0] = currentMove; } } StoreHash(value, hashflagBeta, ply, currentMove, depth); return value; } if (value > oldAlpha) { hashFlag = hashflagExact; alpha = value; } realEval = value; hashMove = currentMove; } } if (!moveMade) { // If we have no valid moves it's either stalemate or checkmate if (inCheck) // Checkmate. return minEval + depth; else // Stalemate return 0; } StoreHash(realEval, hashFlag, ply, hashMove, depth); return realEval; } // // Board code // // This somewhat funky scheme means that a piece is indexed by it's lower 4 bits when accessing in arrays. The fifth bit (black bit) // is used to allow quick edge testing on the board. var colorBlack = 0x10; var colorWhite = 0x08; var pieceEmpty = 0x00; var piecePawn = 0x01; var pieceKnight = 0x02; var pieceBishop = 0x03; var pieceRook = 0x04; var pieceQueen = 0x05; var pieceKing = 0x06; var g_vectorDelta = new Array(256); var g_bishopDeltas = [-15, -17, 15, 17]; var g_knightDeltas = [31, 33, 14, -14, -31, -33, 18, -18]; var g_rookDeltas = [-1, +1, -16, +16]; var g_queenDeltas = [-1, +1, -15, +15, -17, +17, -16, +16]; var g_castleRightsMask = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,15,15,15, 3,15,15,11, 0, 0, 0, 0, 0, 0, 0, 0,15,15,15,15,15,15,15,15, 0, 0, 0, 0, 0, 0, 0, 0,15,15,15,15,15,15,15,15, 0, 0, 0, 0, 0, 0, 0, 0,15,15,15,15,15,15,15,15, 0, 0, 0, 0, 0, 0, 0, 0,15,15,15,15,15,15,15,15, 0, 0, 0, 0, 0, 0, 0, 0,15,15,15,15,15,15,15,15, 0, 0, 0, 0, 0, 0, 0, 0,15,15,15,15,15,15,15,15, 0, 0, 0, 0, 0, 0, 0, 0,13,15,15,15,12,15,15,14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; var moveflagEPC = 0x2 << 16; var moveflagCastleKing = 0x4 << 16; var moveflagCastleQueen = 0x8 << 16; var moveflagPromotion = 0x10 << 16; var moveflagPromoteRook = 0x00 << 16; var moveflagPromoteKnight = 0x20 << 16; var moveflagPromoteQueen = 0x40 << 16; var moveflagPromoteBishop = 0x80 << 16; function MT() { var N = 624; var M = 397; var MAG01 = [0x0, 0x9908b0df]; this.mt = new Array(N); this.mti = N + 1; this.setSeed = function() { var a = arguments; switch (a.length) { case 1: if (a[0].constructor === Number) { this.mt[0]= a[0]; for (var i = 1; i < N; ++i) { var s = this.mt[i - 1] ^ (this.mt[i - 1] >>> 30); this.mt[i] = ((1812433253 * ((s & 0xffff0000) >>> 16)) << 16) + 1812433253 * (s & 0x0000ffff) + i; } this.mti = N; return; } this.setSeed(19650218); var l = a[0].length; var i = 1; var j = 0; for (var k = N > l ? N : l; k != 0; --k) { var s = this.mt[i - 1] ^ (this.mt[i - 1] >>> 30) this.mt[i] = (this.mt[i] ^ (((1664525 * ((s & 0xffff0000) >>> 16)) << 16) + 1664525 * (s & 0x0000ffff))) + a[0][j] + j; if (++i >= N) { this.mt[0] = this.mt[N - 1]; i = 1; } if (++j >= l) { j = 0; } } for (var k = N - 1; k != 0; --k) { var s = this.mt[i - 1] ^ (this.mt[i - 1] >>> 30); this.mt[i] = (this.mt[i] ^ (((1566083941 * ((s & 0xffff0000) >>> 16)) << 16) + 1566083941 * (s & 0x0000ffff))) - i; if (++i >= N) { this.mt[0] = this.mt[N-1]; i = 1; } } this.mt[0] = 0x80000000; return; default: var seeds = new Array(); for (var i = 0; i < a.length; ++i) { seeds.push(a[i]); } this.setSeed(seeds); return; } } this.setSeed(0x1BADF00D); this.next = function (bits) { if (this.mti >= N) { var x = 0; for (var k = 0; k < N - M; ++k) { x = (this.mt[k] & 0x80000000) | (this.mt[k + 1] & 0x7fffffff); this.mt[k] = this.mt[k + M] ^ (x >>> 1) ^ MAG01[x & 0x1]; } for (var k = N - M; k < N - 1; ++k) { x = (this.mt[k] & 0x80000000) | (this.mt[k + 1] & 0x7fffffff); this.mt[k] = this.mt[k + (M - N)] ^ (x >>> 1) ^ MAG01[x & 0x1]; } x = (this.mt[N - 1] & 0x80000000) | (this.mt[0] & 0x7fffffff); this.mt[N - 1] = this.mt[M - 1] ^ (x >>> 1) ^ MAG01[x & 0x1]; this.mti = 0; } var y = this.mt[this.mti++]; y ^= y >>> 11; y ^= (y << 7) & 0x9d2c5680; y ^= (y << 15) & 0xefc60000; y ^= y >>> 18; return (y >>> (32 - bits)) & 0xFFFFFFFF; } } // Position variables var g_board = new Array(256); // Sentinel 0x80, pieces are in low 4 bits, 0x8 for color, 0x7 bits for piece type var g_toMove; // side to move, 0 or 8, 0 = black, 8 = white var g_castleRights; // bitmask representing castling rights, 1 = wk, 2 = wq, 4 = bk, 8 = bq var g_enPassentSquare; var g_baseEval; var g_hashKeyLow, g_hashKeyHigh; var g_inCheck; // Utility variables var g_moveCount = 0; var g_moveUndoStack = new Array(); var g_move50 = 0; var g_repMoveStack = new Array(); var g_hashSize = 1 << 22; var g_hashMask = g_hashSize - 1; var g_hashTable; var g_killers; var historyTable = new Array(32); var g_zobristLow; var g_zobristHigh; var g_zobristBlackLow; var g_zobristBlackHigh; // Evaulation variables var g_mobUnit; var hashflagAlpha = 1; var hashflagBeta = 2; var hashflagExact = 3; function HashEntry(lock, value, flags, hashDepth, bestMove, globalPly) { this.lock = lock; this.value = value; this.flags = flags; this.hashDepth = hashDepth; this.bestMove = bestMove; } function MakeSquare(row, column) { return ((row + 2) << 4) | (column + 4); } function MakeTable(table) { var result = new Array(256); for (var i = 0; i < 256; i++) { result[i] = 0; } for (var row = 0; row < 8; row++) { for (var col = 0; col < 8; col++) { result[MakeSquare(row, col)] = table[row * 8 + col]; } } return result; } function ResetGame(fen) { g_killers = new Array(128); for (var i = 0; i < 128; i++) { g_killers[i] = [0, 0]; } g_hashTable = new Array(g_hashSize); for (var i = 0; i < 32; i++) { historyTable[i] = new Array(256); for (var j = 0; j < 256; j++) historyTable[i][j] = 0; } var mt = new MT(0x1badf00d); g_zobristLow = new Array(256); g_zobristHigh = new Array(256); for (var i = 0; i < 256; i++) { g_zobristLow[i] = new Array(16); g_zobristHigh[i] = new Array(16); for (var j = 0; j < 16; j++) { g_zobristLow[i][j] = mt.next(32); g_zobristHigh[i][j] = mt.next(32); } } g_zobristBlackLow = mt.next(32); g_zobristBlackHigh = mt.next(32); for (var row = 0; row < 8; row++) { for (var col = 0; col < 8; col++) { var square = MakeSquare(row, col); flipTable[square] = MakeSquare(7 - row, col); } } pieceSquareAdj[piecePawn] = MakeTable(pawnAdj); pieceSquareAdj[pieceKnight] = MakeTable(knightAdj); pieceSquareAdj[pieceBishop] = MakeTable(bishopAdj); pieceSquareAdj[pieceRook] = MakeTable(rookAdj); pieceSquareAdj[pieceQueen] = MakeTable(emptyAdj); pieceSquareAdj[pieceKing] = MakeTable(kingAdj); var pieceDeltas = [[], [], g_knightDeltas, g_bishopDeltas, g_rookDeltas, g_queenDeltas, g_queenDeltas]; for (var i = 0; i < 256; i++) { g_vectorDelta[i] = new Object(); g_vectorDelta[i].delta = 0; g_vectorDelta[i].pieceMask = new Array(2); g_vectorDelta[i].pieceMask[0] = 0; g_vectorDelta[i].pieceMask[1] = 0; } // Initialize the vector delta table for (var row = 0; row < 0x80; row += 0x10) for (var col = 0; col < 0x8; col++) { var square = row | col; // Pawn moves var index = square - (square - 17) + 128; g_vectorDelta[index].pieceMask[colorWhite >> 3] |= (1 << piecePawn); index = square - (square - 15) + 128; g_vectorDelta[index].pieceMask[colorWhite >> 3] |= (1 << piecePawn); index = square - (square + 17) + 128; g_vectorDelta[index].pieceMask[0] |= (1 << piecePawn); index = square - (square + 15) + 128; g_vectorDelta[index].pieceMask[0] |= (1 << piecePawn); for (var i = pieceKnight; i <= pieceKing; i++) { for (var dir = 0; dir < pieceDeltas[i].length; dir++) { var target = square + pieceDeltas[i][dir]; while (!(target & 0x88)) { index = square - target + 128; g_vectorDelta[index].pieceMask[colorWhite >> 3] |= (1 << i); g_vectorDelta[index].pieceMask[0] |= (1 << i); var flip = -1; if (square < target) flip = 1; if ((square & 0xF0) == (target & 0xF0)) { // On the same row g_vectorDelta[index].delta = flip * 1; } else if ((square & 0x0F) == (target & 0x0F)) { // On the same column g_vectorDelta[index].delta = flip * 16; } else if ((square % 15) == (target % 15)) { g_vectorDelta[index].delta = flip * 15; } else if ((square % 17) == (target % 17)) { g_vectorDelta[index].delta = flip * 17; } if (i == pieceKnight) { g_vectorDelta[index].delta = pieceDeltas[i][dir]; break; } if (i == pieceKing) break; target += pieceDeltas[i][dir]; } } } } InitializeEval(); InitializeFromFen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"); } function InitializeEval() { g_mobUnit = new Array(2); for (var i = 0; i < 2; i++) { g_mobUnit[i] = new Array(); var enemy = i == 0 ? 0x10 : 8; var friend = i == 0 ? 8 : 0x10; g_mobUnit[i][0] = 1; g_mobUnit[i][0x80] = 0; g_mobUnit[i][enemy | piecePawn] = 1; g_mobUnit[i][enemy | pieceBishop] = 2; g_mobUnit[i][enemy | pieceKnight] = 2; g_mobUnit[i][enemy | pieceRook] = 4; g_mobUnit[i][enemy | pieceQueen] = 6; g_mobUnit[i][enemy | pieceKing] = 6; g_mobUnit[i][friend | piecePawn] = 0; g_mobUnit[i][friend | pieceBishop] = 0; g_mobUnit[i][friend | pieceKnight] = 0; g_mobUnit[i][friend | pieceRook] = 0; g_mobUnit[i][friend | pieceQueen] = 0; g_mobUnit[i][friend | pieceKing] = 0; } } function SetHash() { var result = new Object(); result.hashKeyLow = 0; result.hashKeyHigh = 0; for (var i = 0; i < 256; i++) { var piece = g_board[i]; if (piece & 0x18) { result.hashKeyLow ^= g_zobristLow[i][piece & 0xF] result.hashKeyHigh ^= g_zobristHigh[i][piece & 0xF] } } if (!g_toMove) { result.hashKeyLow ^= g_zobristBlackLow; result.hashKeyHigh ^= g_zobristBlackHigh; } return result; } function InitializeFromFen(fen) { var chunks = fen.split(' '); for (var i = 0; i < 256; i++) g_board[i] = 0x80; var row = 0; var col = 0; var pieces = chunks[0]; for (var i = 0; i < pieces.length; i++) { var c = pieces.charAt(i); if (c == '/') { row++; col = 0; } else { if (c >= '0' && c <= '9') { for (var j = 0; j < parseInt(c); j++) { g_board[MakeSquare(row, col)] = 0; col++; } } else { var isBlack = c >= 'a' && c <= 'z'; var piece = isBlack ? colorBlack : colorWhite; if (!isBlack) c = pieces.toLowerCase().charAt(i); switch (c) { case 'p': piece |= piecePawn; break; case 'b': piece |= pieceBishop; break; case 'n': piece |= pieceKnight; break; case 'r': piece |= pieceRook; break; case 'q': piece |= pieceQueen; break; case 'k': piece |= pieceKing; break; } g_board[MakeSquare(row, col)] = piece; col++; } } } InitializePieceList(); g_toMove = chunks[1].charAt(0) == 'w' ? colorWhite : 0; var them = 8 - g_toMove; g_castleRights = 0; if (chunks[2].indexOf('K') != -1) { if (g_board[MakeSquare(7, 4)] != (pieceKing | colorWhite) || g_board[MakeSquare(7, 7)] != (pieceRook | colorWhite)) { return 'Invalid FEN: White kingside castling not allowed'; } g_castleRights |= 1; } if (chunks[2].indexOf('Q') != -1) { if (g_board[MakeSquare(7, 4)] != (pieceKing | colorWhite) || g_board[MakeSquare(7, 0)] != (pieceRook | colorWhite)) { return 'Invalid FEN: White queenside castling not allowed'; } g_castleRights |= 2; } if (chunks[2].indexOf('k') != -1) { if (g_board[MakeSquare(0, 4)] != (pieceKing | colorBlack) || g_board[MakeSquare(0, 7)] != (pieceRook | colorBlack)) { return 'Invalid FEN: Black kingside castling not allowed'; } g_castleRights |= 4; } if (chunks[2].indexOf('q') != -1) { if (g_board[MakeSquare(0, 4)] != (pieceKing | colorBlack) || g_board[MakeSquare(0, 0)] != (pieceRook | colorBlack)) { return 'Invalid FEN: Black queenside castling not allowed'; } g_castleRights |= 8; } g_enPassentSquare = -1; if (chunks[3].indexOf('-') == -1) { var col = chunks[3].charAt(0).charCodeAt() - 'a'.charCodeAt(); var row = 8 - (chunks[3].charAt(1).charCodeAt() - '0'.charCodeAt()); g_enPassentSquare = MakeSquare(row, col); } var hashResult = SetHash(); g_hashKeyLow = hashResult.hashKeyLow; g_hashKeyHigh = hashResult.hashKeyHigh; g_baseEval = 0; for (var i = 0; i < 256; i++) { if (g_board[i] & colorWhite) { g_baseEval += pieceSquareAdj[g_board[i] & 0x7][i]; g_baseEval += materialTable[g_board[i] & 0x7]; } else if (g_board[i] & colorBlack) { g_baseEval -= pieceSquareAdj[g_board[i] & 0x7][flipTable[i]]; g_baseEval -= materialTable[g_board[i] & 0x7]; } } if (!g_toMove) g_baseEval = -g_baseEval; g_move50 = 0; g_inCheck = IsSquareAttackable(g_pieceList[(g_toMove | pieceKing) << 4], them); // Check for king capture (invalid FEN) if (IsSquareAttackable(g_pieceList[(them | pieceKing) << 4], g_toMove)) { return 'Invalid FEN: Can capture king'; } // Checkmate/stalemate if (GenerateValidMoves().length == 0) { return g_inCheck ? 'Checkmate' : 'Stalemate'; } return ''; } var g_pieceIndex = new Array(256); var g_pieceList = new Array(2 * 8 * 16); var g_pieceCount = new Array(2 * 8); function InitializePieceList() { for (var i = 0; i < 16; i++) { g_pieceCount[i] = 0; for (var j = 0; j < 16; j++) { // 0 is used as the terminator for piece lists g_pieceList[(i << 4) | j] = 0; } } for (var i = 0; i < 256; i++) { g_pieceIndex[i] = 0; if (g_board[i] & (colorWhite | colorBlack)) { var piece = g_board[i] & 0xF; g_pieceList[(piece << 4) | g_pieceCount[piece]] = i; g_pieceIndex[i] = g_pieceCount[piece]; g_pieceCount[piece]++; } } } function MakeMove(move){ // move format: // --flags-- ---to---- --from--- // 0000 0000 0000 0000 0000 0000 // g_board is a 256x256 array // representing the chess board // right in the middle of it // moveflagEPC = 0000 0010 0000 0000 0000 0000 // moveflagCastleKing = 0000 0100 0000 0000 0000 0000 // moveflagCastleQueen = 0000 1000 0000 0000 0000 0000 // moveflagPromotion = 0001 0000 0000 0000 0000 0000 // moveflagPromoteRook = 0000 0000 0000 0000 0000 0000 // moveflagPromoteKnight = 0010 0000 0000 0000 0000 0000 // moveflagPromoteQueen = 0100 0000 0000 0000 0000 0000 // moveflagPromoteBishop = 1000 0000 0000 0000 0000 0000 var me = g_toMove >> 3; var otherColor = 8 - g_toMove; var flags = move & 0xFF0000; var to = (move >> 8) & 0xFF; var from = move & 0xFF; var captured = g_board[to]; var piece = g_board[from]; var epcEnd = to; if (flags & moveflagEPC) { epcEnd = me ? (to + 0x10) : (to - 0x10); captured = g_board[epcEnd]; g_board[epcEnd] = pieceEmpty; } g_moveUndoStack[g_moveCount] = new UndoHistory(g_enPassentSquare, g_castleRights, g_inCheck, g_baseEval, g_hashKeyLow, g_hashKeyHigh, g_move50, captured); g_moveCount++; g_enPassentSquare = -1; if (flags) { if (flags & moveflagCastleKing) { if (IsSquareAttackable(from + 1, otherColor) || IsSquareAttackable(from + 2, otherColor)) { g_moveCount--; return false; } var rook = g_board[to + 1]; g_hashKeyLow ^= g_zobristLow[to + 1][rook & 0xF]; g_hashKeyHigh ^= g_zobristHigh[to + 1][rook & 0xF]; g_hashKeyLow ^= g_zobristLow[to - 1][rook & 0xF]; g_hashKeyHigh ^= g_zobristHigh[to - 1][rook & 0xF]; g_board[to - 1] = rook; g_board[to + 1] = pieceEmpty; g_baseEval -= pieceSquareAdj[rook & 0x7][me == 0 ? flipTable[to + 1] : (to + 1)]; g_baseEval += pieceSquareAdj[rook & 0x7][me == 0 ? flipTable[to - 1] : (to - 1)]; var rookIndex = g_pieceIndex[to + 1]; g_pieceIndex[to - 1] = rookIndex; g_pieceList[((rook & 0xF) << 4) | rookIndex] = to - 1; } else if (flags & moveflagCastleQueen) { if (IsSquareAttackable(from - 1, otherColor) || IsSquareAttackable(from - 2, otherColor)) { g_moveCount--; return false; } var rook = g_board[to - 2]; g_hashKeyLow ^= g_zobristLow[to -2][rook & 0xF]; g_hashKeyHigh ^= g_zobristHigh[to - 2][rook & 0xF]; g_hashKeyLow ^= g_zobristLow[to + 1][rook & 0xF]; g_hashKeyHigh ^= g_zobristHigh[to + 1][rook & 0xF]; g_board[to + 1] = rook; g_board[to - 2] = pieceEmpty; g_baseEval -= pieceSquareAdj[rook & 0x7][me == 0 ? flipTable[to - 2] : (to - 2)]; g_baseEval += pieceSquareAdj[rook & 0x7][me == 0 ? flipTable[to + 1] : (to + 1)]; var rookIndex = g_pieceIndex[to - 2]; g_pieceIndex[to + 1] = rookIndex; g_pieceList[((rook & 0xF) << 4) | rookIndex] = to + 1; } } if (captured) { // Remove our piece from the piece list var capturedType = captured & 0xF; g_pieceCount[capturedType]--; var lastPieceSquare = g_pieceList[(capturedType << 4) | g_pieceCount[capturedType]]; g_pieceIndex[lastPieceSquare] = g_pieceIndex[epcEnd]; g_pieceList[(capturedType << 4) | g_pieceIndex[lastPieceSquare]] = lastPieceSquare; g_pieceList[(capturedType << 4) | g_pieceCount[capturedType]] = 0; g_baseEval += materialTable[captured & 0x7]; g_baseEval += pieceSquareAdj[captured & 0x7][me ? flipTable[epcEnd] : epcEnd]; g_hashKeyLow ^= g_zobristLow[epcEnd][capturedType]; g_hashKeyHigh ^= g_zobristHigh[epcEnd][capturedType]; g_move50 = 0; } else if ((piece & 0x7) == piecePawn) { var diff = to - from; if (diff < 0) diff = -diff; if (diff > 16) { g_enPassentSquare = me ? (to + 0x10) : (to - 0x10); } g_move50 = 0; } g_hashKeyLow ^= g_zobristLow[from][piece & 0xF]; g_hashKeyHigh ^= g_zobristHigh[from][piece & 0xF]; g_hashKeyLow ^= g_zobristLow[to][piece & 0xF]; g_hashKeyHigh ^= g_zobristHigh[to][piece & 0xF]; g_hashKeyLow ^= g_zobristBlackLow; g_hashKeyHigh ^= g_zobristBlackHigh; g_castleRights &= g_castleRightsMask[from] & g_castleRightsMask[to]; g_baseEval -= pieceSquareAdj[piece & 0x7][me == 0 ? flipTable[from] : from]; // Move our piece in the piece list g_pieceIndex[to] = g_pieceIndex[from]; g_pieceList[((piece & 0xF) << 4) | g_pieceIndex[to]] = to; if (flags & moveflagPromotion) { var newPiece = piece & (~0x7); if (flags & moveflagPromoteKnight) newPiece |= pieceKnight; else if (flags & moveflagPromoteQueen) newPiece |= pieceQueen; else if (flags & moveflagPromoteBishop) newPiece |= pieceBishop; else newPiece |= pieceRook; g_hashKeyLow ^= g_zobristLow[to][piece & 0xF]; g_hashKeyHigh ^= g_zobristHigh[to][piece & 0xF]; g_board[to] = newPiece; g_hashKeyLow ^= g_zobristLow[to][newPiece & 0xF]; g_hashKeyHigh ^= g_zobristHigh[to][newPiece & 0xF]; g_baseEval += pieceSquareAdj[newPiece & 0x7][me == 0 ? flipTable[to] : to]; g_baseEval -= materialTable[piecePawn]; g_baseEval += materialTable[newPiece & 0x7]; var pawnType = piece & 0xF; var promoteType = newPiece & 0xF; g_pieceCount[pawnType]--; var lastPawnSquare = g_pieceList[(pawnType << 4) | g_pieceCount[pawnType]]; g_pieceIndex[lastPawnSquare] = g_pieceIndex[to]; g_pieceList[(pawnType << 4) | g_pieceIndex[lastPawnSquare]] = lastPawnSquare; g_pieceList[(pawnType << 4) | g_pieceCount[pawnType]] = 0; g_pieceIndex[to] = g_pieceCount[promoteType]; g_pieceList[(promoteType << 4) | g_pieceIndex[to]] = to; g_pieceCount[promoteType]++; } else { g_board[to] = g_board[from]; g_baseEval += pieceSquareAdj[piece & 0x7][me == 0 ? flipTable[to] : to]; } g_board[from] = pieceEmpty; g_toMove = otherColor; g_baseEval = -g_baseEval; if ((piece & 0x7) == pieceKing || g_inCheck) { if (IsSquareAttackable(g_pieceList[(pieceKing | (8 - g_toMove)) << 4], otherColor)) { UnmakeMove(move); return false; } } else { var kingPos = g_pieceList[(pieceKing | (8 - g_toMove)) << 4]; if (ExposesCheck(from, kingPos)) { UnmakeMove(move); return false; } if (epcEnd != to) { if (ExposesCheck(epcEnd, kingPos)) { UnmakeMove(move); return false; } } } g_inCheck = false; if (flags <= moveflagEPC) { var theirKingPos = g_pieceList[(pieceKing | g_toMove) << 4]; // First check if the piece we moved can attack the enemy king g_inCheck = IsSquareAttackableFrom(theirKingPos, to); if (!g_inCheck) { // Now check if the square we moved from exposes check on the enemy king g_inCheck = ExposesCheck(from, theirKingPos); if (!g_inCheck) { // Finally, ep. capture can cause another square to be exposed if (epcEnd != to) { g_inCheck = ExposesCheck(epcEnd, theirKingPos); } } } } else { // Castle or promotion, slow check g_inCheck = IsSquareAttackable(g_pieceList[(pieceKing | g_toMove) << 4], 8 - g_toMove); } g_repMoveStack[g_moveCount - 1] = g_hashKeyLow; g_move50++; return true; } function UnmakeMove(move){ g_toMove = 8 - g_toMove; g_baseEval = -g_baseEval; g_moveCount--; g_enPassentSquare = g_moveUndoStack[g_moveCount].ep; g_castleRights = g_moveUndoStack[g_moveCount].castleRights; g_inCheck = g_moveUndoStack[g_moveCount].inCheck; g_baseEval = g_moveUndoStack[g_moveCount].baseEval; g_hashKeyLow = g_moveUndoStack[g_moveCount].hashKeyLow; g_hashKeyHigh = g_moveUndoStack[g_moveCount].hashKeyHigh; g_move50 = g_moveUndoStack[g_moveCount].move50; var otherColor = 8 - g_toMove; var me = g_toMove >> 3; var them = otherColor >> 3; var flags = move & 0xFF0000; var captured = g_moveUndoStack[g_moveCount].captured; var to = (move >> 8) & 0xFF; var from = move & 0xFF; var piece = g_board[to]; if (flags) { if (flags & moveflagCastleKing) { var rook = g_board[to - 1]; g_board[to + 1] = rook; g_board[to - 1] = pieceEmpty; var rookIndex = g_pieceIndex[to - 1]; g_pieceIndex[to + 1] = rookIndex; g_pieceList[((rook & 0xF) << 4) | rookIndex] = to + 1; } else if (flags & moveflagCastleQueen) { var rook = g_board[to + 1]; g_board[to - 2] = rook; g_board[to + 1] = pieceEmpty; var rookIndex = g_pieceIndex[to + 1]; g_pieceIndex[to - 2] = rookIndex; g_pieceList[((rook & 0xF) << 4) | rookIndex] = to - 2; } } if (flags & moveflagPromotion) { piece = (g_board[to] & (~0x7)) | piecePawn; g_board[from] = piece; var pawnType = g_board[from] & 0xF; var promoteType = g_board[to] & 0xF; g_pieceCount[promoteType]--; var lastPromoteSquare = g_pieceList[(promoteType << 4) | g_pieceCount[promoteType]]; g_pieceIndex[lastPromoteSquare] = g_pieceIndex[to]; g_pieceList[(promoteType << 4) | g_pieceIndex[lastPromoteSquare]] = lastPromoteSquare; g_pieceList[(promoteType << 4) | g_pieceCount[promoteType]] = 0; g_pieceIndex[to] = g_pieceCount[pawnType]; g_pieceList[(pawnType << 4) | g_pieceIndex[to]] = to; g_pieceCount[pawnType]++; } else { g_board[from] = g_board[to]; } var epcEnd = to; if (flags & moveflagEPC) { if (g_toMove == colorWhite) epcEnd = to + 0x10; else epcEnd = to - 0x10; g_board[to] = pieceEmpty; } g_board[epcEnd] = captured; // Move our piece in the piece list g_pieceIndex[from] = g_pieceIndex[to]; g_pieceList[((piece & 0xF) << 4) | g_pieceIndex[from]] = from; if (captured) { // Restore our piece to the piece list var captureType = captured & 0xF; g_pieceIndex[epcEnd] = g_pieceCount[captureType]; g_pieceList[(captureType << 4) | g_pieceCount[captureType]] = epcEnd; g_pieceCount[captureType]++; } } function ExposesCheck(from, kingPos){ var index = kingPos - from + 128; // If a queen can't reach it, nobody can! if ((g_vectorDelta[index].pieceMask[0] & (1 << (pieceQueen))) != 0) { var delta = g_vectorDelta[index].delta; var pos = kingPos + delta; while (g_board[pos] == 0) pos += delta; var piece = g_board[pos]; if (((piece & (g_board[kingPos] ^ 0x18)) & 0x18) == 0) return false; // Now see if the piece can actually attack the king var backwardIndex = pos - kingPos + 128; return (g_vectorDelta[backwardIndex].pieceMask[(piece >> 3) & 1] & (1 << (piece & 0x7))) != 0; } return false; } function IsSquareOnPieceLine(target, from) { var index = from - target + 128; var piece = g_board[from]; return (g_vectorDelta[index].pieceMask[(piece >> 3) & 1] & (1 << (piece & 0x7))) ? true : false; } function IsSquareAttackableFrom(target, from){ var index = from - target + 128; var piece = g_board[from]; if (g_vectorDelta[index].pieceMask[(piece >> 3) & 1] & (1 << (piece & 0x7))) { // Yes, this square is pseudo-attackable. Now, check for real attack var inc = g_vectorDelta[index].delta; do { from += inc; if (from == target) return true; } while (g_board[from] == 0); } return false; } function IsSquareAttackable(target, color) { // Attackable by pawns? var inc = color ? -16 : 16; var pawn = (color ? colorWhite : colorBlack) | 1; if (g_board[target - (inc - 1)] == pawn) return true; if (g_board[target - (inc + 1)] == pawn) return true; // Attackable by pieces? for (var i = 2; i <= 6; i++) { var index = (color | i) << 4; var square = g_pieceList[index]; while (square != 0) { if (IsSquareAttackableFrom(target, square)) return true; square = g_pieceList[++index]; } } return false; } function GenerateMove(from, to) { return from | (to << 8); } function GenerateMove(from, to, flags){ return from | (to << 8) | flags; } function GenerateValidMoves() { var moveList = new Array(); var allMoves = new Array(); GenerateCaptureMoves(allMoves, null); GenerateAllMoves(allMoves); for (var i = allMoves.length - 1; i >= 0; i--) { if (MakeMove(allMoves[i])) { moveList[moveList.length] = allMoves[i]; UnmakeMove(allMoves[i]); } else { } } return moveList; } function GenerateAllMoves(moveStack) { var from, to, piece, pieceIdx; // Pawn quiet moves pieceIdx = (g_toMove | 1) << 4; from = g_pieceList[pieceIdx++]; while (from != 0) { GeneratePawnMoves(moveStack, from); from = g_pieceList[pieceIdx++]; } // Knight quiet moves pieceIdx = (g_toMove | 2) << 4; from = g_pieceList[pieceIdx++]; while (from != 0) { to = from + 31; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); to = from + 33; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); to = from + 14; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); to = from - 14; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); to = from - 31; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); to = from - 33; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); to = from + 18; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); to = from - 18; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); from = g_pieceList[pieceIdx++]; } // Bishop quiet moves pieceIdx = (g_toMove | 3) << 4; from = g_pieceList[pieceIdx++]; while (from != 0) { to = from - 15; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to -= 15; } to = from - 17; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to -= 17; } to = from + 15; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to += 15; } to = from + 17; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to += 17; } from = g_pieceList[pieceIdx++]; } // Rook quiet moves pieceIdx = (g_toMove | 4) << 4; from = g_pieceList[pieceIdx++]; while (from != 0) { to = from - 1; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to--; } to = from + 1; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to++; } to = from + 16; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to += 16; } to = from - 16; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to -= 16; } from = g_pieceList[pieceIdx++]; } // Queen quiet moves pieceIdx = (g_toMove | 5) << 4; from = g_pieceList[pieceIdx++]; while (from != 0) { to = from - 15; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to -= 15; } to = from - 17; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to -= 17; } to = from + 15; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to += 15; } to = from + 17; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to += 17; } to = from - 1; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to--; } to = from + 1; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to++; } to = from + 16; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to += 16; } to = from - 16; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to -= 16; } from = g_pieceList[pieceIdx++]; } // King quiet moves { pieceIdx = (g_toMove | 6) << 4; from = g_pieceList[pieceIdx]; to = from - 15; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); to = from - 17; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); to = from + 15; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); to = from + 17; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); to = from - 1; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); to = from + 1; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); to = from - 16; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); to = from + 16; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); if (!g_inCheck) { var castleRights = g_castleRights; if (!g_toMove) castleRights >>= 2; if (castleRights & 1) { // Kingside castle if (g_board[from + 1] == pieceEmpty && g_board[from + 2] == pieceEmpty) { moveStack[moveStack.length] = GenerateMove(from, from + 0x02, moveflagCastleKing); } } if (castleRights & 2) { // Queenside castle if (g_board[from - 1] == pieceEmpty && g_board[from - 2] == pieceEmpty && g_board[from - 3] == pieceEmpty) { moveStack[moveStack.length] = GenerateMove(from, from - 0x02, moveflagCastleQueen); } } } } } function GenerateCaptureMoves(moveStack, moveScores) { var from, to, piece, pieceIdx; var inc = (g_toMove == 8) ? -16 : 16; var enemy = g_toMove == 8 ? 0x10 : 0x8; // Pawn captures pieceIdx = (g_toMove | 1) << 4; from = g_pieceList[pieceIdx++]; while (from != 0) { to = from + inc - 1; if (g_board[to] & enemy) { MovePawnTo(moveStack, from, to); } to = from + inc + 1; if (g_board[to] & enemy) { MovePawnTo(moveStack, from, to); } from = g_pieceList[pieceIdx++]; } if (g_enPassentSquare != -1) { var inc = (g_toMove == colorWhite) ? -16 : 16; var pawn = g_toMove | piecePawn; var from = g_enPassentSquare - (inc + 1); if ((g_board[from] & 0xF) == pawn) { moveStack[moveStack.length] = GenerateMove(from, g_enPassentSquare, moveflagEPC); } from = g_enPassentSquare - (inc - 1); if ((g_board[from] & 0xF) == pawn) { moveStack[moveStack.length] = GenerateMove(from, g_enPassentSquare, moveflagEPC); } } // Knight captures pieceIdx = (g_toMove | 2) << 4; from = g_pieceList[pieceIdx++]; while (from != 0) { to = from + 31; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from + 33; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from + 14; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from - 14; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from - 31; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from - 33; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from + 18; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from - 18; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); from = g_pieceList[pieceIdx++]; } // Bishop captures pieceIdx = (g_toMove | 3) << 4; from = g_pieceList[pieceIdx++]; while (from != 0) { to = from; do { to -= 15; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from; do { to -= 17; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from; do { to += 15; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from; do { to += 17; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); from = g_pieceList[pieceIdx++]; } // Rook captures pieceIdx = (g_toMove | 4) << 4; from = g_pieceList[pieceIdx++]; while (from != 0) { to = from; do { to--; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from; do { to++; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from; do { to -= 16; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from; do { to += 16; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); from = g_pieceList[pieceIdx++]; } // Queen captures pieceIdx = (g_toMove | 5) << 4; from = g_pieceList[pieceIdx++]; while (from != 0) { to = from; do { to -= 15; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from; do { to -= 17; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from; do { to += 15; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from; do { to += 17; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from; do { to--; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from; do { to++; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from; do { to -= 16; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from; do { to += 16; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); from = g_pieceList[pieceIdx++]; } // King captures { pieceIdx = (g_toMove | 6) << 4; from = g_pieceList[pieceIdx]; to = from - 15; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from - 17; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from + 15; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from + 17; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from - 1; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from + 1; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from - 16; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from + 16; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); } } function MovePawnTo(moveStack, start, square) { var row = square & 0xF0; if ((row == 0x90) || (row == 0x20)) { moveStack[moveStack.length] = GenerateMove(start, square, moveflagPromotion | moveflagPromoteQueen); moveStack[moveStack.length] = GenerateMove(start, square, moveflagPromotion | moveflagPromoteKnight); moveStack[moveStack.length] = GenerateMove(start, square, moveflagPromotion | moveflagPromoteBishop); moveStack[moveStack.length] = GenerateMove(start, square, moveflagPromotion); } else { moveStack[moveStack.length] = GenerateMove(start, square, 0); } } function GeneratePawnMoves(moveStack, from) { var piece = g_board[from]; var color = piece & colorWhite; var inc = (color == colorWhite) ? -16 : 16; // Quiet pawn moves var to = from + inc; if (g_board[to] == 0) { MovePawnTo(moveStack, from, to, pieceEmpty); // Check if we can do a 2 square jump if ((((from & 0xF0) == 0x30) && color != colorWhite) || (((from & 0xF0) == 0x80) && color == colorWhite)) { to += inc; if (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); } } } } function UndoHistory(ep, castleRights, inCheck, baseEval, hashKeyLow, hashKeyHigh, move50, captured) { this.ep = ep; this.castleRights = castleRights; this.inCheck = inCheck; this.baseEval = baseEval; this.hashKeyLow = hashKeyLow; this.hashKeyHigh = hashKeyHigh; this.move50 = move50; this.captured = captured; } var g_seeValues = [0, 1, 3, 3, 5, 9, 900, 0, 0, 1, 3, 3, 5, 9, 900, 0]; function See(move) { var from = move & 0xFF; var to = (move >> 8) & 0xFF; var fromPiece = g_board[from]; var fromValue = g_seeValues[fromPiece & 0xF]; var toValue = g_seeValues[g_board[to] & 0xF]; if (fromValue <= toValue) { return true; } if (move >> 16) { // Castles, promotion, ep are always good return true; } var us = (fromPiece & colorWhite) ? colorWhite : 0; var them = 8 - us; // Pawn attacks // If any opponent pawns can capture back, this capture is probably not worthwhile (as we must be using knight or above). var inc = (fromPiece & colorWhite) ? -16 : 16; // Note: this is capture direction from to, so reversed from normal move direction if (((g_board[to + inc + 1] & 0xF) == (piecePawn | them)) || ((g_board[to + inc - 1] & 0xF) == (piecePawn | them))) { return false; } var themAttacks = new Array(); // Knight attacks // If any opponent knights can capture back, and the deficit we have to make up is greater than the knights value, // it's not worth it. We can capture on this square again, and the opponent doesn't have to capture back. var captureDeficit = fromValue - toValue; SeeAddKnightAttacks(to, them, themAttacks); if (themAttacks.length != 0 && captureDeficit > g_seeValues[pieceKnight]) { return false; } // Slider attacks g_board[from] = 0; for (var pieceType = pieceBishop; pieceType <= pieceQueen; pieceType++) { if (SeeAddSliderAttacks(to, them, themAttacks, pieceType)) { if (captureDeficit > g_seeValues[pieceType]) { g_board[from] = fromPiece; return false; } } } // Pawn defenses // At this point, we are sure we are making a "losing" capture. The opponent can not capture back with a // pawn. They cannot capture back with a minor/major and stand pat either. So, if we can capture with // a pawn, it's got to be a winning or equal capture. if (((g_board[to - inc + 1] & 0xF) == (piecePawn | us)) || ((g_board[to - inc - 1] & 0xF) == (piecePawn | us))) { g_board[from] = fromPiece; return true; } // King attacks SeeAddSliderAttacks(to, them, themAttacks, pieceKing); // Our attacks var usAttacks = new Array(); SeeAddKnightAttacks(to, us, usAttacks); for (var pieceType = pieceBishop; pieceType <= pieceKing; pieceType++) { SeeAddSliderAttacks(to, us, usAttacks, pieceType); } g_board[from] = fromPiece; // We are currently winning the amount of material of the captured piece, time to see if the opponent // can get it back somehow. We assume the opponent can capture our current piece in this score, which // simplifies the later code considerably. var seeValue = toValue - fromValue; for (; ; ) { var capturingPieceValue = 1000; var capturingPieceIndex = -1; // Find the least valuable piece of the opponent that can attack the square for (var i = 0; i < themAttacks.length; i++) { if (themAttacks[i] != 0) { var pieceValue = g_seeValues[g_board[themAttacks[i]] & 0x7]; if (pieceValue < capturingPieceValue) { capturingPieceValue = pieceValue; capturingPieceIndex = i; } } } if (capturingPieceIndex == -1) { // Opponent can't capture back, we win return true; } // Now, if seeValue < 0, the opponent is winning. If even after we take their piece, // we can't bring it back to 0, then we have lost this battle. seeValue += capturingPieceValue; if (seeValue < 0) { return false; } var capturingPieceSquare = themAttacks[capturingPieceIndex]; themAttacks[capturingPieceIndex] = 0; // Add any x-ray attackers SeeAddXrayAttack(to, capturingPieceSquare, us, usAttacks, themAttacks); // Our turn to capture capturingPieceValue = 1000; capturingPieceIndex = -1; // Find our least valuable piece that can attack the square for (var i = 0; i < usAttacks.length; i++) { if (usAttacks[i] != 0) { var pieceValue = g_seeValues[g_board[usAttacks[i]] & 0x7]; if (pieceValue < capturingPieceValue) { capturingPieceValue = pieceValue; capturingPieceIndex = i; } } } if (capturingPieceIndex == -1) { // We can't capture back, we lose :( return false; } // Assume our opponent can capture us back, and if we are still winning, we can stand-pat // here, and assume we've won. seeValue -= capturingPieceValue; if (seeValue >= 0) { return true; } capturingPieceSquare = usAttacks[capturingPieceIndex]; usAttacks[capturingPieceIndex] = 0; // Add any x-ray attackers SeeAddXrayAttack(to, capturingPieceSquare, us, usAttacks, themAttacks); } } function SeeAddXrayAttack(target, square, us, usAttacks, themAttacks) { var index = square - target + 128; var delta = -g_vectorDelta[index].delta; if (delta == 0) return; square += delta; while (g_board[square] == 0) { square += delta; } if ((g_board[square] & 0x18) && IsSquareOnPieceLine(target, square)) { if ((g_board[square] & 8) == us) { usAttacks[usAttacks.length] = square; } else { themAttacks[themAttacks.length] = square; } } } // target = attacking square, us = color of knights to look for, attacks = array to add squares to function SeeAddKnightAttacks(target, us, attacks) { var pieceIdx = (us | pieceKnight) << 4; var attackerSq = g_pieceList[pieceIdx++]; while (attackerSq != 0) { if (IsSquareOnPieceLine(target, attackerSq)) { attacks[attacks.length] = attackerSq; } attackerSq = g_pieceList[pieceIdx++]; } } function SeeAddSliderAttacks(target, us, attacks, pieceType) { var pieceIdx = (us | pieceType) << 4; var attackerSq = g_pieceList[pieceIdx++]; var hit = false; while (attackerSq != 0) { if (IsSquareAttackableFrom(target, attackerSq)) { attacks[attacks.length] = attackerSq; hit = true; } attackerSq = g_pieceList[pieceIdx++]; } return hit; } function BuildPVMessage(bestMove, value, timeTaken, ply) { var totalNodes = g_nodeCount + g_qNodeCount; return "Ply:" + ply + " Score:" + value + " Nodes:" + totalNodes + " NPS:" + ((totalNodes / (timeTaken / 1000)) | 0) + " " + PVFromHash(bestMove, 15); } ////////////////////////////////////////////////// // Test Harness ////////////////////////////////////////////////// function FinishPlyCallback(bestMove, value, timeTaken, ply) { postMessage("pv " + BuildPVMessage(bestMove, value, timeTaken, ply)); } function FinishMoveLocalTesting(bestMove, value, timeTaken, ply) { if (bestMove != null) { MakeMove(bestMove); postMessage(FormatMove(bestMove)); } } var needsReset = true; self.onmessage = function (e) { if (e.data == "go" || needsReset) { ResetGame(); needsReset = false; if (e.data == "go") return; } if (e.data.match("^position") == "position") { ResetGame(); var result = InitializeFromFen(e.data.substr(9, e.data.length - 9)); if (result.length != 0) { postMessage("message " + result); } } else if (e.data.match("^search") == "search") { g_timeout = parseInt(e.data.substr(7, e.data.length - 7), 10); Search(FinishMoveLocalTesting, 99, FinishPlyCallback); } else if (e.data == "analyze") { g_timeout = 99999999999; Search(null, 99, FinishPlyCallback); } else { MakeMove(GetMoveFromString(e.data)); } }
411
0.686534
1
0.686534
game-dev
MEDIA
0.630792
game-dev
0.891044
1
0.891044
ondras/trw
5,790
levels/dungeon.js
Game.Level.Dungeon = function(depth, previousLevel, previousCell) { Game.Level.call(this); this._depth = depth; this._maxDepth = 3; this._gardener = null; if (this._depth == this._maxDepth) { this._gardener = Game.Beings.create("gardener"); this._gardener.setChats(["Okay, so I murdered him. But it wasn't my idea! She promised me gold if I do it!"]); } this._playerLight = [140, 110, 60]; this._rooms = []; this._build(previousLevel, previousCell); this._initStory(); } Game.Level.Dungeon.extend(Game.Level); Game.Level.Dungeon.prototype._build = function(previousLevel, previousCell) { var w = 60, h = 26; var generator = new ROT.Map.Uniform(w, h); var bitMap = []; for (var i=0;i<w;i++) { bitMap[i] = []; } generator.create(function(x, y, type) { bitMap[x][y] = type; }); this._rooms = generator.getRooms(); var diffx = (ROT.RNG.getUniform() > 0.5 ? 1 : -1); var diffy = (ROT.RNG.getUniform() > 0.5 ? 1 : -1); var sort = function(a, b) { var ca = a.getCenter(); var cb = b.getCenter(); var dx = (ca[0]-cb[0]) * diffx; var dy = (ca[1]-cb[1]) * diffy; return dx+dy; } this._rooms.sort(sort); this._buildFromBitMap(bitMap, w, h); this._buildStaircases(previousLevel, previousCell); this._buildDoors(); this._buildItems(); this._buildBeings(); this.setSize(w, h); } Game.Level.Dungeon.prototype._buildStaircases = function(previousLevel, previousCell) { var center = this._rooms[0].getCenter(); var startCell = Game.Cells.create("staircase-up", {id: "previous"}); this.setCell(startCell, center[0], center[1]); this._portals["previous"] = { level: previousLevel, cell: previousCell } this.cells[(center[0]-1) + "," + center[1]].setId("start"); var center = this._rooms[this._rooms.length-1].getCenter(); if (this._depth == this._maxDepth) { this.setBeing(this._gardener, center[0], center[1]); } else { var endCell = Game.Cells.create("staircase-down", {id: "exit"}); this.setCell(endCell, center[0], center[1]); this.cells[(center[0]-1) + "," + center[1]].setId("from-dungeon"); } } Game.Level.Dungeon.prototype._buildFromBitMap = function(bitMap, w, h) { for (var i=0;i<w;i++) { for (var j=0;j<h;j++) { var value = bitMap[i][j]; switch (value) { case 0: var floor = Game.Cells.create("floor"); this.setCell(floor, i, j); break; case 1: var neighborCount = this._getNeighborCount(bitMap, i, j, 0); if (neighborCount > 0) { var wall = Game.Cells.create("stonewall"); this.setCell(wall, i, j); } break; } /* switch */ } } } Game.Level.Dungeon.prototype._getNeighborCount = function(bitMap, x, y, value) { var result = 0; for (var dx=-1; dx<=1; dx++) { for (var dy=-1; dy<=1; dy++) { if (!dx && !dy) { continue; } var i = x+dx; var j = y+dy; if (!bitMap[i]) { continue; } if (bitMap[i][j] === value) { result++; } } } return result; } Game.Level.Dungeon.prototype._buildDoors = function() { var callback = function(x, y) { var door = Game.Cells.create("door", {closed: ROT.RNG.getUniform() > 0.5}); this.setCell(door, x, y); } for (var i=0;i<this._rooms.length;i++) { this._rooms[i].getDoors(callback.bind(this)); } } Game.Level.Dungeon.prototype._buildBeings = function() { var cells = this._getFreeCells().randomize(); var beingCount = 3 + Math.floor(ROT.RNG.getUniform() * 3); for (var i=0;i<beingCount;i++) { var being = Game.Beings.createRandom({level:this._depth}).setHostile(true); var pos = cells[i].getPosition(); this.setBeing(being, pos[0], pos[1]); } } Game.Level.Dungeon.prototype._buildItems = function() { var cells = this._getFreeCells().randomize(); var itemCount = 3 + Math.floor(ROT.RNG.getUniform() * 3); for (var i=0;i<itemCount;i++) { var item = Game.Items.createRandom(); var pos = cells[i].getPosition(); this.setItem(item, pos[0], pos[1]); } } Game.Level.Dungeon.prototype._getFreeCells = function() { var result = []; for (var key in this.cells) { var cell = this.cells[key]; if (cell.getType() == "floor" && !this.items[key] && !this.beings[key]) { result.push(cell); } } return result; } Game.Level.Dungeon.prototype._initStory = function() { if (this._depth == 1) { this._addRule(function() { return true; }, function() { Game.story.newChapter("A castle dungeon, right. I guess it just won't work without a dungeon. Narrow corridors, rotten smell in the air, poor visibility. Just you wait, murderer, I'm coming!"); Game.story.setTask("Make your way through the dungeon and find the assassin."); return true; /* remove from rule list */ }); } if (this._depth == this._maxDepth) { this._addRule(function() { return this._gardener.chattedWith(); }, function() { this._gardener.setHostile(true); return true; }); this._addRule(function() { return !this._gardener.getHP(); }, function() { Game.storyFlags.gardenerDead = true; Game.story.newChapter("The gardener lies dead. Looks like the groom is avenged now. But my task is far from being over: if the gardener spoke truth, there is someone else behind this - and I have a feeling that I know who."); Game.story.setTask("Get back to the castle and find the bride."); return true; }); } else { this._addRule(function() { var key = Game.player.getPosition().join(","); return (this.cells[key].getId() == "exit"); }, function() { var dungeon = new Game.Level.Dungeon(this._depth+1, this, "from-dungeon"); this._portals["exit"] = { level: dungeon, direction: "fade" }; this._enterPortal("exit"); return true; }); } } Game.Level.Dungeon.prototype._welcomeBeing = function(being) { Game.Level.prototype._welcomeBeing.call(this, being); if (being == Game.player) { being.setLight(this._playerLight); } }
411
0.79441
1
0.79441
game-dev
MEDIA
0.851385
game-dev,testing-qa
0.879775
1
0.879775
CrazyVince/Hacking
2,913
Library/PackageCache/com.unity.collab-proxy@2.0.1/Editor/PlasticSCM/Views/PendingChanges/Changelists/MoveToChangelistMenuBuilder.cs
using System.Collections.Generic; using UnityEngine; using UnityEditor; using Codice.Client.BaseCommands; using Codice.Client.Commands; using Codice.CM.Common; using PlasticGui; using PlasticGui.WorkspaceWindow.PendingChanges.Changelists; using Unity.PlasticSCM.Editor.UI; namespace Unity.PlasticSCM.Editor.Views.PendingChanges.Changelists { internal class MoveToChangelistMenuBuilder { internal MoveToChangelistMenuBuilder( WorkspaceInfo wkInfo, IChangelistMenuOperations operations) { mWkInfo = wkInfo; mOperations = operations; } internal void BuildComponents() { mMoveToChangelistMenuItemContent = new GUIContent( PlasticLocalization.GetString(PlasticLocalization.Name.MoveToChangelist)); mNewChangelistMenuItemContent = new GUIContent(GetSubMenuText( PlasticLocalization.GetString(PlasticLocalization.Name.New))); } internal void UpdateMenuItems( GenericMenu menu, ChangelistMenuOperations operations, List<ChangeInfo> changes, List<ChangeListInfo> involvedChangelists) { if (!operations.HasFlag(ChangelistMenuOperations.MoveToChangelist)) { menu.AddDisabledItem(mMoveToChangelistMenuItemContent); return; } menu.AddItem( mNewChangelistMenuItemContent, false, () => NewChangelist_Click(changes)); List<string> targetChangelists = GetTargetChangelists. ForInvolvedChangelists(mWkInfo, involvedChangelists); if (targetChangelists.Count == 0) return; menu.AddSeparator(GetSubMenuText(string.Empty)); foreach (string changelist in targetChangelists) { menu.AddItem( new GUIContent(GetSubMenuText(changelist)), false, () => MoveToChangelist_Click(changes, changelist)); } } void NewChangelist_Click(List<ChangeInfo> changes) { mOperations.MoveToNewChangelist(changes); } void MoveToChangelist_Click(List<ChangeInfo> changes, string targetChangelist) { mOperations.MoveToChangelist(changes, targetChangelist); } static string GetSubMenuText(string subMenuName) { return UnityMenuItem.GetText( PlasticLocalization.GetString(PlasticLocalization.Name.MoveToChangelist), UnityMenuItem.EscapedText(subMenuName)); } GUIContent mMoveToChangelistMenuItemContent; GUIContent mNewChangelistMenuItemContent; readonly WorkspaceInfo mWkInfo; readonly IChangelistMenuOperations mOperations; } }
411
0.717768
1
0.717768
game-dev
MEDIA
0.624793
game-dev
0.877374
1
0.877374
narknon/FF7R2UProj
1,416
Source/EndGame/Public/EndParticleModuleCircleLocation.h
#pragma once #include "CoreMinimal.h" #include "Particles/Location/ParticleModuleLocationBase.h" #include "Distributions/DistributionFloat.h" #include "EndParticleModuleCircleLocation.generated.h" UCLASS(Blueprintable, EditInlineNew) class UEndParticleModuleCircleLocation : public UParticleModuleLocationBase { GENERATED_BODY() public: UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) FRawDistributionFloat m_Radius; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) float m_RadiusRandom; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) float m_BeginAngle; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) float m_BeginAngleRandom; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) float m_StepAngle; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) float m_StepAngleRandom; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) FRawDistributionFloat m_Velocity; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) float m_VelocityRandom; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) uint8 m_bReverseAngle: 1; UEndParticleModuleCircleLocation(); };
411
0.895838
1
0.895838
game-dev
MEDIA
0.92296
game-dev
0.521464
1
0.521464
goodow/realtime-store
2,548
src/main/java/com/goodow/realtime/store/server/StoreModule.java
/* * Copyright 2014 Goodow.com * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.goodow.realtime.store.server; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.Singleton; import com.google.inject.TypeLiteral; import com.google.inject.multibindings.MapBinder; import com.alienos.guice.VertxModule; import com.goodow.realtime.channel.server.impl.VertxPlatform; import com.goodow.realtime.operation.Transformer; import com.goodow.realtime.operation.impl.CollaborativeOperation; import com.goodow.realtime.operation.impl.CollaborativeTransformer; import com.goodow.realtime.store.server.impl.MemoryDeltaStorage; import com.goodow.realtime.store.server.persistence.RedisElasticSearchStorage; import org.vertx.java.core.Vertx; import org.vertx.java.core.json.JsonObject; import org.vertx.java.platform.Container; import java.util.Map; import javax.inject.Provider; public class StoreModule extends AbstractModule implements VertxModule { public static final long REPLY_TIMEOUT = 15 * 1000; private Vertx vertx; private Container container; @Override public void setContainer(Container container) { this.container = container; } @Override public void setVertx(Vertx vertx) { this.vertx = vertx; } @Override protected void configure() { VertxPlatform.register(vertx); bind(new TypeLiteral<Transformer<CollaborativeOperation>>() { }).to(CollaborativeTransformer.class); MapBinder<String, DeltaStorage> storages = MapBinder.newMapBinder(binder(), String.class, DeltaStorage.class); storages.addBinding("memory").to(MemoryDeltaStorage.class); storages.addBinding("redis-elasticsearch").to(RedisElasticSearchStorage.class); } @Provides @Singleton DeltaStorage provideMutationStorage (Map<String, Provider<DeltaStorage>> storages) { String storage = container.config().getObject("realtime_store", new JsonObject()) .getString("storage", "memory"); return storages.get(storage).get(); } }
411
0.847685
1
0.847685
game-dev
MEDIA
0.632866
game-dev
0.914131
1
0.914131
leezer3/OpenBVE
19,570
source/OpenBVE/Parsers/Script/TrackFollowingObjectParser.cs
using OpenBveApi.Interface; using OpenBveApi.Math; using OpenBveApi.Trains; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using TrainManager.Car; using TrainManager.Trains; using Path = OpenBveApi.Path; namespace OpenBve { internal static class TrackFollowingObjectParser { private static readonly CultureInfo culture = CultureInfo.InvariantCulture; private static TrainBase Train; /// <summary>Parses a track following object</summary> /// <param name="objectPath">Absolute path to the object folder of route data</param> /// <param name="fileName">The XML file to parse</param> internal static TrainBase ParseTrackFollowingObject(string objectPath, string fileName) { // The current XML file to load XDocument currentXML = XDocument.Load(fileName, LoadOptions.SetLineInfo); List<XElement> scriptedTrainElements = currentXML.XPathSelectElements("/openBVE/TrackFollowingObject").ToList(); // Check this file actually contains OpenBVE other train definition elements if (!scriptedTrainElements.Any()) { // We couldn't find any valid XML, so return false throw new InvalidDataException(); } foreach (XElement element in scriptedTrainElements) { ParseScriptedTrainNode(objectPath, fileName, element); } return Train; } /// <summary>Parses a base track following object node</summary> /// <param name="ObjectPath">Absolute path to the object folder of route data</param> /// <param name="FileName">The filename of the containing XML file</param> /// <param name="SectionElement">The XElement to parse</param> private static void ParseScriptedTrainNode(string ObjectPath, string FileName, XElement SectionElement) { string Section = SectionElement.Name.LocalName; string TrainDirectory = string.Empty; bool ConsistReversed = false; List<TravelData> Data = new List<TravelData>(); XElement trainNode = null; foreach (XElement KeyNode in SectionElement.Elements()) { string Key = KeyNode.Name.LocalName; int LineNumber = ((IXmlLineInfo)KeyNode).LineNumber; switch (Key.ToLowerInvariant()) { case "definition": Train = new ScriptedTrain(TrainState.Pending); ParseDefinitionNode(FileName, KeyNode, Train as ScriptedTrain); break; case "runinterval": case "pretrain": Train = new TrainBase(TrainState.Pending, TrainType.PreTrain); NumberFormats.TryParseDoubleVb6(KeyNode.Value, out Train.TimetableDelta); break; case "train": trainNode = KeyNode; break; case "points": case "stops": ParseTravelDataNodes(FileName, KeyNode, Data); break; default: Interface.AddMessage(MessageType.Warning, false, $"Unsupported key {Key} encountered in {Section} at line {LineNumber.ToString(culture)} in {FileName}"); break; } } if (trainNode != null) { ParseTrainNode(ObjectPath, FileName, trainNode, ref TrainDirectory, ref ConsistReversed); } else { throw new InvalidDataException("No train node specified for scripted train"); } if (Train is ScriptedTrain) { if (Data.Count < 2) { Interface.AddMessage(MessageType.Error, false, $"There must be at least two points to go through in {FileName}"); return; } if (!(Data.First() is TravelStopData) || !(Data.Last() is TravelStopData)) { Interface.AddMessage(MessageType.Error, false, $"The first and the last point to go through must be the \"Stop\" node in {FileName}"); return; } } if (string.IsNullOrEmpty(TrainDirectory)) { Interface.AddMessage(MessageType.Error, false, $"No train has been specified in {FileName}"); return; } /* * First check for a train.ai file- Functionally identical, but allows for differently configured AI * trains not to show up as drivable */ string TrainData = Path.CombineFile(TrainDirectory, "train.ai"); if (!File.Exists(TrainData)) { // Check for the standard drivable train.dat TrainData = Path.CombineFile(TrainDirectory, "train.dat"); } string ExteriorFile = Path.CombineFile(TrainDirectory, "extensions.cfg"); if (!File.Exists(TrainData) || !File.Exists(ExteriorFile)) { Interface.AddMessage(MessageType.Error, true, $"The supplied train folder in TrackFollowingObject {FileName} did not contain a complete set of data."); return; } AbstractTrain currentTrain = Train; for (int i = 0; i < Program.CurrentHost.Plugins.Length; i++) { if (Program.CurrentHost.Plugins[i].Train != null && Program.CurrentHost.Plugins[i].Train.CanLoadTrain(TrainData)) { Program.CurrentHost.Plugins[i].Train.LoadTrain(Encoding.UTF8, TrainDirectory, ref currentTrain, ref Interface.CurrentControls); } } if (!Train.Cars.Any()) { Interface.AddMessage(MessageType.Error, false, $"Failed to load the specified train in {FileName}"); return; } if (ConsistReversed) { Train.Reverse(); } if (Train is ScriptedTrain st) { Train.AI = new TrackFollowingObjectAI(st, Data.ToArray()); foreach (var Car in Train.Cars) { Car.FrontAxle.Follower.TrackIndex = Data[0].RailIndex; Car.RearAxle.Follower.TrackIndex = Data[0].RailIndex; Car.FrontBogie.FrontAxle.Follower.TrackIndex = Data[0].RailIndex; Car.FrontBogie.RearAxle.Follower.TrackIndex = Data[0].RailIndex; Car.RearBogie.FrontAxle.Follower.TrackIndex = Data[0].RailIndex; Car.RearBogie.RearAxle.Follower.TrackIndex = Data[0].RailIndex; Train.PlaceCars(Data[0].Position); } } else { Train.AI = new Game.SimpleHumanDriverAI(Train, Interface.CurrentOptions.PrecedingTrainSpeedLimit); Train.Specs.DoorOpenMode = DoorMode.Manual; Train.Specs.DoorCloseMode = DoorMode.Manual; } } /// <summary> /// Function to parse TFO definition /// </summary> /// <param name="FileName">The filename of the containing XML file</param> /// <param name="SectionElement">The XElement to parse</param> /// <param name="Train">The track following object to parse this node into</param> private static void ParseDefinitionNode(string FileName, XElement SectionElement, ScriptedTrain Train) { string Section = SectionElement.Name.LocalName; foreach (XElement KeyNode in SectionElement.Elements()) { string Key = KeyNode.Name.LocalName; string Value = KeyNode.Value; int LineNumber = ((IXmlLineInfo)KeyNode).LineNumber; switch (Key.ToLowerInvariant()) { case "appearancetime": if (Value.Any() && !Interface.TryParseTime(Value, out Train.AppearanceTime)) { Interface.AddMessage(MessageType.Error, false, $"Value is invalid in {Key} in {Section} at line {LineNumber.ToString(culture)} in {FileName}"); } break; case "appearancestartposition": if (Value.Any() && !NumberFormats.TryParseDoubleVb6(Value, out Train.AppearanceStartPosition)) { Interface.AddMessage(MessageType.Error, false, $"Value is invalid in {Key} in {Section} at line {LineNumber.ToString(culture)} in {FileName}"); } break; case "appearanceendposition": if (Value.Any() && !NumberFormats.TryParseDoubleVb6(Value, out Train.AppearanceEndPosition)) { Interface.AddMessage(MessageType.Error, false, $"Value is invalid in {Key} in {Section} at line {LineNumber.ToString(culture)} in {FileName}"); } break; case "leavetime": if (Value.Any() && !Interface.TryParseTime(Value, out Train.LeaveTime)) { Interface.AddMessage(MessageType.Error, false, $"Value is invalid in {Key} in {Section} at line {LineNumber.ToString(culture)} in {FileName}"); } break; default: Interface.AddMessage(MessageType.Warning, false, $"Unsupported key {Key} encountered in {Section} at line {LineNumber.ToString(culture)} in {FileName}"); break; } } } /// <summary> /// Function to parse train definition /// </summary> /// <param name="ObjectPath">Absolute path to the object folder of route data</param> /// <param name="FileName">The filename of the containing XML file</param> /// <param name="SectionElement">The XElement to parse</param> /// <param name="TrainDirectory">Absolute path to the train directory</param> /// <param name="ConsistReversed">Whether to reverse the train composition.</param> private static void ParseTrainNode(string ObjectPath, string FileName, XElement SectionElement, ref string TrainDirectory, ref bool ConsistReversed) { string Section = SectionElement.Name.LocalName; foreach (XElement KeyNode in SectionElement.Elements()) { string Key = KeyNode.Name.LocalName; string Value = KeyNode.Value; int LineNumber = ((IXmlLineInfo)KeyNode).LineNumber; switch (Key.ToLowerInvariant()) { case "directory": { string TmpPath = Path.CombineDirectory(Path.GetDirectoryName(FileName), Value); if (!Directory.Exists(TmpPath)) { TmpPath = Path.CombineFile(Program.FileSystem.InitialTrainFolder, Value); } if (!Directory.Exists(TmpPath)) { TmpPath = Path.CombineFile(Program.FileSystem.TrainInstallationDirectory, Value); } if (!Directory.Exists(TmpPath)) { TmpPath = Path.CombineFile(ObjectPath, Value); } if (!Directory.Exists(TmpPath)) { Interface.AddMessage(MessageType.Error, false, $"Directory was not found in {Key} in {Section} at line {LineNumber.ToString(culture)} in {FileName}"); } else { TrainDirectory = TmpPath; } } break; case "reversed": if (Value.Any()) { switch (Value.ToLowerInvariant()) { case "true": ConsistReversed = true; break; case "false": ConsistReversed = false; break; default: { if (!NumberFormats.TryParseIntVb6(Value, out int n)) { Interface.AddMessage(MessageType.Error, false, $"Value is invalid in {Key} in {Section} at line {LineNumber.ToString(culture)} in {FileName}"); } else { ConsistReversed = Convert.ToBoolean(n); } } break; } } break; default: Interface.AddMessage(MessageType.Warning, false, $"Unsupported key {Key} encountered in {Section} at line {LineNumber.ToString(culture)} in {FileName}"); break; } } } /// <summary>Parses a train travel data node</summary> /// <param name="FileName">The filename of the containing XML file</param> /// <param name="SectionElement">The XElement to parse</param> /// <param name="Data">The list of travel data to add this to</param> private static void ParseTravelDataNodes(string FileName, XElement SectionElement, ICollection<TravelData> Data) { string Section = SectionElement.Name.LocalName; foreach (XElement KeyNode in SectionElement.Elements()) { string Key = KeyNode.Name.LocalName; int LineNumber = ((IXmlLineInfo)KeyNode).LineNumber; switch (Key.ToLowerInvariant()) { case "stop": Data.Add(ParseTravelStopNode(FileName, KeyNode)); break; case "point": Data.Add(ParseTravelPointNode(FileName, KeyNode)); break; default: Interface.AddMessage(MessageType.Warning, false, $"Unsupported key {Key} encountered in {Section} at line {LineNumber.ToString(culture)} in {FileName}"); break; } } } /// <summary> /// Function to parse the contents of TravelData class /// </summary> /// <param name="FileName">The filename of the containing XML file</param> /// <param name="SectionElement">The XElement to parse</param> /// <param name="Data">Travel data to which the parse results apply</param> private static void ParseTravelDataNode(string FileName, XElement SectionElement, TravelData Data) { string Section = SectionElement.Name.LocalName; double Decelerate = 0.0; double Accelerate = 0.0; double TargetSpeed = 0.0; bool targetSpeedSet = false; foreach (XElement KeyNode in SectionElement.Elements()) { string Key = KeyNode.Name.LocalName; string Value = KeyNode.Value; int LineNumber = ((IXmlLineInfo)KeyNode).LineNumber; switch (Key.ToLowerInvariant()) { case "decelerate": if (Value.Any() && !NumberFormats.TryParseDoubleVb6(Value, out Decelerate) || Decelerate < 0.0) { Interface.AddMessage(MessageType.Error, false, $"Value is expected to be a non-negative floating-point number in {Key} in {Section} at line {LineNumber.ToString(culture)} in {FileName}"); } break; case "position": case "stopposition": if (Value.Any() && !NumberFormats.TryParseDoubleVb6(Value, out Data.Position)) { Interface.AddMessage(MessageType.Error, false, $"Value is invalid in {Key} in {Section} at line {LineNumber.ToString(culture)} in {FileName}"); } break; case "accelerate": if (Value.Any() && !NumberFormats.TryParseDoubleVb6(Value, out Accelerate) || Accelerate < 0.0) { Interface.AddMessage(MessageType.Error, false, $"Value is expected to be a non-negative floating-point number in {Key} in {Section} at line {LineNumber.ToString(culture)} in {FileName}"); } break; case "targetspeed": if (Value.Any() && !NumberFormats.TryParseDoubleVb6(Value, out TargetSpeed) || TargetSpeed < 0.0) { Interface.AddMessage(MessageType.Error, false, $"Value is expected to be a non-negative floating-point number in {Key} in {Section} at line {LineNumber.ToString(culture)} in {FileName}"); } targetSpeedSet = true; break; case "rail": if (Value.Any() && !NumberFormats.TryParseIntVb6(Value, out Data.RailIndex) || Data.RailIndex < 0) { Interface.AddMessage(MessageType.Error, false, $"Value is expected to be a non-negative integer number in {Key} in {Section} at line {LineNumber.ToString(culture)} in {FileName}"); Data.RailIndex = 0; } if (!Program.CurrentRoute.Tracks.ContainsKey(Data.RailIndex) || Program.CurrentRoute.Tracks[Data.RailIndex].Elements.Length == 0) { Interface.AddMessage(MessageType.Error, false, $"RailIndex is invalid in {Key} in {Section} at line {LineNumber.ToString(culture)} in {FileName}"); Data.RailIndex = 0; } break; } } if (!targetSpeedSet) { Interface.AddMessage(MessageType.Warning, false, $"A TargetSpeed was not set in {Section}. This may cause unexpected results."); } Data.Decelerate = -Decelerate / 3.6; Data.Accelerate = Accelerate / 3.6; Data.TargetSpeed = TargetSpeed / 3.6; } /// <summary> /// Function to parse the contents of TravelStopData class /// </summary> /// <param name="FileName">The filename of the containing XML file</param> /// <param name="SectionElement">The XElement to parse</param> /// <returns>An instance of the new TravelStopData class with the parse result applied</returns> private static TravelStopData ParseTravelStopNode(string FileName, XElement SectionElement) { string Section = SectionElement.Name.LocalName; TravelStopData Data = new TravelStopData(); ParseTravelDataNode(FileName, SectionElement, Data); foreach (XElement KeyNode in SectionElement.Elements()) { string Key = KeyNode.Name.LocalName; string Value = KeyNode.Value; int LineNumber = ((IXmlLineInfo)KeyNode).LineNumber; switch (Key.ToLowerInvariant()) { case "stoptime": if (Value.Any() && !Interface.TryParseTime(Value, out Data.StopTime)) { Interface.AddMessage(MessageType.Error, false, $"Value is invalid in {Key} in {Section} at line {LineNumber.ToString(culture)} in {FileName}"); } break; case "doors": { int Door = 0; bool DoorBoth = false; switch (Value.ToLowerInvariant()) { case "l": case "left": Door = -1; break; case "r": case "right": Door = 1; break; case "n": case "none": case "neither": Door = 0; break; case "b": case "both": DoorBoth = true; break; default: if (Value.Any() && !NumberFormats.TryParseIntVb6(Value, out Door)) { Interface.AddMessage(MessageType.Error, false, $"Value is invalid in {Key} in {Section} at line {LineNumber.ToString(culture)} in {FileName}"); } break; } Data.OpenLeftDoors = Door < 0.0 | DoorBoth; Data.OpenRightDoors = Door > 0.0 | DoorBoth; } break; case "direction": { int d = 0; switch (Value.ToLowerInvariant()) { case "f": d = 1; break; case "r": d = -1; break; default: if (Value.Any() && (!NumberFormats.TryParseIntVb6(Value, out d) || !Enum.IsDefined(typeof(TravelDirection), d))) { Interface.AddMessage(MessageType.Error, false, $"Value is invalid in {Key} in {Section} at line {LineNumber.ToString(culture)} in {FileName}"); d = 1; } break; } Data.Direction = (TravelDirection)d; } break; case "decelerate": case "position": case "stopposition": case "accelerate": case "targetspeed": case "rail": // Already parsed break; default: Interface.AddMessage(MessageType.Warning, false, $"Unsupported key {Key} encountered in {Section} at line {LineNumber.ToString(culture)} in {FileName}"); break; } } return Data; } /// <summary> /// Function to parse the contents of TravelPointData class /// </summary> /// <param name="FileName">The filename of the containing XML file</param> /// <param name="SectionElement">The XElement to parse</param> /// <returns>An instance of the new TravelPointData class with the parse result applied</returns> private static TravelPointData ParseTravelPointNode(string FileName, XElement SectionElement) { string Section = SectionElement.Name.LocalName; TravelPointData Data = new TravelPointData(); ParseTravelDataNode(FileName, SectionElement, Data); double PassingSpeed = 0.0; foreach (XElement KeyNode in SectionElement.Elements()) { string Key = KeyNode.Name.LocalName; string Value = KeyNode.Value; int LineNumber = ((IXmlLineInfo)KeyNode).LineNumber; switch (Key.ToLowerInvariant()) { case "passingspeed": if (Value.Any() && !NumberFormats.TryParseDoubleVb6(Value, out PassingSpeed) || PassingSpeed < 0.0) { Interface.AddMessage(MessageType.Error, false, $"Value is expected to be a non-negative floating-point number in {Key} in {Section} at line {LineNumber.ToString(culture)} in {FileName}"); } break; case "decelerate": case "position": case "stopposition": case "accelerate": case "targetspeed": case "rail": // Already parsed break; default: Interface.AddMessage(MessageType.Warning, false, $"Unsupported key {Key} encountered in {Section} at line {LineNumber.ToString(culture)} in {FileName}"); break; } } Data.PassingSpeed = PassingSpeed / 3.6; return Data; } } }
411
0.934481
1
0.934481
game-dev
MEDIA
0.292443
game-dev
0.945265
1
0.945265
mattmatterson111/IS12-Warfare-Two
6,456
code/modules/surgery/surgery.dm
/* SURGERY STEPS */ /datum/surgery_step var/priority = 0 //steps with higher priority would be attempted first // type path referencing tools that can be used for this step, and how well are they suited for it var/list/allowed_tools = null // type paths referencing races that this step applies to. var/list/allowed_species = null var/list/disallowed_species = null // duration of the step var/min_duration = 0 var/max_duration = 0 // evil infection stuff that will make everyone hate me var/can_infect = 0 //How much blood this step can get on surgeon. 1 - hands, 2 - full body. var/blood_level = 0 var/shock_level = 0 //what shock level will this step put patient on var/delicate = 0 //if this step NEEDS stable optable or can be done on any valid surface with no penalty //returns how well tool is suited for this step /datum/surgery_step/proc/tool_quality(obj/item/tool) for (var/T in allowed_tools) if (istype(tool,T)) return allowed_tools[T] return 0 // Checks if this step applies to the user mob at all /datum/surgery_step/proc/is_valid_target(mob/living/carbon/human/target) if(!hasorgans(target)) return 0 if(allowed_species) for(var/species in allowed_species) if(target.species.get_bodytype(target) == species) return 1 if(disallowed_species) for(var/species in disallowed_species) if(target.species.get_bodytype(target) == species) return 0 return 1 // checks whether this step can be applied with the given user and target /datum/surgery_step/proc/can_use(mob/living/user, mob/living/carbon/human/target, target_zone, obj/item/tool) return 0 // does stuff to begin the step, usually just printing messages. Moved germs transfering and bloodying here too /datum/surgery_step/proc/begin_step(mob/living/user, mob/living/carbon/human/target, target_zone, obj/item/tool) var/obj/item/organ/external/affected = target.get_organ(target_zone) if (can_infect && affected) spread_germs_to_organ(affected, user) if (ishuman(user) && prob(60)) var/mob/living/carbon/human/H = user if (blood_level) H.bloody_hands(target,0) if (blood_level > 1) H.bloody_body(target,0) if(shock_level) target.shock_stage = max(target.shock_stage, shock_level) return // does stuff to end the step, which is normally print a message + do whatever this step changes /datum/surgery_step/proc/end_step(mob/living/user, mob/living/carbon/human/target, target_zone, obj/item/tool) return // stuff that happens when the step fails /datum/surgery_step/proc/fail_step(mob/living/user, mob/living/carbon/human/target, target_zone, obj/item/tool) return null /datum/surgery_step/proc/success_chance(mob/living/user, mob/living/carbon/human/target, obj/item/tool) . = tool_quality(tool) if(user == target) . -= 10 if(ishuman(user)) var/mob/living/carbon/human/H = user . -= round(H.shock_stage * 0.5) if(H.eye_blurry) . -= 20 if(H.eye_blind) . -= 60 if(delicate) if(user.slurring) . -= 10 if(!target.lying) . -= 30 var/turf/T = get_turf(target) if(locate(/obj/machinery/optable, T)) . -= 0 else if(locate(/obj/structure/bed, T)) . -= 5 else if(locate(/obj/structure/table, T)) . -= 10 else if(locate(/obj/effect/rune/, T)) . -= 10 . = max(., 0) /proc/spread_germs_to_organ(var/obj/item/organ/external/E, var/mob/living/carbon/human/user) if(!istype(user) || !istype(E)) return var/germ_level = user.germ_level if(user.gloves) germ_level = user.gloves.germ_level E.germ_level = max(germ_level,E.germ_level) //as funny as scrubbing microbes out with clean gloves is - no. /obj/item/proc/do_surgery(mob/living/carbon/M, mob/living/carbon/human/user, fuckup_prob) if(!istype(M)) return 0 if (user.a_intent == I_HURT) //check for Hippocratic Oath return 0 var/zone = user.zone_sel.selecting if(zone in M.op_stage.in_progress) //Can't operate on someone repeatedly. to_chat(user, "<span class='warning'>You can't operate on this area while surgery is already in progress.</span>") return 1 for(var/datum/surgery_step/S in surgery_steps) //check if tool is right or close enough and if this step is possible if(S.tool_quality(src)) var/step_is_valid = S.can_use(user, M, zone, src) if(step_is_valid && S.is_valid_target(M)) if(step_is_valid == SURGERY_FAILURE) // This is a failure that already has a message for failing. return 1 M.op_stage.in_progress += zone S.begin_step(user, M, zone, src) //start on it //We had proper tools! (or RNG smiled.) and user did not move or change hands. if(prob(S.success_chance(user, M, src)) && do_mob(user, M, rand(S.min_duration, S.max_duration))) if(user.statscheck(user.STAT_LEVEL(int), user.SKILL_LEVEL(surgery), "6d6", 20) >= SUCCESS) S.end_step(user, M, zone, src) //finish successfully else visible_message("<span class='warning'>[user] messes up the surgery step. They must try again.</span>") S.fail_step(user, M, zone, src) // INTERWAR EDIT : BRING BACK SURGERY FAILSTEPS user.my_skills[SKILL(surgery)].give_xp(10, user)//If they fail it then give them some XP for trying. else if ((src in user.contents) && user.Adjacent(M)) //or visible_message("<span class='warning'>[user] messes up the surgery step. They must try again.</span>") S.fail_step(user, M, zone, src) //malpractice~ user.my_skills[SKILL(surgery)].give_xp(10, user)//If they fail it then give them some XP for trying. else // This failing silently was a pain. to_chat(user, "<span class='warning'>You must remain close to your patient to conduct surgery.</span>") if (M) M.op_stage.in_progress -= zone // Clear the in-progress flag. if (ishuman(M)) var/mob/living/carbon/human/H = M H.update_surgery() return 1 //don't want to do weapony things after surgery return 0 /proc/sort_surgeries() var/gap = surgery_steps.len var/swapped = 1 while (gap > 1 || swapped) swapped = 0 if(gap > 1) gap = round(gap / 1.247330950103979) if(gap < 1) gap = 1 for(var/i = 1; gap + i <= surgery_steps.len; i++) var/datum/surgery_step/l = surgery_steps[i] //Fucking hate var/datum/surgery_step/r = surgery_steps[gap+i] //how lists work here if(l.priority < r.priority) surgery_steps.Swap(i, gap + i) swapped = 1 /datum/surgery_status/ var/eyes = 0 var/face = 0 var/head_reattach = 0 var/current_organ = "organ" var/list/in_progress = list()
411
0.82873
1
0.82873
game-dev
MEDIA
0.280983
game-dev
0.866405
1
0.866405
GodotECS/godex
5,560
thirdparty/bullet/BulletSoftBody/btDeformableMousePickingForce.h
/* Written by Xuchen Han <xuchenhan2015@u.northwestern.edu> Bullet Continuous Collision Detection and Physics Library Copyright (c) 2019 Google Inc. http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_MOUSE_PICKING_FORCE_H #define BT_MOUSE_PICKING_FORCE_H #include "btDeformableLagrangianForce.h" class btDeformableMousePickingForce : public btDeformableLagrangianForce { // If true, the damping force will be in the direction of the spring // If false, the damping force will be in the direction of the velocity btScalar m_elasticStiffness, m_dampingStiffness; const btSoftBody::Face& m_face; btVector3 m_mouse_pos; btScalar m_maxForce; public: typedef btAlignedObjectArray<btVector3> TVStack; btDeformableMousePickingForce(btScalar k, btScalar d, const btSoftBody::Face& face, const btVector3& mouse_pos, btScalar maxForce = 0.3) : m_elasticStiffness(k), m_dampingStiffness(d), m_face(face), m_mouse_pos(mouse_pos), m_maxForce(maxForce) { } virtual void addScaledForces(btScalar scale, TVStack& force) { addScaledDampingForce(scale, force); addScaledElasticForce(scale, force); } virtual void addScaledExplicitForce(btScalar scale, TVStack& force) { addScaledElasticForce(scale, force); } virtual void addScaledDampingForce(btScalar scale, TVStack& force) { for (int i = 0; i < 3; ++i) { btVector3 v_diff = m_face.m_n[i]->m_v; btVector3 scaled_force = scale * m_dampingStiffness * v_diff; if ((m_face.m_n[i]->m_x - m_mouse_pos).norm() > SIMD_EPSILON) { btVector3 dir = (m_face.m_n[i]->m_x - m_mouse_pos).normalized(); scaled_force = scale * m_dampingStiffness * v_diff.dot(dir) * dir; } force[m_face.m_n[i]->index] -= scaled_force; } } virtual void addScaledElasticForce(btScalar scale, TVStack& force) { btScalar scaled_stiffness = scale * m_elasticStiffness; for (int i = 0; i < 3; ++i) { btVector3 dir = (m_face.m_n[i]->m_q - m_mouse_pos); btVector3 scaled_force = scaled_stiffness * dir; if (scaled_force.safeNorm() > m_maxForce) { scaled_force.safeNormalize(); scaled_force *= m_maxForce; } force[m_face.m_n[i]->index] -= scaled_force; } } virtual void addScaledDampingForceDifferential(btScalar scale, const TVStack& dv, TVStack& df) { btScalar scaled_k_damp = m_dampingStiffness * scale; for (int i = 0; i < 3; ++i) { btVector3 local_scaled_df = scaled_k_damp * dv[m_face.m_n[i]->index]; if ((m_face.m_n[i]->m_x - m_mouse_pos).norm() > SIMD_EPSILON) { btVector3 dir = (m_face.m_n[i]->m_x - m_mouse_pos).normalized(); local_scaled_df = scaled_k_damp * dv[m_face.m_n[i]->index].dot(dir) * dir; } df[m_face.m_n[i]->index] -= local_scaled_df; } } virtual void buildDampingForceDifferentialDiagonal(btScalar scale, TVStack& diagA) {} virtual double totalElasticEnergy(btScalar dt) { double energy = 0; for (int i = 0; i < 3; ++i) { btVector3 dir = (m_face.m_n[i]->m_q - m_mouse_pos); btVector3 scaled_force = m_elasticStiffness * dir; if (scaled_force.safeNorm() > m_maxForce) { scaled_force.safeNormalize(); scaled_force *= m_maxForce; } energy += 0.5 * scaled_force.dot(dir); } return energy; } virtual double totalDampingEnergy(btScalar dt) { double energy = 0; for (int i = 0; i < 3; ++i) { btVector3 v_diff = m_face.m_n[i]->m_v; btVector3 scaled_force = m_dampingStiffness * v_diff; if ((m_face.m_n[i]->m_x - m_mouse_pos).norm() > SIMD_EPSILON) { btVector3 dir = (m_face.m_n[i]->m_x - m_mouse_pos).normalized(); scaled_force = m_dampingStiffness * v_diff.dot(dir) * dir; } energy -= scaled_force.dot(m_face.m_n[i]->m_v) / dt; } return energy; } virtual void addScaledElasticForceDifferential(btScalar scale, const TVStack& dx, TVStack& df) { btScalar scaled_stiffness = scale * m_elasticStiffness; for (int i = 0; i < 3; ++i) { btVector3 dir = (m_face.m_n[i]->m_q - m_mouse_pos); btScalar dir_norm = dir.norm(); btVector3 dir_normalized = (dir_norm > SIMD_EPSILON) ? dir.normalized() : btVector3(0, 0, 0); int id = m_face.m_n[i]->index; btVector3 dx_diff = dx[id]; btScalar r = 0; // rest length is 0 for picking spring btVector3 scaled_df = btVector3(0, 0, 0); if (dir_norm > SIMD_EPSILON) { scaled_df -= scaled_stiffness * dir_normalized.dot(dx_diff) * dir_normalized; scaled_df += scaled_stiffness * dir_normalized.dot(dx_diff) * ((dir_norm - r) / dir_norm) * dir_normalized; scaled_df -= scaled_stiffness * ((dir_norm - r) / dir_norm) * dx_diff; } df[id] += scaled_df; } } void setMousePos(const btVector3& p) { m_mouse_pos = p; } virtual btDeformableLagrangianForceType getForceType() { return BT_MOUSE_PICKING_FORCE; } }; #endif /* btMassSpring_h */
411
0.925041
1
0.925041
game-dev
MEDIA
0.836636
game-dev
0.988817
1
0.988817
nature-of-code/Nature-of-Code-Website-Archive
1,398
book/processingjs/chapter02/_2_8_mutual_attraction/Mover.pde
class Mover { PVector location; PVector velocity; PVector acceleration; float mass; Mover(float m, float x, float y) { mass = m; location = new PVector(x, y); velocity = new PVector(0, 0); acceleration = new PVector(0, 0); } void applyForce(PVector force) { PVector f = PVector.div(force, mass); acceleration.add(f); } void update() { velocity.add(acceleration); location.add(velocity); acceleration.mult(0); } void display() { stroke(0); strokeWeight(2); fill(0, 100); ellipse(location.x, location.y, mass*24, mass*24); } PVector attract(Mover m) { PVector force = PVector.sub(location, m.location); // Calculate direction of force float distance = force.mag(); // Distance between objects distance = constrain(distance, 5.0, 25.0); // Limiting the distance to eliminate "extreme" results for very close or very far objects force.normalize(); // Normalize vector (distance doesn't matter here, we just want this vector for direction float strength = (g * mass * m.mass) / (distance * distance); // Calculate gravitional force magnitude force.mult(strength); // Get force vector --> magnitude * direction return force; } }
411
0.730582
1
0.730582
game-dev
MEDIA
0.428155
game-dev
0.889648
1
0.889648
lihas/WindowDetective
7,034
src/inspector/DynamicData.h
////////////////////////////////////////////////////////////////////////// // File: DynamicData.h // // Date: 2010-07-28 // // Desc: Classes for defining custom data structures. Raw data is // // stored in a block of memory, where each member can be accessed // // using a defined offset and size. The type is also defined along // // with a format (using printf notation). // ////////////////////////////////////////////////////////////////////////// /******************************************************************** Window Detective Copyright (C) 2010-2017 XTAL256 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ********************************************************************/ #ifndef DYNAMIC_DATA_H #define DYNAMIC_DATA_H #include <QtXml> #include "window_detective\include.h" #include "window_detective\Error.h" // Class declarations class DataType; class PrimitiveType; class FieldDefinition; class StructDefinition; class DynamicStruct; /*--------------------------------------------------------------------------+ | Abstract data type. | +--------------------------------------------------------------------------*/ class DataType { protected: String name; // Name of this type (e.g. "int", "HWND") String printFormat; // How the data will be printed (using printf-like notation) public: DataType() : name(), printFormat() {} String getName() const { return name; } String getPrintFormat() const { return printFormat; } void setPrintFormat(String str) { printFormat = str; } virtual ushort getSize() const = 0; virtual ushort getAlignment() const = 0; virtual bool isPrimitive() const { return false; } virtual bool isStruct() const { return false; } }; /*--------------------------------------------------------------------------+ | Primitive data type (e.g. int, float). | +--------------------------------------------------------------------------*/ class PrimitiveType : public DataType { private: ushort size; // Size of data (can be 1, 2, 4 or 8 bytes) public: PrimitiveType(QDomElement& node); ushort getSize() const { return size; } ushort getAlignment() const { return size; } bool isPrimitive() const { return true; } }; /*--------------------------------------------------------------------------+ | Field (variable) for a struct. Can contain any data type. | +--------------------------------------------------------------------------*/ class FieldDefinition { protected: enum FieldFormatType { FormatNormal, FormatEnum, FormatFlags }; String name; // Name of this field (i.e. the variable's name) DataType* dataType; // The type of data this field holds ushort offset; // The byte offset of this field in it's struct FieldFormatType formatType; // When Enum or Flags, printFormat will contain the enum or flag name String printFormat; // Use data type's format if this is empty public: FieldDefinition(QDomElement& node, ushort offset); FieldDefinition(String name, String typeName); FieldDefinition(StructDefinition* structDefn); String getName() const { return name; } DataType* getType() const { return dataType; } ushort getOffset() const { return offset; } String getPrintFormat() const { return printFormat; } void setPrintFormat(String str) { printFormat = str; } String toString(byte* data) const; }; /*--------------------------------------------------------------------------+ | Structure type. | +--------------------------------------------------------------------------*/ class StructDefinition : public DataType { private: QList<FieldDefinition> fields; // List of fields (members variables) ushort size; // The combined size of the data types public: StructDefinition(QDomElement& node); const FieldDefinition& getField(String name) const; const FieldDefinition& getField(int i) const { return fields[i]; } int numFields() const { return fields.size(); } ushort getSize() const { return size; } ushort getAlignment() const; bool isStruct() const { return true; } }; /*--------------------------------------------------------------------------+ | Structure instance. | +--------------------------------------------------------------------------*/ class DynamicStruct { private: StructDefinition* definition; // The type of struct (i.e. the 'class' of this 'instance') byte* data; // The raw data ushort size; // Total size of the data (may not be the same as the definiton) public: DynamicStruct() : definition(NULL), data(NULL), size(0) {} // Default constructor - NULL data DynamicStruct(StructDefinition* defn, void* data, ushort size); ~DynamicStruct(); void init(StructDefinition* defn, void* data, ushort size); StructDefinition* getDefinition() const { return definition; } byte* getData() const { return data; } ushort getSize() const { return size; } bool isNull() const { return data == NULL; } template <typename T> T get(String fieldName) const; String fieldToString(int fieldIndex) const; void toXmlStream(QXmlStreamWriter& stream) const; }; /*--------------------------------------------------------------------------+ | Template definition (must be in header). | | Returns the data at the given field, converted to the given type. | +--------------------------------------------------------------------------*/ template <typename T> T DynamicStruct::get(String fieldName) const { // TODO // check sizeof(T) // return static_cast<T>(offset(fieldName)); return T(); } /*********************/ /*** Error classes ***/ /*********************/ class DynamicStructError : public Error { public: DynamicStructError() : Error() {} DynamicStructError(String msg) : Error("DynamicStructError", msg) {} }; #endif // DYNAMIC_DATA_H
411
0.927759
1
0.927759
game-dev
MEDIA
0.712729
game-dev
0.879925
1
0.879925
TeamHypersomnia/Hypersomnia
1,031
src/augs/math/simple_physics.h
#pragma once #include "augs/math/physics_structs.h" struct simple_rot_vel { // GEN INTROSPECTOR struct simple_rot_vel real32 rotation = 0.f; real32 angular_velocity = 0.f; // END GEN INTROSPECTOR void apply(const real32 in) { angular_velocity += in; } void integrate(const real32 dt) { rotation += angular_velocity * dt; } void damp(const real32 dt, const real32 angular) { angular_velocity = augs::damp(angular_velocity, dt, angular); } }; struct simple_body { // GEN INTROSPECTOR struct simple_body vec2 position; real32 rotation = 0.f; vec2 linear_velocity; real32 angular_velocity = 0.f; // END GEN INTROSPECTOR void apply(const impulse_input in) { linear_velocity += in.linear; angular_velocity += in.angular; } void integrate(const real32 dt) { position += linear_velocity * dt; rotation += angular_velocity * dt; } void damp(const real32 dt, const damping_input in) { linear_velocity.damp(dt, in.linear); angular_velocity = augs::damp(angular_velocity, dt, in.angular); } };
411
0.573019
1
0.573019
game-dev
MEDIA
0.405072
game-dev
0.789363
1
0.789363
GregHib/void
1,574
engine/src/main/kotlin/world/gregs/voidps/engine/inv/ItemAdded.kt
package world.gregs.voidps.engine.inv import world.gregs.voidps.engine.entity.character.player.Player import world.gregs.voidps.engine.entity.item.Item import world.gregs.voidps.engine.event.Event import world.gregs.voidps.engine.event.EventDispatcher import world.gregs.voidps.engine.event.Events import world.gregs.voidps.network.login.protocol.visual.update.player.EquipSlot /** * An item slot updated to an item in an inventory. * @param inventory The transaction inventory * @param index the index of the item in the target inventory * @param item the new state of the item */ data class ItemAdded( val inventory: String, val index: Int, val item: Item, ) : Event { override val notification = true override val size = 4 override fun parameter(dispatcher: EventDispatcher, index: Int) = when (index) { 0 -> "item_added" 1 -> item.id 2 -> this.index 3 -> inventory else -> null } } fun itemAdded(item: String = "*", slot: EquipSlot, inventory: String = "*", handler: suspend ItemAdded.(Player) -> Unit) { itemAdded(item, slot.index, inventory, handler) } fun itemAdded(item: String = "*", indices: Collection<Int>, inventory: String = "*", handler: suspend ItemAdded.(Player) -> Unit) { for (index in indices) { itemAdded(item, index, inventory, handler) } } fun itemAdded(item: String = "*", index: Int? = null, inventory: String = "*", handler: suspend ItemAdded.(Player) -> Unit) { Events.handle("item_added", item, index ?: "*", inventory, handler = handler) }
411
0.868707
1
0.868707
game-dev
MEDIA
0.965065
game-dev
0.899397
1
0.899397
Goob-Station/Goob-Station-MRP
6,393
Content.Client/Decals/DecalSystem.cs
using Content.Client.Decals.Overlays; using Content.Shared.Decals; using Robust.Client.GameObjects; using Robust.Client.Graphics; using Robust.Shared.GameStates; using Robust.Shared.Utility; using static Content.Shared.Decals.DecalGridComponent; namespace Content.Client.Decals { public sealed class DecalSystem : SharedDecalSystem { [Dependency] private readonly IOverlayManager _overlayManager = default!; [Dependency] private readonly SpriteSystem _sprites = default!; private DecalOverlay _overlay = default!; private HashSet<uint> _removedUids = new(); private readonly List<Vector2i> _removedChunks = new(); public override void Initialize() { base.Initialize(); _overlay = new DecalOverlay(_sprites, EntityManager, PrototypeManager); _overlayManager.AddOverlay(_overlay); SubscribeLocalEvent<DecalGridComponent, ComponentHandleState>(OnHandleState); SubscribeNetworkEvent<DecalChunkUpdateEvent>(OnChunkUpdate); } public void ToggleOverlay() { if (_overlayManager.HasOverlay<DecalOverlay>()) { _overlayManager.RemoveOverlay(_overlay); } else { _overlayManager.AddOverlay(_overlay); } } public override void Shutdown() { base.Shutdown(); _overlayManager.RemoveOverlay(_overlay); } protected override void OnDecalRemoved(EntityUid gridId, uint decalId, DecalGridComponent component, Vector2i indices, DecalChunk chunk) { base.OnDecalRemoved(gridId, decalId, component, indices, chunk); DebugTools.Assert(chunk.Decals.ContainsKey(decalId)); chunk.Decals.Remove(decalId); } private void OnHandleState(EntityUid gridUid, DecalGridComponent gridComp, ref ComponentHandleState args) { // is this a delta or full state? _removedChunks.Clear(); Dictionary<Vector2i, DecalChunk> modifiedChunks; switch (args.Current) { case DecalGridDeltaState delta: { modifiedChunks = delta.ModifiedChunks; foreach (var key in gridComp.ChunkCollection.ChunkCollection.Keys) { if (!delta.AllChunks.Contains(key)) _removedChunks.Add(key); } break; } case DecalGridState state: { modifiedChunks = state.Chunks; foreach (var key in gridComp.ChunkCollection.ChunkCollection.Keys) { if (!state.Chunks.ContainsKey(key)) _removedChunks.Add(key); } break; } default: return; } if (_removedChunks.Count > 0) RemoveChunks(gridUid, gridComp, _removedChunks); if (modifiedChunks.Count > 0) UpdateChunks(gridUid, gridComp, modifiedChunks); } private void OnChunkUpdate(DecalChunkUpdateEvent ev) { foreach (var (netGrid, updatedGridChunks) in ev.Data) { if (updatedGridChunks.Count == 0) continue; var gridId = GetEntity(netGrid); if (!TryComp(gridId, out DecalGridComponent? gridComp)) { Log.Error($"Received decal information for an entity without a decal component: {ToPrettyString(gridId)}"); continue; } UpdateChunks(gridId, gridComp, updatedGridChunks); } // Now we'll cull old chunks out of range as the server will send them to us anyway. foreach (var (netGrid, chunks) in ev.RemovedChunks) { if (chunks.Count == 0) continue; var gridId = GetEntity(netGrid); if (!TryComp(gridId, out DecalGridComponent? gridComp)) { Log.Error($"Received decal information for an entity without a decal component: {ToPrettyString(gridId)}"); continue; } RemoveChunks(gridId, gridComp, chunks); } } private void UpdateChunks(EntityUid gridId, DecalGridComponent gridComp, Dictionary<Vector2i, DecalChunk> updatedGridChunks) { var chunkCollection = gridComp.ChunkCollection.ChunkCollection; // Update any existing data / remove decals we didn't receive data for. foreach (var (indices, newChunkData) in updatedGridChunks) { if (chunkCollection.TryGetValue(indices, out var chunk)) { _removedUids.Clear(); _removedUids.UnionWith(chunk.Decals.Keys); _removedUids.ExceptWith(newChunkData.Decals.Keys); foreach (var removedUid in _removedUids) { OnDecalRemoved(gridId, removedUid, gridComp, indices, chunk); gridComp.DecalIndex.Remove(removedUid); } } chunkCollection[indices] = newChunkData; foreach (var (uid, decal) in newChunkData.Decals) { gridComp.DecalIndex[uid] = indices; } } } private void RemoveChunks(EntityUid gridId, DecalGridComponent gridComp, IEnumerable<Vector2i> chunks) { var chunkCollection = gridComp.ChunkCollection.ChunkCollection; foreach (var index in chunks) { if (!chunkCollection.TryGetValue(index, out var chunk)) continue; foreach (var decalId in chunk.Decals.Keys) { OnDecalRemoved(gridId, decalId, gridComp, index, chunk); gridComp.DecalIndex.Remove(decalId); } chunkCollection.Remove(index); } } } }
411
0.952896
1
0.952896
game-dev
MEDIA
0.699519
game-dev
0.9137
1
0.9137
dht3218/esp32pico_watch
2,554
libraries/lvgl/src/core/lv_obj_class.h
/** * @file lv_obj_class.h * */ #ifndef LV_OBJ_CLASS_H #define LV_OBJ_CLASS_H #ifdef __cplusplus extern "C" { #endif /********************* * INCLUDES *********************/ #include <stdint.h> #include <stdbool.h> /********************* * DEFINES *********************/ /********************** * TYPEDEFS **********************/ struct _lv_obj_t; struct _lv_obj_class_t; struct _lv_event_t; typedef enum { LV_OBJ_CLASS_EDITABLE_INHERIT, /**< Check the base class. Must have 0 value to let zero initialized class inherit*/ LV_OBJ_CLASS_EDITABLE_TRUE, LV_OBJ_CLASS_EDITABLE_FALSE, } lv_obj_class_editable_t; typedef enum { LV_OBJ_CLASS_GROUP_DEF_INHERIT, /**< Check the base class. Must have 0 value to let zero initialized class inherit*/ LV_OBJ_CLASS_GROUP_DEF_TRUE, LV_OBJ_CLASS_GROUP_DEF_FALSE, } lv_obj_class_group_def_t; typedef void (*lv_obj_class_event_cb_t)(struct _lv_obj_class_t * class_p, struct _lv_event_t * e); /** * Describe the common methods of every object. * Similar to a C++ class. */ typedef struct _lv_obj_class_t { const struct _lv_obj_class_t * base_class; void (*constructor_cb)(const struct _lv_obj_class_t * class_p, struct _lv_obj_t * obj); void (*destructor_cb)(const struct _lv_obj_class_t * class_p, struct _lv_obj_t * obj); #if LV_USE_USER_DATA void * user_data; #endif void (*event_cb)(const struct _lv_obj_class_t * class_p, struct _lv_event_t * e); /**< Widget type specific event function*/ lv_coord_t width_def; lv_coord_t height_def; uint32_t editable : 2; /**< Value from ::lv_obj_class_editable_t*/ uint32_t group_def : 2; /**< Value from ::lv_obj_class_group_def_t*/ uint32_t instance_size : 16; } lv_obj_class_t; /********************** * GLOBAL PROTOTYPES **********************/ /** * Create an object form a class descriptor * @param class_p pointer to a class * @param parent pointer to an object where the new object should be created * @return pointer to the created object */ struct _lv_obj_t * lv_obj_class_create_obj(const struct _lv_obj_class_t * class_p, struct _lv_obj_t * parent); void lv_obj_class_init_obj(struct _lv_obj_t * obj); void _lv_obj_destruct(struct _lv_obj_t * obj); bool lv_obj_is_editable(struct _lv_obj_t * obj); bool lv_obj_is_group_def(struct _lv_obj_t * obj); /********************** * MACROS **********************/ #ifdef __cplusplus } /*extern "C"*/ #endif #endif /*LV_OBJ_CLASS_H*/
411
0.915295
1
0.915295
game-dev
MEDIA
0.471432
game-dev
0.553096
1
0.553096
valryon/flipon-tiny
9,702
Assets/scripts/Runtime/UI/Widgets/ObjectiveWidget.cs
// Tiny Flipon by Damien Mayance // This file is subject to the terms and conditions defined in // file 'LICENSE.md', which is part of this source code package. using System; using UnityEngine; using DG.Tweening; using TMPro; using UnityEngine.Serialization; using UnityEngine.UI; namespace Pon { public class ObjectiveWidget : MonoBehaviour { #pragma warning disable 0649 [Header("Bindings")] [SerializeField] private GameObject panelIcon; [SerializeField] private TextMeshProUGUI textIcon; [FormerlySerializedAs("icon")] [SerializeField] private Image objectiveIcon; [SerializeField] private Image tickIcon; [SerializeField] private GameObject panelNoIcon; [SerializeField] private TextMeshProUGUI textNoIcon; [SerializeField] private Image tickNoIcon; #pragma warning restore 0649 private TextMeshProUGUI text; private Image tick; private PlayerScript player; private Objective objective; private ObjectiveStats lastStats; private bool completed; private string nextValue; void Awake() { panelIcon.SetActive(false); panelNoIcon.SetActive(false); gameObject.SetActive(false); } private void Start() { player = GetComponentInParent<PlayerScript>(); } #region Objectives /// <summary> /// Display objective and progression /// </summary> public void SetObjective(Objective obj) { bool active = (obj != null); gameObject.SetActive(active); completed = false; objective = obj; if (active) { if (obj.IsMultiObjectives) { Log.Error("Widget cannot display a multiple objective... divide it first!"); return; } UpdateDisplay(objective.GetObjectiveType(), objective.stats, new ObjectiveStats(), objective.StartStats, true); } } public void UpdateObjective(PlayerScript player, ObjectiveStats current) { if (completed) return; if (objective == null) return; UpdateDisplay(objective.GetObjectiveType(), objective.stats, current, objective.StartStats, IsImmediateUpdate); if (objective.Succeed(player, current)) { CompleteObjective(true); } } public void CompleteObjective(bool success) { if (gameObject.activeInHierarchy) { completed = true; if (success) { var seq = DOTween.Sequence(); seq.AppendInterval(1f); seq.Append(text.DOFade(0f, 0.5f).SetEase(Ease.OutQuart)); seq.AppendCallback(() => { tick.gameObject.SetActive(true); tick.color = tick.color.SetAlpha(0f); tick.DOFade(1f, 0.5f).SetEase(Ease.OutQuart); }); } else { text.color = Color.red; var seq = DOTween.Sequence(); seq.AppendInterval(1f); seq.Append(text.DOFade(0f, 0.5f).SetEase(Ease.OutQuart)); seq.AppendInterval(2f); seq.AppendCallback(() => { panelNoIcon.SetActive(false); panelIcon.SetActive(false); }); } } } #endregion #region Display private void UpdateDisplay(ObjectiveStatType type, ObjectiveStats target, ObjectiveStats current, ObjectiveStats start, bool immediate) { gameObject.SetActive(true); // Build text string t = string.Empty; Sprite s = null; if (type == ObjectiveStatType.HighestMultiplier) { t = "x" + target.highestCombo; // Disable icon for now // t = (target.highestCombo - current.highestCombo).ToString(); // s = ObjectiveData.GetIcon("combo_best"); // if (current.highestCombo == 0 && lastStats.highestCombo > 0) // { // Reset(); // immediate = true; // // // Create a bunch of ejected stars // for (int i = 0; i < lastStats.highestCombo; i++) // { // var image = GameUIScript.CreateObjectiveIcon(player.grid, this, transform.position); // var p = transform.position + RandomEx.GetVector3(-4, 4f, 0f, 3f, 0, 0); // image.transform.DOMove(p, 0.35f) // .SetEase(Ease.OutCubic).OnComplete(() => // { // image.transform.DOScale(Vector3.zero, 0.15f) // .OnComplete(() => { Destroy(image.gameObject); }); // }); // } // } } if (type == ObjectiveStatType.Score) { t = "<b>" + Mathf.Max(0, target.score - (current.score - start.score)) + "</b> PTS"; s = ObjectiveData.GetIcon("score"); } if (type == ObjectiveStatType.TotalCombos) { t = Mathf.Max(0, target.totalCombos - (current.totalCombos - start.totalCombos)).ToString(); s = ObjectiveData.GetIcon("combo_total"); } if (type == ObjectiveStatType.Total4Combos) { t = Mathf.Max(0, target.total4Combos - (current.total4Combos - start.total4Combos)).ToString(); s = ObjectiveData.GetIcon("combo_4"); } if (type == ObjectiveStatType.Total5Combos) { t = Mathf.Max(0, target.total5Combos - (current.total5Combos - start.total5Combos)).ToString(); s = ObjectiveData.GetIcon("combo_5"); } if (type == ObjectiveStatType.TotalLCombos) { t = Mathf.Max(0, target.totalLCombos - (current.totalLCombos - start.totalLCombos)).ToString(); s = ObjectiveData.GetIcon("combo_L"); } if (type == ObjectiveStatType.Time) { t = target.timeReached + "'"; // s = ObjectiveData.GetIcon("time"); -> null } if (type == ObjectiveStatType.TimeLimit) { t = (int) target.timeMax + "'"; // s = ObjectiveData.GetIcon("time"); -> null } if (type == ObjectiveStatType.Level) { t = target.speedLevel.ToString(); s = ObjectiveData.GetIcon("level"); } if (type == ObjectiveStatType.TotalChains) { t = Mathf.Max(0, target.totalChains - (current.totalChains - start.totalChains)).ToString(); s = ObjectiveData.GetIcon("chain"); } if (type == ObjectiveStatType.HighestChain) { throw new NotImplementedException("Highest chains not used yet"); } if (type == ObjectiveStatType.Height) { s = ObjectiveData.GetIcon("height"); if (player == null) { player = FindObjectOfType<PlayerScript>(); } if (player != null) { int ch = player.grid.HighestY; int th = player.grid.targetHeight; t = (Mathf.Abs(th - ch) + 1).ToString(); } else { t = target.digHeight.ToString(); } } if (completed == false) { if (immediate) { if (s != null) { SetWithIcon(s, t); } else { SetWithoutIcon(t); } } else { nextValue = t; } } lastStats = current; } private void SetWithIcon(Sprite s, string t) { if (panelIcon.activeInHierarchy == false) { panelIcon.SetActive(true); panelNoIcon.SetActive(false); text = textIcon; text.color = text.color.SetAlpha(1f); tick = tickIcon; objectiveIcon.color = objectiveIcon.color.SetAlpha(1f); text.gameObject.SetActive(true); objectiveIcon.gameObject.SetActive(true); tick.gameObject.SetActive(false); } text.text = t; objectiveIcon.sprite = s; } private void SetWithoutIcon(string t) { if (panelNoIcon.activeInHierarchy == false) { panelIcon.SetActive(false); panelNoIcon.SetActive(true); text = textNoIcon; text.color = text.color.SetAlpha(1f); text.gameObject.SetActive(true); tick = tickNoIcon; tick.gameObject.SetActive(false); } text.text = t; objectiveIcon = null; } private Sequence sequence; public void Highlight() { if (sequence != null) sequence.Kill(); if (IsCompleted == false) { text.text = nextValue; text.color = Color.white; text.transform.DOKill(); text.transform.localScale = Vector3.one; text.transform.DOPunchScale(Vector3.one * 1.15f, 0.5f, 1); } } public void Reset() { if (sequence != null) sequence.Kill(); text.transform.DOKill(); text.transform.localScale = Vector3.one; sequence = DOTween.Sequence(); sequence.Append(text.DOColor(Color.red, 0.25f).SetEase(Ease.OutCubic)); sequence.Join(text.transform.DOPunchPosition(new Vector3(25, 0, 0), 0.5f, 25)); sequence.Append(text.DOColor(Color.white, 0.25f).SetEase(Ease.OutCubic)); } #endregion public Objective Objective => objective; public TextMeshProUGUI Text => text; public Image Icon => objectiveIcon; public bool IsCompleted => completed; private bool IsImmediateUpdate { get { var type = objective.GetObjectiveType(); switch (type) { case ObjectiveStatType.Score: case ObjectiveStatType.TotalCombos: case ObjectiveStatType.Total4Combos: case ObjectiveStatType.Total5Combos: case ObjectiveStatType.TotalLCombos: case ObjectiveStatType.HighestMultiplier: return false; } return true; } } } }
411
0.691199
1
0.691199
game-dev
MEDIA
0.8105
game-dev
0.95494
1
0.95494
ggnkua/Atari_ST_Sources
93,098
C/Christophe Fontanel/ReDMCSB_Release2/OBJECT/ENGINE/NOCP/DM12GE/CHAMPION.S
BSS SEG "bss" G407_s_Par:/* global */ .WORD #3328 G409_ai_Ch:/* global */ .WORD #8 G410_ai_Ch:/* global */ .WORD #8 CODE SEG "init!" MOVE #-1,G411_i_Lea(A4) BSS SEG "bss" G411_i_Lea:/* global */ .WORD #2 G412_puc_B:/* global */ .WORD #4 G413_i_Lea:/* global */ .WORD #2 G414_T_Lea:/* global */ .WORD #2 G415_B_Lea:/* global */ .WORD #2 G416_i_Use:/* global */ .WORD #2 CODE SEG "init!" LEA G417_apc_B(A4),A1 DATA SEG "s!" s!: DATA 4B 41 4D 50 46 45 52 00 CODE SEG "init!" LEA s!(A4),A0 MOVE.L A0,(A1)+ DATA SEG "s!" DATA 4E 49 4E 4A 41 00 CODE SEG "init!" LEA s!+8(A4),A0 MOVE.L A0,(A1)+ DATA SEG "s!" DATA 50 52 49 45 53 54 45 52 00 00 CODE SEG "init!" LEA s!+14(A4),A0 MOVE.L A0,(A1)+ DATA SEG "s!" DATA 4D 41 47 49 45 52 00 00 CODE SEG "init!" LEA s!+24(A4),A0 MOVE.L A0,(A1)+ BSS SEG "bss" G417_apc_B:/* global */ .WORD #16 CODE SEG "player" F278_apzz_:/* global */ LINK A6,L$0 MOVEM.L A3-A2/D7-D5,-(A7) MOVE G298_B_New(A4),D0 BNE L2(PC) MOVE G414_T_Lea(A4),D0 MOVE D0,D5 CMPI #-1,D0 BNE.S L3 MOVE #1,G415_B_Lea(A4) MOVE #-1,G413_i_Lea(A4) JSR F069_aaaL_(PC) BRA.S L4 L3: MOVE #1,-(A7) MOVE D5,-(A7) JSR F297_atzz_(PC) ADDQ.L #4,A7 L4: LEA G407_s_Par(A4),A0 MOVE.L A0,A3 CLR D7 BRA.S L5 L6: ANDI #127,48(A3) ORI #-27648,48(A3) L7: MOVE D7,D0 ADDQ #1,D7 MOVE.L A3,D0 ADDA #800,A3 L5: MOVE D7,D0 CMP G305_ui_Pa(A4),D0 BCS.S L6 L8: JSR F293_ahzz_(PC) MOVE G411_i_Lea(A4),D0 MOVE D0,D7 CMPI #-1,D0 BEQ.S L9 MOVE #-1,G411_i_Lea(A4) MOVE D7,-(A7) JSR F368_fzzz_(PC) ADDQ.L #2,A7 L9: MOVE G514_i_Mag(A4),D0 MOVE D0,D7 CMPI #-1,D0 BEQ.S L10 MOVE #-1,G514_i_Mag(A4) MOVE D7,-(A7) JSR F394_ozzz_(PC) ADDQ.L #2,A7 L10: BRA.S L11 L2: MOVE #-1,G414_T_Lea(A4) MOVE #-1,G413_i_Lea(A4) MOVE #1,G415_B_Lea(A4) L11: L1: MOVEM.L (A7)+,D5-D7/A2-A3 UNLK A6 RTS L$0: .EQU #-8 F279_xxxx_:/* global */ LINK A6,L$12 MOVEM.L A3/D7-D5,-(A7) MOVE.L 8(A6),A3 MOVE 12(A6),D7 CLR D5 CLR D6 BRA.S L14 L15: MOVE D5,D0 ASL #4,D0 MOVE.B (A3)+,D1 EXT D1 SUB #65,D1 ADD D1,D0 MOVE D0,D5 L16: ADDQ #1,D6 L14: MOVE D6,D0 CMP D7,D0 BCS.S L15 L17: MOVE D5,D0 L13: MOVEM.L (A7)+,D5-D7/A3 UNLK A6 RTS L$12: .EQU #0 F280_agzz_:/* global */ LINK A6,L$18 MOVEM.L A3-A2/D7-D4,-(A7) MOVE G415_B_Lea(A4),D0 BNE.S L20 BRA L19(PC) L20: CMPI #4,G305_ui_Pa(A4) BNE.S L21 BRA L19(PC) L21: MOVE G305_ui_Pa(A4),D0 MOVE D0,-2(A6) MULS #800,D0 LEA G407_s_Par(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,A3 MOVE #800,-(A7) MOVE.L A3,-(A7) JSR F008_aA19_(PC) ADDQ.L #6,A7 MOVE #1,D0 MOVE D0,G578_B_Use(A4) MOVE #-1,-(A7) MOVE #16,-(A7) MOVE #128,-(A7) MOVE 8(A6),D0 LSR #3,D0 MULU #29,D0 MOVE D0,-(A7) MOVE 8(A6),D0 AND #7,D0 ASL #5,D0 MOVE D0,-(A7) PEA G047_s_Gra(A4) LEA 336(A3),A0 MOVE.L A0,-(A7) MOVE #26,-(A7) JSR F489_ayzz_(PC) ADDQ.L #2,A7 MOVE.L D0,-(A7) JSR F132_xzzz_(PC) ADDA #22,A7 MOVE.B #1,30(A3) MOVE.B #2,31(A3) MOVE.B #-1,32(A3) MOVE #-1,44(A3) MOVE #-1,46(A3) MOVE G308_i_Par(A4),D0 MOVE.B D0,28(A3) CLR D6 BRA.S L22 L23: L24: ADDQ #1,D6 L22: MOVE D6,D0 ADD G308_i_Par(A4),D0 AND #3,D0 MOVE D0,-(A7) JSR F285_szzz_(PC) ADDQ.L #2,A7 CMPI #-1,D0 BNE.S L23 L25: MOVE D6,D0 ADD G308_i_Par(A4),D0 AND #3,D0 MOVE.B D0,29(A3) MOVE #1024,48(A3) MOVE G308_i_Par(A4),D0 MOVE.B D0,40(A3) JSR F027_AA59_(PC) MOVE.L D0,D1 AND #255,D1 MOVE #1500,D0 ADD D1,D0 MOVE D0,66(A3) JSR F027_AA59_(PC) MOVE.L D0,D1 AND #255,D1 MOVE #1500,D0 ADD D1,D0 MOVE D0,68(A3) CLR D6 BRA.S L26 L27: MOVE D6,D0 ASL.L #1,D0 LEA 212(A3),A0 ADDA D0,A0 MOVE #-1,(A0) L28: ADDQ #1,D6 L26: CMPI #30,D6 BCS.S L27 L29: MOVE G307_i_Par(A4),-(A7) MOVE G306_i_Par(A4),-(A7) JSR F161_szzz_(PC) ADDQ.L #4,A7 MOVE D0,D7 BRA.S L30 L31: L32: MOVE D7,-(A7) JSR F159_rzzz_(PC) ADDQ.L #2,A7 MOVE D0,D7 L30: MOVE D7,D0 AND #15360,D0 LSR #2,D0 LSR #8,D0 CMPI #2,D0 BNE.S L31 L33: MOVE #-32766,-(A7) MOVE D7,-(A7) LEA -96(A6),A0 MOVE.L A0,D0 MOVE.L D0,A2 MOVE.L D0,-(A7) JSR F168_ajzz_(PC) ADDQ.L #8,A7 CLR D6 BRA.S L34 L35: MOVE D4,D0 MOVE D6,D1 ADDQ #1,D6 LEA (A3),A0 ADDA D1,A0 MOVE.B D0,(A0) L34: MOVE.B (A2)+,D0 AND #255,D0 MOVE D0,D4 CMPI #10,D0 BNE.S L35 L36: MOVE D6,D0 LEA (A3),A0 ADDA D0,A0 CLR.B (A0) CLR D6 CLR -4(A6) L37: MOVE.B (A2)+,D4 AND #255,D4 CMPI #10,D4 BNE.S L40 MOVE -4(A6),D0 BEQ.S L41 BRA.S L39 L41: MOVE #1,-4(A6) BRA.S L42 L40: MOVE D4,D0 MOVE D6,D1 ADDQ #1,D6 LEA 8(A3),A0 ADDA D1,A0 MOVE.B D0,(A0) L42: L38: BRA.S L37 L39: MOVE D6,D0 LEA 8(A3),A0 ADDA D0,A0 CLR.B (A0) MOVE.B (A2)+,D0 EXT D0 CMP #77,D0 BNE.S L43 ORI #16,48(A3) L43: ADDQ.L #1,A2 MOVE #4,-(A7) MOVE.L A2,-(A7) JSR F279_xxxx_(PC) ADDQ.L #6,A7 MOVE D0,54(A3) MOVE D0,52(A3) ADDQ.L #4,A2 MOVE #4,-(A7) MOVE.L A2,-(A7) JSR F279_xxxx_(PC) ADDQ.L #6,A7 MOVE D0,58(A3) MOVE D0,56(A3) ADDQ.L #4,A2 MOVE #4,-(A7) MOVE.L A2,-(A7) JSR F279_xxxx_(PC) ADDQ.L #6,A7 MOVE D0,62(A3) MOVE D0,60(A3) ADDQ.L #4,A2 ADDQ.L #1,A2 CLR D6 BRA.S L44 L45: MOVE D6,D0 MULS #3,D0 LEA 72(A3),A0 ADDA D0,A0 MOVE.B #30,(A0) MOVE #2,-(A7) MOVE.L A2,-(A7) JSR F279_xxxx_(PC) ADDQ.L #6,A7 MOVE D6,D1 MULS #3,D1 LEA 70(A3),A0 ADDA D1,A0 MOVE.B D0,(A0) MOVE D6,D1 MULS #3,D1 LEA 71(A3),A0 ADDA D1,A0 AND #255,D0 MOVE.B D0,(A0) ADDQ.L #2,A2 L46: ADDQ #1,D6 L44: CMPI #6,D6 BLS.S L45 L47: MOVE.B #10,72(A3) ADDQ.L #1,A2 MOVE #4,D6 BRA.S L48 L49: MOVE.B (A2)+,D0 EXT D0 SUB #65,D0 MOVE D0,D4 CMPI #0,D0 BLS.S L52 MOVE.L #125,D0 ASL.L D4,D0 MOVE D6,D1 MULS #6,D1 LEA 94(A3),A0 ADDA D1,A0 MOVE.L D0,(A0) L52: L50: ADDQ #1,D6 L48: CMPI #19,D6 BLS.S L49 L51: CLR D6 BRA.S L53 L54: CLR.L -18(A6) MOVE D6,D5 ADDQ #1,D5 ASL #2,D5 CLR -4(A6) BRA.S L57 L58: MOVE D5,D0 ADD -4(A6),D0 MULS #6,D0 LEA 94(A3),A0 ADDA D0,A0 MOVE.L (A0),D0 ADD.L D0,-18(A6) L59: ADDQ #1,-4(A6) L57: CMPI #4,-4(A6) BCS.S L58 L60: MOVE D6,D0 MULS #6,D0 LEA 94(A3),A0 ADDA D0,A0 MOVE.L -18(A6),(A0) L55: ADDQ #1,D6 L53: CMPI #3,D6 BLS.S L54 L56: MOVE -2(A6),D0 ADDQ #1,D0 MOVE D0,G299_ui_Ca(A4) ADDQ #1,G305_ui_Pa(A4) MOVE G305_ui_Pa(A4),D0 CMPI #1,D0 BNE.S L61 CLR -(A7) JSR F368_fzzz_(PC) ADDQ.L #2,A7 MOVE #1,G508_B_Ref(A4) BRA.S L62 L61: JSR F388_rzzz_(PC) MOVE G305_ui_Pa(A4),D0 SUBQ #1,D0 MOVE D0,-(A7) JSR F386_ezzz_(PC) ADDQ.L #2,A7 L62: MOVE G306_i_Par(A4),-8(A6) MOVE G307_i_Par(A4),-10(A6) MOVE G308_i_Par(A4),D0 ADDQ #2,D0 AND #3,D0 MOVE D0,-12(A6) MOVE G308_i_Par(A4),D1 ASL.L #1,D1 LEA G233_ai_Gr(A4),A0 ADDA D1,A0 MOVE (A0),D1 MOVE -8(A6),D0 ADD D1,D0 MOVE D0,-8(A6) MOVE G308_i_Par(A4),D1 ASL.L #1,D1 LEA G234_ai_Gr(A4),A0 ADDA D1,A0 MOVE (A0),D1 MOVE -10(A6),D0 ADD D1,D0 MOVE D0,-10(A6) MOVE -10(A6),-(A7) MOVE -8(A6),-(A7) JSR F161_szzz_(PC) ADDQ.L #4,A7 MOVE D0,D7 MOVE #13,D6 BRA L63(PC) L64: MOVE D7,D0 AND #15360,D0 LSR #2,D0 LSR #8,D0 MOVE D0,D4 CMPI #3,D0 BLS L66(PC) MOVE D7,D0 LSR #6,D0 LSR #8,D0 CMP -12(A6),D0 BNE L66(PC) MOVE D7,-(A7) JSR F141_anzz_(PC) ADDQ.L #2,A7 MULS #6,D0 LEA G237_as_Gr+4(A4),A0 ADDA D0,A0 MOVE (A0),-14(A6) MOVE D4,D0 L67: CMP #6,D0 BEQ.S L68 BRA.S L70 L68: MOVE #2,-6(A6) BRA.S L72 L73: MOVE -14(A6),D0 MOVE -6(A6),D1 ASL.L #1,D1 LEA G038_ai_Gr(A4),A0 ADDA D1,A0 AND (A0),D0 BEQ.S L76 BRA L2T280_048(PC) L76: L74: ADDQ #1,-6(A6) L72: CMPI #5,-6(A6) BLS.S L73 L75: MOVE -14(A6),D0 AND G038_ai_Gr+20(A4),D0 BEQ.S L77 CMPI #-1,232(A3) BNE.S L77 MOVE #10,-6(A6) BRA.S L78 L77: BRA.S L2T280_046 L78: BRA L69(PC) BRA.S L71 L70: CMP #5,D0 BEQ.S L71 BRA.S L79 L71: CMPI #-1,214(A3) BNE.S L81 MOVE #1,-6(A6) BRA.S L82 L81: BRA.S L2T280_046 L82: BRA.S L69 BRA.S L80 L79: CMP #7,D0 BEQ.S L80 L83: CMP #8,D0 BEQ.S L80 BRA.S L84 L80: CMPI #-1,234(A3) BNE.S L86 MOVE #11,-6(A6) BRA.S L87 L86: CMPI #-1,224(A3) BNE.S L88 MOVE #6,-6(A6) BRA.S L89 L88: BRA.S L2T280_046 L89: L87: BRA.S L69 BRA.S L85 L84: CMP #9,D0 BEQ.S L85 L90: CMP #10,D0 BEQ.S L85 BRA.S L91 L85: L2T280_046: MOVE -14(A6),D0 AND G038_ai_Gr+20(A4),D0 BEQ.S L93 CMPI #-1,232(A3) BNE.S L93 MOVE #10,-6(A6) BRA.S L94 L93: MOVE D6,D0 ADDQ #1,D6 MOVE D0,-6(A6) L94: L91: L92: L69: L2T280_048: MOVE -6(A6),D0 ASL.L #1,D0 LEA 212(A3),A0 ADDA D0,A0 CMPI #-1,(A0) BEQ.S L95 BRA.S L2T280_046 L95: MOVE -6(A6),-(A7) MOVE D7,-(A7) MOVE -2(A6),-(A7) JSR F301_apzz_(PC) ADDQ.L #6,A7 L66: MOVE D7,-(A7) JSR F159_rzzz_(PC) ADDQ.L #2,A7 MOVE D0,D7 L63: CMPI #-2,D7 BNE L64(PC) L65: MOVE -2(A6),-(A7) JSR F355_hzzz_(PC) ADDQ.L #2,A7 JSR F456_vzzz_(PC) L19: MOVEM.L (A7)+,D4-D7/A2-A3 UNLK A6 RTS L$18: .EQU #-96 F281_xxxx_:/* global */ LINK A6,L$96 MOVEM.L A3-A2/D7-D4,-(A7) MOVE.L 8(A6),A3 MOVE #3,-8(A6) MOVE #8,-6(A6) MOVE #3,D0 MOVE D0,-12(A6) ADD #167,D0 MOVE D0,-10(A6) MOVE #112,-(A7) MOVE #12,-(A7) PEA -12(A6) MOVE.L G296_puc_B(A4),-(A7) JSR F135_xzzz_(PC) ADDA #12,A7 MOVE #4,-(A7) MOVE #72,-(A7) PEA G032_s_Gra(A4) MOVE #27,-(A7) JSR F489_ayzz_(PC) ADDQ.L #2,A7 MOVE.L D0,-(A7) JSR F020_aAA5_(PC) ADDA #12,A7 DATA SEG "s!" DATA 5F 5F 5F 5F 5F 5F 5F 00 CODE SEG "player" PEA s!+32(A4) MOVE #13,-(A7) MOVE #58,-(A7) MOVE #177,-(A7) JSR F052_aaoz_(PC) ADDA #10,A7 DATA SEG "s!" DATA 5F 5F 5F 5F 5F 5F 5F 5F 5F 5F 5F 5F 5F 5F 5F 5F 5F 5F 5F 00 CODE SEG "player" PEA s!+40(A4) MOVE #13,-(A7) MOVE #76,-(A7) MOVE #105,-(A7) JSR F052_aaoz_(PC) ADDA #10,A7 JSR F077_aA39_(PC) CLR -(A7) JSR F097_lzzz_(PC) ADDQ.L #2,A7 CLR -(A7) JSR F067_aaat_(PC) ADDQ.L #2,A7 JSR F078_xzzz_(PC) MOVE #0,D0 MOVE D0,D7 LEA (A3),A0 ADDA D0,A0 CLR.B (A0) CLR.B 8(A3) MOVE #1,D6 LEA (A3),A0 MOVE.L A0,A2 MOVE #177,-2(A6) MOVE #91,-4(A6) MOVE G588_i_Mou(A4),D0 AND #2,D0 MOVE D0,-20(A6) L98: CMPI #2,D6 SEQ D0 TST.B D0 BEQ.S L102 CMPI #19,D7 SEQ D0 TST.B D0 L102: AND #1,D0 MOVE D0,D4 BNE.S L101 JSR F077_aA39_(PC) PEA G051_ac_Gr(A4) MOVE #12,-(A7) MOVE #9,-(A7) MOVE -4(A6),-(A7) MOVE -2(A6),-(A7) MOVE #160,-(A7) MOVE.L G348_pl_Bi(A4),-(A7) JSR F040_aacZ_(PC) ADDA #18,A7 JSR F078_xzzz_(PC) L101: BRA L103(PC) L104: MOVE G588_i_Mou(A4),D0 AND #2,D0 MOVE D0,-18(A6) MOVE -18(A6),D0 BEQ L106(PC) MOVE -20(A6),D0 BNE L106(PC) MOVE G589_i_Mou(A4),-14(A6) MOVE G590_i_Mou(A4),-16(A6) CMPI #2,D6 BEQ.S L108 CMPI #0,D7 BLS L107(PC) L108: CMPI #197,-14(A6) BCS L107(PC) CMPI #215,-14(A6) BHI L107(PC) CMPI #147,-16(A6) BCS L107(PC) CMPI #155,-16(A6) BHI L107(PC) MOVE D7,-22(A6) LEA (A3),A0 MOVE.L A0,D0 MOVE.L D0,A2 MOVE.L D0,-(A7) PEA -30(A6) JSR strcpy(PC) ADDQ.L #8,A7 MOVE.L A2,-(A7) JSR strlen(PC) ADDQ.L #4,A7 MOVE D0,D7 BRA.S L109 L110: MOVE D7,D0 MOVE.L A2,A0 ADDA D0,A0 CLR.B (A0) L109: SUBQ #1,D7 MOVE D7,D0 MOVE.L A2,A0 ADDA D0,A0 MOVE.B (A0),D0 EXT D0 CMP #32,D0 BEQ.S L110 L111: CLR D7 BRA.S L112 L113: MOVE.L A2,-(A7) MOVE D7,D0 MULS #800,D0 LEA G407_s_Par(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,-(A7) JSR strcmp(PC) ADDQ.L #8,A7 TST D0 BNE.S L116 BRA.S L3T281_011_ L116: L114: ADDQ #1,D7 L112: MOVE D7,D0 MOVE G305_ui_Pa(A4),D1 SUBQ #1,D1 CMP D1,D0 BCS.S L113 L115: BRA L97(PC) L3T281_011_: CMPI #2,D6 BNE.S L117 LEA 8(A3),A0 MOVE.L A0,A2 L117: PEA -30(A6) LEA (A3),A0 MOVE.L A0,D0 MOVE.L D0,A2 MOVE.L D0,-(A7) JSR strcpy(PC) ADDQ.L #8,A7 MOVE -22(A6),D7 BRA L118(PC) L107: CMPI #107,-14(A6) BCS.S L119 CMPI #175,-14(A6) BHI.S L119 CMPI #147,-16(A6) BCS.S L119 CMPI #155,-16(A6) BHI.S L119 MOVE #8,D5 BRA L105(PC) L119: CMPI #107,-14(A6) BCS.S L121 CMPI #215,-14(A6) BHI.S L121 CMPI #116,-16(A6) BCS.S L121 CMPI #144,-16(A6) BLS.S L120 L121: BRA L3T281_023(PC) L120: MOVE -14(A6),D0 ADDQ #4,D0 AND.L #65535,D0 DIVU #10,D0 SWAP D0 TST D0 BEQ.S L123 MOVE -16(A6),D0 ADDQ #5,D0 AND.L #65535,D0 DIVU #10,D0 SWAP D0 TST D0 BNE.S L122 CMPI #207,-14(A6) BCS.S L124 CMPI #135,-16(A6) BEQ.S L122 L124: L123: BRA.S L3T281_023 L122: MOVE #11,D5 MOVE -16(A6),D1 SUB #116,D1 AND.L #65535,D1 DIVU #10,D1 MULU D1,D5 MOVE D5,-40(A6) MOVE #65,D5 ADD -40(A6),D5 MOVE -14(A6),D1 SUB #107,D1 AND.L #65535,D1 DIVU #10,D1 ADD D1,D5 CMPI #86,D5 BEQ.S L126 CMPI #97,D5 BNE.S L125 L126: MOVE #13,D5 BRA.S L105 L125: CMPI #87,D5 BLT.S L127 SUBQ #1,D5 L127: CMPI #90,D5 BLE.S L128 MOVE D5,D0 SUB #90,D0 LEA G053_ac_Gr+-1(A4),A0 ADDA D0,A0 MOVE.B (A0),D0 EXT D0 MOVE D0,D5 L128: BRA.S L105 L118: L106: L3T281_023: MOVE -18(A6),-20(A6) MOVE #37,-(A7) JSR R056_aaal_(PC) ADDQ.L #2,A7 L103: MOVE #11,-(A7) JSR R057_rzzz_(PC) ADDQ.L #2,A7 TST D0 BEQ L104(PC) L105: MOVE -18(A6),-20(A6) MOVE #11,-(A7) JSR R057_rzzz_(PC) ADDQ.L #2,A7 TST D0 BEQ.S L129 MOVE #7,-(A7) JSR R057_rzzz_(PC) ADDQ.L #2,A7 MOVE D0,D5 L129: CMPI #97,D5 BLT.S L130 CMPI #122,D5 BGT.S L130 SUB #32,D5 L130: CMPI #65,D5 BLT.S L133 CMPI #90,D5 BLE.S L132 L133: CMPI #46,D5 BEQ.S L132 CMPI #44,D5 BEQ.S L132 CMPI #59,D5 BEQ.S L132 CMPI #58,D5 BEQ.S L132 CMPI #32,D5 BNE.S L131 L132: CMPI #32,D5 BNE.S L134 CMPI #0,D7 BNE.S L134 BRA.S L135 L134: MOVE D4,D0 BNE.S L136 MOVE D5,D0 MOVE.B D0,G052_ac_Gr(A4) JSR F077_aA39_(PC) PEA G052_ac_Gr(A4) MOVE #12,-(A7) MOVE #13,-(A7) MOVE -4(A6),-(A7) MOVE -2(A6),-(A7) MOVE #160,-(A7) MOVE.L G348_pl_Bi(A4),-(A7) JSR F040_aacZ_(PC) ADDA #18,A7 JSR F078_xzzz_(PC) MOVE D5,D0 MOVE D7,D1 ADDQ #1,D7 MOVE.L A2,A0 ADDA D1,A0 MOVE.B D0,(A0) MOVE D7,D0 MOVE.L A2,A0 ADDA D0,A0 CLR.B (A0) ADDQ #6,-2(A6) CMPI #1,D6 BNE.S L137 CMPI #7,D7 BNE.S L137 BRA.S L3T281_033_ L137: L136: L135: BRA L138(PC) L131: CMPI #13,D5 BNE.S L139 CMPI #1,D6 BNE.S L140 CMPI #0,D7 BLS.S L140 JSR F077_aA39_(PC) PEA G051_ac_Gr(A4) MOVE #12,-(A7) MOVE #13,-(A7) MOVE -4(A6),-(A7) MOVE -2(A6),-(A7) MOVE #160,-(A7) MOVE.L G348_pl_Bi(A4),-(A7) JSR F040_aacZ_(PC) ADDA #18,A7 JSR F078_xzzz_(PC) L3T281_033_: MOVE #2,D6 LEA 8(A3),A0 MOVE.L A0,A2 MOVE #105,-2(A6) MOVE #109,-4(A6) CLR D7 L140: BRA L141(PC) L139: CMPI #8,D5 BNE L142(PC) CMPI #1,D6 BNE.S L143 CMPI #0,D7 BNE.S L143 BRA.S L99 L143: MOVE D4,D0 BNE.S L144 JSR F077_aA39_(PC) PEA G051_ac_Gr(A4) MOVE #12,-(A7) MOVE #13,-(A7) MOVE -4(A6),-(A7) MOVE -2(A6),-(A7) MOVE #160,-(A7) MOVE.L G348_pl_Bi(A4),-(A7) JSR F040_aacZ_(PC) ADDA #18,A7 JSR F078_xzzz_(PC) L144: CMPI #0,D7 BNE.S L145 LEA (A3),A0 MOVE.L A0,A2 MOVE.L A2,-(A7) JSR strlen(PC) ADDQ.L #4,A7 SUBQ #1,D0 MOVE D0,D7 MOVE #1,D6 MOVE #177,D0 MOVE D7,D1 MULU #6,D1 ADD D1,D0 MOVE D0,-2(A6) MOVE #91,-4(A6) BRA.S L146 L145: SUBQ #1,D7 SUBQ #6,-2(A6) L146: MOVE D7,D0 MOVE.L A2,A0 ADDA D0,A0 CLR.B (A0) L142: L141: L138: L99: BRA L98(PC) L100: L97: MOVEM.L (A7)+,D4-D7/A2-A3 UNLK A6 RTS L$96: .EQU #-40 F282_xzzz_:/* global */ LINK A6,L$147 MOVEM.L A3-A2/D7-D4,-(A7) MOVE G305_ui_Pa(A4),D0 SUBQ #1,D0 MOVE D0,D7 MULS #800,D0 LEA G407_s_Par(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,A3 CMPI #162,8(A6) BNE L149(PC) MOVE #4,-(A7) JSR F355_hzzz_(PC) ADDQ.L #2,A7 CLR G299_ui_Ca(A4) CMPI #1,G305_ui_Pa(A4) BNE.S L150 MOVE #-1,-(A7) JSR F368_fzzz_(PC) ADDQ.L #2,A7 L150: SUBQ #1,G305_ui_Pa(A4) CLR -8(A6) MOVE #28,-6(A6) MOVE D7,D0 MULU #69,D0 MOVE D0,-12(A6) ADD #66,D0 MOVE D0,-10(A6) CLR G578_B_Use(A4) JSR F077_aA39_(PC) MOVE #160,-(A7) CLR -(A7) PEA -12(A6) MOVE.L G348_pl_Bi(A4),-(A7) JSR F135_xzzz_(PC) ADDA #12,A7 MOVE #160,-(A7) CLR -(A7) MOVE.B 29(A3),D0 AND #255,D0 ADDQ #4,D0 SUB G308_i_Par(A4),D0 AND #3,D0 ASL #2,D0 ASL.L #1,D0 LEA G054_ai_Gr(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,-(A7) MOVE.L G348_pl_Bi(A4),-(A7) JSR F135_xzzz_(PC) ADDA #12,A7 JSR F457_AA08_(PC) JSR F078_xzzz_(PC) BRA L151(PC) L149: CLR G299_ui_Ca(A4) MOVE G306_i_Par(A4),-2(A6) MOVE G307_i_Par(A4),-4(A6) MOVE G308_i_Par(A4),D1 ASL.L #1,D1 LEA G233_ai_Gr(A4),A0 ADDA D1,A0 MOVE (A0),D1 MOVE -2(A6),D0 ADD D1,D0 MOVE D0,-2(A6) MOVE G308_i_Par(A4),D1 ASL.L #1,D1 LEA G234_ai_Gr(A4),A0 ADDA D1,A0 MOVE (A0),D1 MOVE -4(A6),D0 ADD D1,D0 MOVE D0,-4(A6) CLR D6 BRA.S L152 L153: MOVE D6,D0 ASL.L #1,D0 LEA 212(A3),A0 ADDA D0,A0 MOVE (A0),D0 MOVE D0,D4 CMPI #-1,D0 BEQ.S L156 MOVE -4(A6),-(A7) MOVE -2(A6),-(A7) CLR -(A7) MOVE D4,-(A7) JSR F164_dzzz_(PC) ADDQ.L #8,A7 L156: L154: ADDQ #1,D6 L152: CMPI #30,D6 BCS.S L153 L155: MOVE -4(A6),-(A7) MOVE -2(A6),-(A7) JSR F161_szzz_(PC) ADDQ.L #4,A7 MOVE D0,D4 L157: MOVE D4,D0 AND #15360,D0 LSR #2,D0 LSR #8,D0 CMPI #3,D0 BNE.S L160 MOVE D4,-(A7) JSR F156_afzz_(PC) ADDQ.L #2,A7 MOVE.L D0,A2 ANDI #-128,2(A2) BRA.S L159 L160: MOVE D4,-(A7) JSR F159_rzzz_(PC) ADDQ.L #2,A7 MOVE D0,D4 L158: BRA.S L157 L159: CMPI #161,8(A6) BNE.S L161 MOVE.L A3,-(A7) JSR F281_xxxx_(PC) ADDQ.L #4,A7 MOVE #120,-(A7) LEA 92(A3),A0 MOVE.L A0,-(A7) JSR F008_aA19_(PC) ADDQ.L #6,A7 CLR D6 BRA.S L162 L163: JSR F027_AA59_(PC) AND.L #65535,D0 DIVU #7,D0 SWAP D0 MOVE D0,D5 MOVE D5,D0 MULS #3,D0 LEA 71(A3),A0 ADDA D0,A0 ADDQ.B #1,(A0) MOVE D5,D0 MULS #3,D0 LEA 70(A3),A0 ADDA D0,A0 ADDQ.B #1,(A0) L164: ADDQ #1,D6 L162: CMPI #12,D6 BCS.S L163 L165: L161: CMPI #1,G305_ui_Pa(A4) BNE.S L166 MOVE.L G313_ul_Ga(A4),G362_l_Las(A4) CLR -(A7) JSR F368_fzzz_(PC) ADDQ.L #2,A7 CLR -(A7) JSR F394_ozzz_(PC) ADDQ.L #2,A7 BRA.S L167 L166: MOVE G514_i_Mag(A4),-(A7) JSR F393_lzzz_(PC) ADDQ.L #2,A7 L167: JSR F051_AA19_(PC) LEA (A3),A0 MOVE.L A0,-(A7) MOVE D7,D0 LEA G046_auc_G(A4),A0 ADDA D0,A0 MOVE.B (A0),D0 AND #255,D0 MOVE D0,D6 MOVE D0,-(A7) JSR F047_xzzz_(PC) ADDQ.L #6,A7 DATA SEG "s!" DATA 20 5A 55 4D 20 4C 45 42 45 4E 20 45 52 57 45 43 4B 54 2E 00 20 52 45 49 4E 4B 41 52 4E 49 45 52 54 2E 00 00 CODE SEG "player" CMPI #160,8(A6) BNE.S L168 LEA s!+60(A4),A0 MOVE.L A0,D0 BRA.S L169 L168: LEA s!+80(A4),A0 MOVE.L A0,D0 L169: MOVE.L D0,-(A7) MOVE D6,-(A7) JSR F047_xzzz_(PC) ADDQ.L #6,A7 MOVE #4,-(A7) JSR F355_hzzz_(PC) ADDQ.L #2,A7 JSR F457_AA08_(PC) CMPI #-1,G411_i_Lea(A4) BNE.S L170 MOVE #0,D0 BRA.S L171 L170: MOVE #1,D0 L171: MOVE D0,-(A7) JSR F067_aaat_(PC) ADDQ.L #2,A7 L151: L148: MOVEM.L (A7)+,D4-D7/A2-A3 UNLK A6 RTS L$147: .EQU #-12 F283_azzz_:/* global */ LINK A6,L$172 MOVEM.L A3/D7,-(A7) MOVE 8(A6),D0 MULS #800,D0 LEA G407_s_Par(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,A3 MOVE.B 29(A3),D0 AND #255,D0 MOVE D0,-(A7) JSR F285_szzz_(PC) ADDQ.L #2,A7 CMPI #-1,D0 BEQ.S L174 CLR D7 BRA.S L175 L176: L177: ADDQ #1,D7 L175: MOVE D7,-(A7) JSR F285_szzz_(PC) ADDQ.L #2,A7 CMPI #-1,D0 BNE.S L176 L178: MOVE D7,D0 MOVE.B D0,29(A3) L174: MOVE 54(A3),D7 MOVE D7,D0 MOVE D7,D1 LSR #6,D1 SUB D1,D0 SUBQ #1,D0 MOVE D0,-(A7) MOVE #25,-(A7) JSR F025_aatz_(PC) ADDQ.L #4,A7 MOVE D0,54(A3) ASR #1,D0 MOVE D0,52(A3) MOVE G514_i_Mag(A4),-(A7) JSR F393_lzzz_(PC) ADDQ.L #2,A7 MOVE G308_i_Par(A4),D0 MOVE.B D0,28(A3) ORI #-27648,48(A3) MOVE 8(A6),-(A7) JSR F292_arzz_(PC) ADDQ.L #2,A7 L173: MOVEM.L (A7)+,D7/A3 UNLK A6 RTS L$172: .EQU #0 F284_czzz_:/* global */ LINK A6,L$179 MOVEM.L A3/D7-D5,-(A7) MOVE 8(A6),D7 MOVE D7,D0 CMP G308_i_Par(A4),D0 BNE.S L181 BRA.S L180 L181: MOVE D7,D0 SUB G308_i_Par(A4),D0 MOVE D0,D5 CMPI #0,D0 BGE.S L182 ADDQ #4,D5 L182: LEA G407_s_Par(A4),A0 MOVE.L A0,A3 CLR D6 BRA.S L183 L184: MOVE.B 29(A3),D0 AND #255,D0 ADD D5,D0 AND #3,D0 MOVE.B D0,29(A3) MOVE.B 28(A3),D0 AND #255,D0 ADD D5,D0 AND #3,D0 MOVE.B D0,28(A3) ADDA #800,A3 L185: ADDQ #1,D6 L183: MOVE D6,D0 CMP G305_ui_Pa(A4),D0 BCS.S L184 L186: MOVE D7,G308_i_Par(A4) JSR F296_aizz_(PC) L180: MOVEM.L (A7)+,D5-D7/A3 UNLK A6 RTS L$179: .EQU #0 F285_szzz_:/* global */ LINK A6,L$187 MOVEM.L A3/D7-D6,-(A7) MOVE 8(A6),D7 MOVE #0,D0 MOVE D0,D6 LEA G407_s_Par(A4),A0 MOVE.L A0,D0 MOVE.L D0,A3 BRA.S L189 L190: MOVE.B 29(A3),D0 AND #255,D0 CMP D7,D0 BNE.S L193 MOVE 52(A3),D0 BEQ.S L193 MOVE D6,D0 BRA.S L188 L193: L191: MOVE D6,D0 ADDQ #1,D6 MOVE.L A3,D0 ADDA #800,A3 L189: MOVE D6,D0 CMP G305_ui_Pa(A4),D0 BCS.S L190 L192: MOVE #-1,D0 L188: MOVEM.L (A7)+,D6-D7/A3 UNLK A6 RTS L$187: .EQU #0 F286_hzzz_:/* global */ LINK A6,L$194 MOVEM.L D7-D6,-(A7) MOVE G305_ui_Pa(A4),D0 BEQ L196(PC) MOVE 8(A6),D0 MOVE G306_i_Par(A4),D1 SUB D1,D0 MOVE D0,-(A7) JSR F023_aarz_(PC) ADDQ.L #2,A7 MOVE.L D0,-(A7) MOVE 10(A6),D0 MOVE G307_i_Par(A4),D1 SUB D1,D0 MOVE D0,-(A7) JSR F023_aarz_(PC) ADDQ.L #2,A7 MOVE.L D0,D1 MOVE.L (A7)+,D0 ADD D1,D0 CMPI #1,D0 BGT.S L196 MOVE 12(A6),-(A7) MOVE 10(A6),-(A7) MOVE 8(A6),-(A7) MOVE G307_i_Par(A4),-(A7) MOVE G306_i_Par(A4),-(A7) PEA -4(A6) JSR F229_hzzz_(PC) ADDA #14,A7 CLR D7 BRA.S L197 L198: MOVE D7,D0 LEA -4(A6),A0 ADDA D0,A0 MOVE.B (A0),D0 AND #255,D0 MOVE D0,-(A7) JSR F285_szzz_(PC) ADDQ.L #2,A7 MOVE D0,D6 CMPI #0,D0 BLT.S L201 MOVE D6,D0 BRA.S L195 L201: L199: ADDQ #1,D7 L197: CMPI #4,D7 BCS.S L198 L200: L196: MOVE #-1,D0 L195: MOVEM.L (A7)+,D6-D7 UNLK A6 RTS L$194: .EQU #-4 F287_xxxx_:/* global */ LINK A6,L$202 MOVEM.L A3-A2/D7-D4,-(A7) MOVE 8(A6),D0 MULS #800,D0 LEA G407_s_Par(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,A3 CLR D6 CMPI #0,52(A3) BLE.S L204 MOVE 52(A3),D5 EXT.L D5 ASL.L #2,D5 ASL.L #8,D5 MOVE.L D5,-(A7) MOVE.L #25,D5 MOVE.L D5,-(A7) JSR _lmul(PC) MOVE.L (A7)+,D5 MOVE.L D5,-(A7) MOVE 54(A3),D5 EXT.L D5 MOVE.L D5,-(A7) JSR _ldiv(PC) MOVE.L (A7)+,D5 ADDQ.L #4,A7 MOVE.L D5,D0 AND.L #1023,D0 BEQ.S L205 MOVE.L D5,D0 ASR.L #2,D0 ASR.L #8,D0 ADDQ.L #1,D0 MOVE D6,D1 ADDQ #1,D6 ASL.L #1,D1 LEA -6(A6),A0 ADDA D1,A0 MOVE D0,(A0) BRA.S L206 L205: MOVE.L D5,D0 ASR.L #2,D0 ASR.L #8,D0 MOVE D6,D1 ADDQ #1,D6 ASL.L #1,D1 LEA -6(A6),A0 ADDA D1,A0 MOVE D0,(A0) L206: BRA.S L207 L204: MOVE D6,D0 ADDQ #1,D6 ASL.L #1,D0 LEA -6(A6),A0 ADDA D0,A0 CLR (A0) L207: CMPI #0,56(A3) BLE.S L208 MOVE 56(A3),D5 EXT.L D5 ASL.L #2,D5 ASL.L #8,D5 MOVE.L D5,-(A7) MOVE.L #25,D5 MOVE.L D5,-(A7) JSR _lmul(PC) MOVE.L (A7)+,D5 MOVE.L D5,-(A7) MOVE 58(A3),D5 EXT.L D5 MOVE.L D5,-(A7) JSR _ldiv(PC) MOVE.L (A7)+,D5 ADDQ.L #4,A7 MOVE.L D5,D0 AND.L #1023,D0 BEQ.S L209 MOVE.L D5,D0 ASR.L #2,D0 ASR.L #8,D0 ADDQ.L #1,D0 MOVE D6,D1 ADDQ #1,D6 ASL.L #1,D1 LEA -6(A6),A0 ADDA D1,A0 MOVE D0,(A0) BRA.S L210 L209: MOVE.L D5,D0 ASR.L #2,D0 ASR.L #8,D0 MOVE D6,D1 ADDQ #1,D6 ASL.L #1,D1 LEA -6(A6),A0 ADDA D1,A0 MOVE D0,(A0) L210: BRA.S L211 L208: MOVE D6,D0 ADDQ #1,D6 ASL.L #1,D0 LEA -6(A6),A0 ADDA D0,A0 CLR (A0) L211: CMPI #0,60(A3) BLE.S L212 MOVE 60(A3),D0 CMP 62(A3),D0 BLE.S L213 MOVE D6,D0 ASL.L #1,D0 LEA -6(A6),A0 ADDA D0,A0 MOVE #25,(A0) BRA.S L214 L213: MOVE 60(A3),D5 EXT.L D5 ASL.L #2,D5 ASL.L #8,D5 MOVE.L D5,-(A7) MOVE.L #25,D5 MOVE.L D5,-(A7) JSR _lmul(PC) MOVE.L (A7)+,D5 MOVE.L D5,-(A7) MOVE 62(A3),D5 EXT.L D5 MOVE.L D5,-(A7) JSR _ldiv(PC) MOVE.L (A7)+,D5 ADDQ.L #4,A7 MOVE.L D5,D0 AND.L #1023,D0 BEQ.S L215 MOVE.L D5,D0 ASR.L #2,D0 ASR.L #8,D0 ADDQ.L #1,D0 MOVE D6,D1 ASL.L #1,D1 LEA -6(A6),A0 ADDA D1,A0 MOVE D0,(A0) BRA.S L216 L215: MOVE.L D5,D0 ASR.L #2,D0 ASR.L #8,D0 MOVE D6,D1 ASL.L #1,D1 LEA -6(A6),A0 ADDA D1,A0 MOVE D0,(A0) L216: L214: BRA.S L217 L212: MOVE D6,D0 ASL.L #1,D0 LEA -6(A6),A0 ADDA D0,A0 CLR (A0) L217: JSR F077_aA39_(PC) MOVE.L G348_pl_Bi(A4),A0 LEA 320(A0),A0 MOVE 8(A6),D1 EXT.L D1 CMP #3,D1 BCS.S L9T287_014 MOVE.L #-./,),(-*,(,D6 MOVE.L D6,D7 ADDQ.L #1,D7 BRA.S L9T287_017 L9T287_014: CMP #2,D1 BCS.S L9T287_015 MOVEQ #0,D6 MOVE.L #-./,),(-*,(,D7 BRA.S L9T287_017 L9T287_015: CMP #1,D1 BCS.S L9T287_016 MOVE.L #-2147483647,D6 MOVE.L D6,D7 SUBQ.L #1,D7 BRA.S L9T287_017 L9T287_016: MOVE.L #-2147483647,D6 MOVEQ #1,D7 L9T287_017: ADD D1,D1 MOVE D1,D2 ADD D1,D1 ADD D2,D1 MOVE D1,-8(A6) ADDQ #4,-8(A6) LEA -6(A6),A3 L9T287_018_: MOVE.L A0,A2 LEA G056_aaui_(A4),A1 ADDA 0(A1,D1),A2 LSL #1,D1 LEA G055_aaaui(A4),A1 MOVE 0(A1,D1),D2 MOVE 2(A1,D1),D3 MOVE D2,D4 NOT D4 MOVE D3,D5 NOT D5 LSR #1,D1 MOVE (A3)+,D0 JSR S287_xxxx_(PC) CMP -8(A6),D1 BEQ L9T287_030(PC) ADDQ #2,D1 BRA.S L9T287_018_ S287_xxxx_:/* global */ MOVE D1,-(A7) MOVE #24,D1 L9T287_020_: CMP D1,D0 BHI.S L9T287_021 AND D4,(A2) AND D5,8(A2) AND D4,2(A2) AND D5,10(A2) OR D2,4(A2) OR D3,12(A2) OR D2,6(A2) OR D3,14(A2) BRA.S L9T287_029 L9T287_021: TST D6 BEQ.S L9T287_022 OR D2,(A2) OR D3,8(A2) BRA.S L9T287_023 L9T287_022: AND D4,(A2) AND D5,8(A2) L9T287_023: TST.L D6 BGE.S L9T287_024 OR D2,2(A2) OR D3,10(A2) BRA.S L9T287_025 L9T287_024: AND D4,2(A2) AND D5,10(A2) L9T287_025: TST D7 BEQ.S L9T287_026 OR D2,4(A2) OR D3,12(A2) BRA.S L9T287_027 L9T287_026: AND D4,4(A2) AND D5,12(A2) L9T287_027: TST.L D7 BGE.S L9T287_028 OR D2,6(A2) OR D3,14(A2) BRA.S L9T287_029 L9T287_028: AND D4,6(A2) AND D5,14(A2) L9T287_029: LEA 160(A2),A2 DBF D1,L9T287_020_ MOVE (A7)+,D1 RTS L9T287_030: JSR F078_xzzz_(PC) L203: MOVEM.L (A7)+,D4-D7/A2-A3 UNLK A6 RTS L$202: .EQU #-8 F288_xxxx_:/* global */ LINK A6,L$218 BSS SEG "bss" 11G419_ac_: .WORD #6 CODE SEG "player" MOVEM.L A3/D7-D5,-(A7) MOVE 8(A6),D7 MOVE 10(A6),D6 MOVE D6,D0 BEQ.S L220 MOVE #1,-(A7) MOVE #32,-(A7) MOVE #4,-(A7) PEA 11G419_ac_(A4) JSR F009_aA49_(PC) ADDA #10,A7 L220: LEA 11G419_ac_+4(A4),A0 MOVE.L A0,A3 CLR.B (A3) MOVE D7,D0 BNE.S L221 MOVE.B #48,-(A3) BRA.S L222 L221: BRA.S L223 L224: MOVE D7,D0 AND.L #65535,D0 DIVU #10,D0 MOVE D0,D7 MULU #10,D0 MOVE D0,-10(A6) MOVE #48,D0 ADD D5,D0 SUB -10(A6),D0 MOVE.B D0,-(A3) L223: MOVE D7,D5 BNE.S L224 L225: L222: MOVE D6,D0 BEQ.S L226 MOVE #4,D0 SUB 12(A6),D0 LEA 11G419_ac_(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,D0 BRA.S L219 L226: MOVE.L A3,D0 L219: MOVEM.L (A7)+,D5-D7/A3 UNLK A6 RTS L$218: .EQU #-10 F289_xxxx_:/* global */ LINK A6,L$227 MOVE #3,-(A7) MOVE #1,-(A7) MOVE 10(A6),-(A7) JSR F288_xxxx_(PC) ADDQ.L #6,A7 MOVE.L D0,-(A7) MOVE #13,-(A7) MOVE 8(A6),-(A7) MOVE #55,-(A7) JSR F052_aaoz_(PC) ADDA #10,A7 DATA SEG "s!" DATA 2F 00 CODE SEG "player" PEA s!+96(A4) MOVE #13,-(A7) MOVE 8(A6),-(A7) MOVE #73,-(A7) JSR F052_aaoz_(PC) ADDA #10,A7 MOVE #3,-(A7) MOVE #1,-(A7) MOVE 12(A6),-(A7) JSR F288_xxxx_(PC) ADDQ.L #6,A7 MOVE.L D0,-(A7) MOVE #13,-(A7) MOVE 8(A6),-(A7) MOVE #79,-(A7) JSR F052_aaoz_(PC) ADDA #10,A7 L228: UNLK A6 RTS L$227: .EQU #0 F290_xxxx_:/* global */ LINK A6,L$229 MOVE.L A3,-(A7) MOVE.L 8(A6),A3 MOVE 54(A3),-(A7) MOVE 52(A3),-(A7) MOVE #116,-(A7) JSR F289_xxxx_(PC) ADDQ.L #6,A7 MOVE 58(A3),D0 EXT.L D0 DIVS #10,D0 MOVE D0,-(A7) MOVE 56(A3),D0 EXT.L D0 DIVS #10,D0 MOVE D0,-(A7) MOVE #124,-(A7) JSR F289_xxxx_(PC) ADDQ.L #6,A7 MOVE 62(A3),-(A7) MOVE 60(A3),-(A7) MOVE #132,-(A7) JSR F289_xxxx_(PC) ADDQ.L #6,A7 L230: MOVE.L (A7)+,A3 UNLK A6 RTS L$229: .EQU #0 F291_xxxx_:/* global */ LINK A6,L$231 MOVEM.L A3-A2/D7-D4,-(A7) MOVE 10(A6),D7 MOVE #-1,-20(A6) MOVE 8(A6),D0 MULS #800,D0 LEA G407_s_Par(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,A3 MOVE G423_i_Inv(A4),D5 MOVE 8(A6),D1 ADDQ #1,D1 CMP D1,D5 SEQ D5 AND #1,D5 MOVE D5,D0 BNE.S L233 CMPI #1,D7 BHI.S L235 MOVE G299_ui_Ca(A4),D0 MOVE 8(A6),D1 ADDQ #1,D1 CMP D1,D0 BNE.S L234 L235: BRA L232(PC) L234: MOVE 8(A6),D0 ASL #1,D0 ADD D7,D0 MOVE D0,-2(A6) BRA.S L236 L233: MOVE #8,D0 ADD D7,D0 MOVE D0,-2(A6) L236: CMPI #30,D7 BCS.S L237 MOVE D7,D6 ASL.L #1,D6 LEA G425_aT_Ch+-60(A4),A0 ADDA D6,A0 MOVE (A0),D6 BRA.S L238 L237: MOVE D7,D6 ASL.L #1,D6 LEA 212(A3),A0 ADDA D6,A0 MOVE (A0),D6 L238: MOVE -2(A6),D0 MULS #6,D0 LEA G030_as_Gr(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,A2 MOVE (A2),D0 SUBQ #1,D0 MOVE D0,-18(A6) ADD #17,D0 MOVE D0,-16(A6) MOVE 2(A2),D0 SUBQ #1,D0 MOVE D0,-14(A6) ADD #17,D0 MOVE D0,-12(A6) MOVE D5,D0 BEQ.S L239 MOVE.L G296_puc_B(A4),-24(A6) MOVE #112,-26(A6) BRA.S L240 L239: MOVE.L G348_pl_Bi(A4),D0 MOVE.L D0,-24(A6) MOVE #160,-26(A6) JSR F077_aA39_(PC) L240: CMPI #-1,D6 BNE.S L241 CMPI #5,D7 BHI.S L242 MOVE #212,D4 MOVE D7,D1 ASL #1,D1 ADD D1,D4 MOVE 50(A3),D0 MOVE #1,D1 ASL D7,D1 AND D1,D0 BEQ.S L243 ADDQ #1,D4 MOVE #34,-20(A6) BRA.S L244 L243: MOVE #33,-20(A6) L244: BRA.S L245 L242: CMPI #10,D7 BCS.S L246 CMPI #13,D7 BHI.S L246 MOVE #208,D4 MOVE D7,D1 SUB #10,D1 ADD D1,D4 BRA.S L247 L246: MOVE #204,D4 L247: L245: BRA.S L248 L241: MOVE D6,-(A7) JSR F033_aaaz_(PC) ADDQ.L #2,A7 MOVE D0,D4 MOVE D5,D0 BEQ.S L249 CMPI #1,D7 BNE.S L249 CMPI #144,D4 BEQ.S L250 CMPI #30,D4 BNE.S L249 L250: ADDQ #1,D4 L249: CMPI #5,D7 BHI.S L251 MOVE 50(A3),D0 MOVE #1,D1 ASL D7,D1 AND D1,D0 BEQ.S L252 MOVE #34,-20(A6) BRA.S L253 L252: MOVE #33,-20(A6) L253: L251: L248: CMPI #1,D7 BNE.S L254 MOVE 8(A6),D0 ADDQ #1,D0 CMP G506_i_Act(A4),D0 BNE.S L254 MOVE #35,-20(A6) L254: CMPI #-1,-20(A6) BEQ.S L255 MOVE #0,D0 MOVE D0,G578_B_Use(A4) MOVE #12,-(A7) MOVE -26(A6),-(A7) MOVE #16,-(A7) CLR -(A7) CLR -(A7) PEA -18(A6) MOVE.L -24(A6),-(A7) MOVE -20(A6),-(A7) JSR F489_ayzz_(PC) ADDQ.L #2,A7 MOVE.L D0,-(A7) JSR F132_xzzz_(PC) ADDA #22,A7 L255: MOVE D4,-(A7) MOVE -2(A6),-(A7) JSR F038_AA07_(PC) ADDQ.L #4,A7 MOVE D5,D0 BNE.S L256 JSR F078_xzzz_(PC) L256: L232: MOVEM.L (A7)+,D4-D7/A2-A3 UNLK A6 RTS L$231: .EQU #-26 F292_arzz_:/* global */ LINK A6,L$257 MOVEM.L A3-A2/D7-D4,-(A7) MOVE 8(A6),D7 MOVE D7,D0 MULU #69,D0 MOVE D0,-4(A6) MOVE D7,D0 MULS #800,D0 LEA G407_s_Par(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,A3 MOVE 48(A3),D6 MOVE D6,D0 AND #-128,D0 BNE.S L259 BRA L258(PC) L259: MOVE D7,D5 ADDQ #1,D5 MOVE G423_i_Inv(A4),D1 CMP D1,D5 SEQ D5 AND #1,D5 CLR G578_B_Use(A4) JSR F077_aA39_(PC) MOVE D6,D0 AND #4096,D0 BEQ L260(PC) CLR -12(A6) MOVE #28,-10(A6) MOVE -4(A6),D0 MOVE D0,-16(A6) ADD #66,D0 MOVE D0,-14(A6) MOVE 52(A3),D0 BEQ L261(PC) MOVE #160,-(A7) MOVE #12,-(A7) PEA -16(A6) MOVE.L G348_pl_Bi(A4),-(A7) JSR F135_xzzz_(PC) ADDA #12,A7 MOVE #6,-(A7) PEA -22(A6) JSR F008_aA19_(PC) ADDQ.L #6,A7 CLR D4 CMPI #0,G407_s_Par+3206(A4) BLE.S L262 MOVE D4,D0 ADDQ #1,D4 ASL.L #1,D0 LEA -22(A6),A0 ADDA D0,A0 MOVE #38,(A0) L262: CMPI #0,G407_s_Par+3208(A4) BLE.S L263 MOVE D4,D0 ADDQ #1,D4 ASL.L #1,D0 LEA -22(A6),A0 ADDA D0,A0 MOVE #39,(A0) L263: CMPI #0,G407_s_Par+3204(A4) BGT.S L265 MOVE 274(A3),D0 BEQ.S L264 L265: MOVE D4,D0 ADDQ #1,D4 ASL.L #1,D0 LEA -22(A6),A0 ADDA D0,A0 MOVE #37,(A0) L264: BRA.S L266 L267: MOVE #10,-(A7) MOVE #40,-(A7) PEA -16(A6) MOVE D4,D0 ASL.L #1,D0 LEA -22(A6),A0 ADDA D0,A0 MOVE (A0),-(A7) JSR F489_ayzz_(PC) ADDQ.L #2,A7 MOVE.L D0,-(A7) JSR F021_a002_(PC) ADDA #12,A7 L266: MOVE D4,D0 SUBQ #1,D4 TST D0 BNE.S L267 L268: MOVE D5,D0 BEQ.S L269 MOVE D7,-(A7) JSR F354_szzz_(PC) ADDQ.L #2,A7 OR #256,D6 BRA.S L270 L269: OR #-24192,D6 L270: BRA.S L271 L261: MOVE #-1,-(A7) MOVE #40,-(A7) PEA -16(A6) MOVE #8,-(A7) JSR F489_ayzz_(PC) ADDQ.L #2,A7 MOVE.L D0,-(A7) JSR F021_a002_(PC) ADDA #12,A7 LEA (A3),A0 MOVE.L A0,-(A7) MOVE #1,-(A7) MOVE #13,-(A7) MOVE #5,-(A7) MOVE -4(A6),D0 ADDQ #1,D0 MOVE D0,-(A7) JSR F053_aajz_(PC) ADDA #12,A7 MOVE D7,-(A7) JSR F386_ezzz_(PC) ADDQ.L #2,A7 BRA L15T292_042(PC) L271: L260: MOVE 52(A3),D0 BNE.S L272 BRA L15T292_042(PC) L272: MOVE D6,D0 AND #128,D0 BEQ L273(PC) MOVE D7,D4 MOVE G411_i_Lea(A4),D1 CMP D1,D4 BNE.S L274 MOVE #9,D4 BRA.S L275 L274: MOVE #13,D4 L275: MOVE D5,D0 BEQ L276(PC) LEA (A3),A0 MOVE.L A0,D0 MOVE.L D0,A2 MOVE.L D0,-(A7) MOVE D4,-(A7) MOVE #7,-(A7) MOVE #3,-(A7) JSR F052_aaoz_(PC) ADDA #10,A7 MOVE.L A2,-(A7) JSR strlen(PC) ADDQ.L #4,A7 MOVE D0,-32(A6) MOVE #6,D0 MULS -32(A6),D0 ADDQ #3,D0 MOVE D0,-6(A6) MOVE.B 8(A3),-1(A6) MOVE.B -1(A6),D0 EXT D0 CMP #44,D0 BEQ.S L277 MOVE.B -1(A6),D0 EXT D0 CMP #59,D0 BEQ.S L277 MOVE.B -1(A6),D0 EXT D0 CMP #45,D0 BEQ.S L277 ADDQ #6,-6(A6) L277: LEA 8(A3),A0 MOVE.L A0,-(A7) MOVE D4,-(A7) MOVE #7,-(A7) MOVE -6(A6),-(A7) JSR F052_aaoz_(PC) ADDA #10,A7 OR #16384,D6 BRA.S L278 L276: CLR -12(A6) MOVE #6,-10(A6) MOVE -4(A6),D0 MOVE D0,-16(A6) ADD #42,D0 MOVE D0,-14(A6) MOVE #160,-(A7) MOVE #1,-(A7) PEA -16(A6) MOVE.L G348_pl_Bi(A4),-(A7) JSR F135_xzzz_(PC) ADDA #12,A7 LEA (A3),A0 MOVE.L A0,-(A7) MOVE #1,-(A7) MOVE D4,-(A7) MOVE #5,-(A7) MOVE -4(A6),D0 ADDQ #1,D0 MOVE D0,-(A7) JSR F053_aajz_(PC) ADDA #12,A7 L278: L273: MOVE D6,D0 AND #256,D0 BEQ L279(PC) MOVE D7,-(A7) JSR F287_xxxx_(PC) ADDQ.L #2,A7 MOVE D5,D0 BEQ L280(PC) MOVE.L A3,-(A7) JSR F290_xxxx_(PC) ADDQ.L #4,A7 CMPI #0,66(A3) BLT.S L282 CMPI #0,68(A3) BLT.S L282 MOVE.B 42(A3),D0 BEQ.S L281 L282: MOVE #34,-8(A6) BRA.S L283 L281: MOVE #33,-8(A6) L283: MOVE #12,-(A7) MOVE #16,-(A7) PEA G048_s_Gra(A4) MOVE -8(A6),-(A7) JSR F489_ayzz_(PC) ADDQ.L #2,A7 MOVE.L D0,-(A7) JSR F020_aAA5_(PC) ADDA #12,A7 MOVE #33,-8(A6) MOVE #1,D4 BRA.S L284 L285: MOVE D4,D0 MULS #3,D0 LEA 71(A3),A0 ADDA D0,A0 MOVE.B (A0),D0 MOVE D4,D1 MULS #3,D1 LEA 70(A3),A0 ADDA D1,A0 MOVE.B (A0),D1 AND #255,D1 AND #255,D0 CMP D1,D0 BGE.S L288 MOVE #34,-8(A6) BRA.S L287 L288: L286: ADDQ #1,D4 L284: CMPI #6,D4 BLE.S L285 L287: MOVE #12,-(A7) MOVE #16,-(A7) PEA G049_s_Gra(A4) MOVE -8(A6),-(A7) JSR F489_ayzz_(PC) ADDQ.L #2,A7 MOVE.L D0,-(A7) JSR F020_aAA5_(PC) ADDA #12,A7 OR #16384,D6 L280: L279: MOVE D6,D0 AND #8192,D0 BEQ.S L289 MOVE D5,D4 BEQ.S L294 MOVE #5,D4 BRA.S L295 L294: MOVE #1,D4 L295: BRA.S L290 L291: MOVE D4,-(A7) MOVE D7,-(A7) JSR F291_xxxx_(PC) ADDQ.L #4,A7 L292: SUBQ #1,D4 L290: CMPI #0,D4 BGE.S L291 L293: MOVE D5,D0 BEQ.S L296 OR #16384,D6 L296: L289: MOVE D6,D0 AND #512,D0 BEQ L297(PC) MOVE D5,D0 BEQ L297(PC) MOVE.L A3,-(A7) JSR F309_awzz_(PC) ADDQ.L #4,A7 MOVE D0,D4 MOVE D0,-42(A6) MOVE 272(A3),D0 CMP -42(A6),D0 BLS.S L298 MOVE #8,-8(A6) BRA.S L299 L298: MOVE 272(A3),D0 AND.L #65535,D0 ASL.L #3,D0 MOVE D4,D1 EXT.L D1 MOVE.L D1,-(A7) MOVE.L #5,D1 MOVE.L D1,-(A7) JSR _lmul(PC) MOVE.L (A7)+,D1 CMP.L D1,D0 BLE.S L300 MOVE #11,-8(A6) BRA.S L301 L300: MOVE #13,-8(A6) L301: L299: DATA SEG "s!" DATA 4C 41 53 54 20 00 CODE SEG "player" PEA s!+98(A4) MOVE -8(A6),-(A7) MOVE #132,-(A7) MOVE #104,-(A7) JSR F052_aaoz_(PC) ADDA #10,A7 MOVE 272(A3),D4 AND.L #65535,D4 DIVU #10,D4 MOVE #3,-(A7) MOVE #1,-(A7) MOVE D4,-(A7) JSR F288_xxxx_(PC) ADDQ.L #6,A7 MOVE.L D0,-(A7) PEA G353_ac_St(A4) JSR strcpy(PC) ADDQ.L #8,A7 DATA SEG "s!" DATA 2C 00 CODE SEG "player" PEA s!+104(A4) PEA G353_ac_St(A4) JSR strcat(PC) ADDQ.L #8,A7 MOVE 272(A3),D0 MOVE D4,D1 MULS #10,D1 SUB D1,D0 MOVE D0,D4 MOVE #1,-(A7) CLR -(A7) MOVE D4,-(A7) JSR F288_xxxx_(PC) ADDQ.L #6,A7 MOVE.L D0,-(A7) PEA G353_ac_St(A4) JSR strcat(PC) ADDQ.L #8,A7 DATA SEG "s!" DATA 2F 00 CODE SEG "player" PEA s!+106(A4) PEA G353_ac_St(A4) JSR strcat(PC) ADDQ.L #8,A7 MOVE.L A3,-(A7) JSR F309_awzz_(PC) ADDQ.L #4,A7 ADDQ #5,D0 AND.L #65535,D0 DIVU #10,D0 MOVE D0,D4 MOVE #3,-(A7) MOVE #1,-(A7) MOVE D4,-(A7) JSR F288_xxxx_(PC) ADDQ.L #6,A7 MOVE.L D0,-(A7) PEA G353_ac_St(A4) JSR strcat(PC) ADDQ.L #8,A7 DATA SEG "s!" DATA 20 4B 47 00 CODE SEG "player" PEA s!+108(A4) PEA G353_ac_St(A4) JSR strcat(PC) ADDQ.L #8,A7 PEA G353_ac_St(A4) MOVE -8(A6),-(A7) MOVE #132,-(A7) MOVE #148,-(A7) JSR F052_aaoz_(PC) ADDA #10,A7 OR #16384,D6 L297: MOVE.B 29(A3),D4 AND #255,D4 ADDQ #4,D4 SUB G308_i_Par(A4),D4 AND #3,D4 MOVE D6,D0 AND #1024,D0 BEQ L302(PC) MOVE G599_ui_Us(A4),D0 MOVE D4,D1 ADDQ #1,D1 CMP D1,D0 BEQ L302(PC) MOVE #160,-(A7) MOVE D7,D0 LEA G046_auc_G(A4),A0 ADDA D0,A0 MOVE.B (A0),D0 AND #255,D0 MOVE D0,-(A7) MOVE D4,D0 ASL #2,D0 ASL.L #1,D0 LEA G054_ai_Gr(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,-(A7) MOVE.L G348_pl_Bi(A4),-(A7) JSR F135_xzzz_(PC) ADDA #12,A7 MOVE #12,-(A7) MOVE #160,-(A7) MOVE #40,-(A7) CLR -(A7) MOVE.B 28(A3),D0 AND #255,D0 ADDQ #4,D0 SUB G308_i_Par(A4),D0 AND #3,D0 MULS #19,D0 MOVE D0,-(A7) MOVE D4,D0 ASL #2,D0 ASL.L #1,D0 LEA G054_ai_Gr(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,-(A7) MOVE.L G348_pl_Bi(A4),-(A7) MOVE #28,-(A7) JSR F489_ayzz_(PC) ADDQ.L #2,A7 MOVE.L D0,-(A7) JSR F132_xzzz_(PC) ADDA #22,A7 L302: MOVE D6,D0 AND #2048,D0 BEQ.S L303 MOVE D5,D0 BEQ.S L303 MOVE G333_B_Pre(A4),D0 BEQ.S L304 JSR F345_xxxx_(PC) BRA.S L305 L304: MOVE G331_B_Pre(A4),D0 BEQ.S L306 MOVE G415_B_Lea(A4),D0 BEQ.S L307 JSR F351_xxxx_(PC) L307: BRA.S L308 L306: JSR F347_xxxx_(PC) L308: L305: OR #16384,D6 L303: MOVE D6,D0 AND #-32768,D0 BEQ.S L309 MOVE #1,-(A7) MOVE D7,-(A7) JSR F291_xxxx_(PC) ADDQ.L #4,A7 MOVE D7,-(A7) JSR F386_ezzz_(PC) ADDQ.L #2,A7 MOVE D5,D0 BEQ.S L310 OR #16384,D6 L310: L309: MOVE D6,D0 AND #16384,D0 BEQ.S L311 CLR -(A7) JSR F097_lzzz_(PC) ADDQ.L #2,A7 L311: L15T292_042: ANDI #127,48(A3) JSR F078_xzzz_(PC) L258: MOVEM.L (A7)+,D4-D7/A2-A3 UNLK A6 RTS L$257: .EQU #-42 F293_ahzz_:/* global */ LINK A6,L$312 MOVE D7,-(A7) MOVE #37,-(A7) JSR R056_aaal_(PC) ADDQ.L #2,A7 CLR D7 BRA.S L314 L315: MOVE D7,-(A7) JSR F292_arzz_(PC) ADDQ.L #2,A7 L316: ADDQ #1,D7 L314: MOVE D7,D0 CMP G305_ui_Pa(A4),D0 BCS.S L315 L317: L313: MOVE (A7)+,D7 UNLK A6 RTS L$312: .EQU #0 F294_aozz_:/* global */ LINK A6,L$318 MOVEM.L A3-A2/D7-D6,-(A7) MOVE 8(A6),D0 MULS #800,D0 LEA G407_s_Par(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,A3 MOVE 10(A6),D7 ASL.L #1,D7 LEA 212(A3),A0 ADDA D7,A0 MOVE (A0),D7 MOVE D7,D0 AND #15360,D0 LSR #2,D0 LSR #8,D0 CMPI #5,D0 BEQ.S L320 MOVE #0,D0 BRA L319(PC) L320: MOVE D7,-(A7) JSR F158_ayzz_(PC) ADDQ.L #2,A7 MOVE.L D0,A2 MOVE.B 1(A2),D0 AND #255,D0 CMP #16,D0 BLT.S L321 MOVE.B 1(A2),D0 AND #255,D0 CMP #31,D0 BGT.S L321 MOVE #10,D6 BRA.S L322 L321: MOVE.B 1(A2),D0 AND #255,D0 CMP #32,D0 BLT.S L323 MOVE.B 1(A2),D0 AND #255,D0 CMP #47,D0 BGT.S L323 MOVE #11,D6 BRA.S L324 L323: MOVE #0,D0 BRA.S L319 L324: L322: MOVE 12(A6),D7 ASL.L #1,D7 LEA 212(A3),A0 ADDA D7,A0 MOVE (A0),D7 MOVE D7,-(A7) JSR F158_ayzz_(PC) ADDQ.L #2,A7 MOVE.L D0,A2 MOVE D7,D0 AND #15360,D0 LSR #2,D0 LSR #8,D0 CMPI #5,D0 SEQ D0 TST.B D0 BEQ.S L325 MOVE.B 1(A2),D0 AND #255,D0 CMP D6,D0 SEQ D0 TST.B D0 L325: AND #1,D0 L319: MOVEM.L (A7)+,D6-D7/A2-A3 UNLK A6 RTS L$318: .EQU #0 F295_xxxx_:/* global */ LINK A6,L$326 MOVEM.L D7-D5,-(A7) MOVE 8(A6),D7 MOVE D7,-(A7) JSR F039_aaaL_(PC) ADDQ.L #2,A7 MOVE D0,D6 CMPI #32,D6 BGE.S L330 CMPI #0,D6 BGE.S L329 L330: CMPI #148,D6 BLT.S L331 CMPI #163,D6 BLE.S L329 L331: CMPI #195,D6 BNE.S L328 L329: MOVE 10(A6),-(A7) JSR F033_aaaz_(PC) ADDQ.L #2,A7 MOVE D0,D5 MOVE D5,D0 CMP D6,D0 BEQ.S L332 CMPI #8,D7 BGE.S L333 MOVE G420_B_Mou(A4),D0 BNE.S L333 MOVE #1,G420_B_Mou(A4) JSR F077_aA39_(PC) L333: MOVE D5,-(A7) MOVE D7,-(A7) JSR F038_AA07_(PC) ADDQ.L #4,A7 MOVE #1,D0 BRA.S L327 L332: L328: MOVE #0,D0 L327: MOVEM.L (A7)+,D5-D7 UNLK A6 RTS L$326: .EQU #0 F296_aizz_:/* global */ LINK A6,L$334 MOVEM.L A3-A2/D7-D4,-(A7) MOVE G423_i_Inv(A4),D6 MOVE G299_ui_Ca(A4),D0 BEQ.S L336 MOVE D6,D0 BNE.S L336 BRA L335(PC) L336: CLR G420_B_Mou(A4) MOVE G413_i_Lea(A4),D0 MOVE D0,D5 CMPI #32,D0 BGE.S L339 MOVE G413_i_Lea(A4),D0 MOVE D0,D5 CMPI #0,D0 BGE.S L338 L339: MOVE G413_i_Lea(A4),D0 MOVE D0,D5 CMPI #148,D0 BLT.S L340 MOVE G413_i_Lea(A4),D0 MOVE D0,D5 CMPI #163,D0 BLE.S L338 L340: MOVE G413_i_Lea(A4),D0 MOVE D0,D5 CMPI #195,D0 BNE.S L337 L338: MOVE G414_T_Lea(A4),-(A7) JSR F033_aaaz_(PC) ADDQ.L #2,A7 MOVE D0,-2(A6) MOVE -2(A6),D0 CMP D5,D0 BEQ.S L341 MOVE #1,G420_B_Mou(A4) JSR F077_aA39_(PC) MOVE.L G412_puc_B(A4),-(A7) MOVE -2(A6),-(A7) JSR F036_aA19_(PC) ADDQ.L #6,A7 MOVE.L G412_puc_B(A4),-(A7) JSR F068_aagz_(PC) ADDQ.L #4,A7 MOVE -2(A6),G413_i_Lea(A4) MOVE G414_T_Lea(A4),-(A7) JSR F034_aaau_(PC) ADDQ.L #2,A7 L341: L337: CLR D7 BRA.S L342 L343: MOVE D7,D4 LSR #1,D4 MOVE D6,D0 MOVE D4,D1 ADDQ #1,D1 CMP D1,D0 BNE.S L346 BRA.S L344 L346: MOVE D7,D0 AND #1,D0 MOVE D4,D1 MULS #800,D1 LEA G407_s_Par+212(A4),A0 ADDA D1,A0 ASL.L #1,D0 LEA (A0),A0 ADDA D0,A0 MOVE (A0),-(A7) MOVE D7,-(A7) JSR F295_xxxx_(PC) ADDQ.L #4,A7 TST D0 BEQ.S L347 MOVE D7,D0 AND #1,D0 CMPI #1,D0 BNE.S L347 MOVE D4,-(A7) JSR F386_ezzz_(PC) ADDQ.L #2,A7 L347: L344: ADDQ #1,D7 L342: MOVE D7,D0 MOVE G305_ui_Pa(A4),D1 ASL #1,D1 CMP D1,D0 BCS.S L343 L345: MOVE D6,D0 BEQ L348(PC) MOVE D6,D0 MULS #800,D0 LEA G407_s_Par+-800(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,A2 MOVE #0,D0 MOVE D0,D7 ASL.L #1,D0 LEA 212(A2),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,A3 CLR D5 BRA.S L349 L350: MOVE (A3),-(A7) MOVE D7,D0 ADDQ #8,D0 MOVE D0,-(A7) JSR F295_xxxx_(PC) ADDQ.L #4,A7 MOVE D0,-4(A6) OR D0,D5 MOVE -4(A6),D0 BEQ.S L353 CMPI #1,D7 BNE.S L353 MOVE D6,D0 SUBQ #1,D0 MOVE D0,-(A7) JSR F386_ezzz_(PC) ADDQ.L #2,A7 L353: L351: MOVE D7,D0 ADDQ #1,D7 MOVE.L A3,D0 ADDQ.L #2,A3 L349: CMPI #30,D7 BCS.S L350 L352: CMPI #4,G424_i_Pan(A4) BNE.S L354 LEA G425_aT_Ch(A4),A0 MOVE.L A0,A3 CLR D7 BRA.S L355 L356: MOVE (A3),-(A7) MOVE D7,D0 ADD #38,D0 MOVE D0,-(A7) JSR F295_xxxx_(PC) ADDQ.L #4,A7 OR D0,D5 L357: MOVE D7,D0 ADDQ #1,D7 MOVE.L A3,D0 ADDQ.L #2,A3 L355: CMPI #8,D7 BCS.S L356 L358: L354: MOVE D5,D0 BEQ.S L359 ORI #16384,48(A2) MOVE D6,D0 SUBQ #1,D0 MOVE D0,-(A7) JSR F292_arzz_(PC) ADDQ.L #2,A7 L359: L348: MOVE G420_B_Mou(A4),D0 BEQ.S L360 JSR F078_xzzz_(PC) L360: L335: MOVEM.L (A7)+,D4-D7/A2-A3 UNLK A6 RTS L$334: .EQU #-4 F297_atzz_:/* global */ LINK A6,L$361 CMPI #-1,8(A6) BNE.S L363 BRA L362(PC) L363: CLR G415_B_Lea(A4) MOVE.L G412_puc_B(A4),-(A7) MOVE 8(A6),D0 MOVE D0,G414_T_Lea(A4) MOVE D0,-(A7) JSR F033_aaaz_(PC) ADDQ.L #2,A7 MOVE D0,G413_i_Lea(A4) MOVE D0,-(A7) JSR F036_aA19_(PC) ADDQ.L #6,A7 JSR F077_aA39_(PC) MOVE 8(A6),-(A7) JSR F034_aaau_(PC) ADDQ.L #2,A7 MOVE 10(A6),D0 BEQ.S L364 MOVE #1,G325_B_Set(A4) BRA.S L365 L364: MOVE.L G412_puc_B(A4),-(A7) JSR F068_aagz_(PC) ADDQ.L #4,A7 L365: JSR F078_xzzz_(PC) CMPI #-1,G411_i_Lea(A4) BEQ.S L366 MOVE 8(A6),-(A7) JSR F140_yzzz_(PC) ADDQ.L #2,A7 MOVE.L D0,D1 MOVE G411_i_Lea(A4),D0 MULS #800,D0 LEA G407_s_Par+272(A4),A0 ADDA D0,A0 MOVE (A0),D0 ADD D1,D0 MOVE D0,(A0) MOVE G411_i_Lea(A4),D0 MULS #800,D0 LEA G407_s_Par+48(A4),A0 ADDA D0,A0 ORI #512,(A0) MOVE G411_i_Lea(A4),-(A7) JSR F292_arzz_(PC) ADDQ.L #2,A7 L366: L362: UNLK A6 RTS L$361: .EQU #0 F298_aqzz_:/* global */ LINK A6,L$367 MOVE D7,-(A7) MOVE #1,G415_B_Lea(A4) MOVE G414_T_Lea(A4),D0 MOVE D0,D7 CMPI #-1,D0 BEQ.S L369 MOVE #-1,G414_T_Lea(A4) MOVE #-1,G413_i_Lea(A4) JSR F077_aA39_(PC) JSR F035_aaaw_(PC) JSR F069_aaaL_(PC) JSR F078_xzzz_(PC) CMPI #-1,G411_i_Lea(A4) BEQ.S L370 MOVE D7,-(A7) JSR F140_yzzz_(PC) ADDQ.L #2,A7 MOVE.L D0,D1 MOVE G411_i_Lea(A4),D0 MULS #800,D0 LEA G407_s_Par+272(A4),A0 ADDA D0,A0 MOVE (A0),D0 SUB D1,D0 MOVE D0,(A0) MOVE G411_i_Lea(A4),D0 MULS #800,D0 LEA G407_s_Par+48(A4),A0 ADDA D0,A0 ORI #512,(A0) MOVE G411_i_Lea(A4),-(A7) JSR F292_arzz_(PC) ADDQ.L #2,A7 L370: L369: MOVE D7,D0 L368: MOVE (A7)+,D7 UNLK A6 RTS L$367: .EQU #0 F299_xxxx_:/* global */ LINK A6,L$371 MOVEM.L A3/D7-D4,-(A7) MOVE.L 8(A6),A3 MOVE 12(A6),D7 MOVE 14(A6),D6 CLR D4 MOVE 18(A6),D0 AND #15360,D0 LSR #2,D0 LSR #8,D0 MOVE D0,D5 CMPI #5,D0 BEQ.S L374 CMPI #6,D5 BNE.S L373 L374: CMPI #0,D7 BCS.S L373 CMPI #12,D7 BHI.S L373 MOVE 18(A6),-(A7) JSR F156_afzz_(PC) ADDQ.L #2,A7 MOVE.L D0,-4(A6) CMPI #5,D5 BNE.S L377 MOVE.L -4(A6),A0 MOVE 2(A0),D0 AND #256,D0 LSR #8,D0 BNE.S L376 L377: CMPI #6,D5 BNE.S L375 MOVE.L -4(A6),D0 MOVE.L D0,A0 MOVE 2(A0),D0 AND #256,D0 LSR #8,D0 BEQ.S L375 L376: CLR D5 MOVE #-3,D4 BRA L22T299_044(PC) L375: L373: CMPI #137,D6 BNE.S L378 CLR D5 MOVE #10,D4 BRA L379(PC) L378: CMPI #1,D7 BNE L380(PC) CMPI #45,D6 BNE.S L381 MOVE #1,D5 MOVE #5,D4 BRA L382(PC) L381: MOVE #8,D5 CMPI #20,D6 BCS.S L383 CMPI #22,D6 BHI.S L383 MOVE #4,D4 BRA L384(PC) L383: CMPI #58,D6 BCS L385(PC) CMPI #66,D6 BHI L385(PC) MOVE D6,D0 L386: CMP #58,D0 BEQ.S L387 BRA.S L389 L387: MOVE #2,D4 BRA L388(PC) BRA.S L390 L389: CMP #59,D0 BEQ.S L390 BRA.S L391 L390: MOVE #1,D4 BRA.S L388 BRA.S L392 L391: CMP #60,D0 BEQ.S L392 BRA.S L393 L392: MOVE #6,D4 BRA.S L388 BRA.S L394 L393: CMP #61,D0 BEQ.S L394 BRA.S L395 L394: MOVE #4,D4 BRA.S L388 BRA.S L396 L395: CMP #62,D0 BEQ.S L396 BRA.S L397 L396: MOVE #10,D4 BRA.S L388 BRA.S L398 L397: CMP #63,D0 BEQ.S L398 BRA.S L399 L398: MOVE #8,D4 BRA.S L388 BRA.S L400 L399: CMP #64,D0 BEQ.S L400 BRA.S L401 L400: MOVE #16,D4 BRA.S L388 BRA.S L402 L401: CMP #65,D0 BEQ.S L402 BRA.S L403 L402: MOVE #7,D4 BRA.S L388 BRA.S L404 L403: CMP #66,D0 BEQ.S L404 BRA.S L405 L404: MOVE #5,D4 L405: L406: L388: BRA.S L407 L385: MOVE D6,D0 L408: CMP #38,D0 BEQ.S L409 BRA.S L411 L409: MOVE #1,D4 BRA.S L410 BRA.S L412 L411: CMP #41,D0 BEQ.S L412 BRA.S L413 L412: MOVE #2,D4 BRA.S L410 BRA.S L414 L413: CMP #40,D0 BEQ.S L414 BRA.S L415 L414: MOVE #4,D4 L415: L416: L410: L407: L384: L382: BRA L417(PC) L380: CMPI #4,D7 BNE.S L418 CMPI #142,D6 BNE.S L419 MOVE #1,D5 MOVE #10,D4 L419: BRA L420(PC) L418: CMPI #2,D7 BNE.S L421 CMPI #104,D6 BNE.S L422 MOVE #3,D5 MOVE #10,D4 BRA.S L423 L422: CMPI #140,D6 BNE.S L424 MOVE #2,D5 MOVE #10,D4 L424: L423: BRA.S L425 L421: CMPI #3,D7 BNE.S L426 CMPI #141,D6 BNE.S L427 MOVE #6,D5 MOVE #12,D4 BRA.S L428 L427: CMPI #81,D6 BNE.S L429 MOVE #2,D5 MOVE #8,D4 L429: L428: BRA.S L430 L426: CMPI #10,D7 BNE.S L431 CMPI #10,D6 BCS.S L432 CMPI #11,D6 BHI.S L432 MOVE #5,D5 MOVE #15,D4 BRA.S L433 L432: CMPI #81,D6 BNE.S L434 MOVE #2,D5 MOVE #8,D4 BRA.S L435 L434: CMPI #122,D6 BNE.S L436 MOVE #8,D5 MOVE #3,D4 L436: L435: L433: L431: L430: L425: L420: L417: L379: L22T299_044: MOVE D4,D0 BEQ.S L437 MOVE D4,D0 MULS 16(A6),D0 MOVE D0,D4 CMPI #8,D5 BNE.S L438 MOVE D4,D0 ADD D0,62(A3) BRA.S L439 L438: CMPI #7,D5 BGE.S L440 CLR D7 BRA.S L441 L442: MOVE D5,D0 MULS #3,D0 LEA 70(A3),A0 ADD.L A0,D0 MOVE.L D0,-14(A6) MOVE D7,D0 ADDQ #1,D7 MOVE.L -14(A6),A0 ADDA D0,A0 MOVE.B (A0),D0 AND #255,D0 ADD D4,D0 MOVE.B D0,(A0) L441: CMPI #2,D7 BLS.S L442 L443: L440: L439: ORI #2304,48(A3) L437: L372: MOVEM.L (A7)+,D4-D7/A3 UNLK A6 RTS L$371: .EQU #-14 F300_aozz_:/* global */ LINK A6,L$444 MOVEM.L A3-A2/D7-D5,-(A7) MOVE 10(A6),D7 MOVE 8(A6),D0 MULS #800,D0 LEA G407_s_Par(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,A3 CMPI #30,D7 BCS.S L446 MOVE D7,D6 ASL.L #1,D6 LEA G425_aT_Ch+-60(A4),A0 ADDA D6,A0 MOVE (A0),D6 MOVE D7,D0 ASL.L #1,D0 LEA G425_aT_Ch+-60(A4),A0 ADDA D0,A0 MOVE #-1,(A0) BRA.S L447 L446: MOVE D7,D6 ASL.L #1,D6 LEA 212(A3),A0 ADDA D6,A0 MOVE (A0),D6 MOVE D7,D0 ASL.L #1,D0 LEA 212(A3),A0 ADDA D0,A0 MOVE #-1,(A0) L447: CMPI #-1,D6 BNE.S L448 MOVE #-1,D0 BRA L445(PC) L448: MOVE 8(A6),D0 ADDQ #1,D0 MOVE G423_i_Inv(A4),D1 CMP D1,D0 SEQ D0 AND #1,D0 MOVE D0,-2(A6) MOVE D6,-(A7) JSR F033_aaaz_(PC) ADDQ.L #2,A7 MOVE D0,D5 MOVE D6,-(A7) MOVE #-1,-(A7) MOVE D5,-(A7) MOVE D7,-(A7) MOVE.L A3,-(A7) JSR F299_xxxx_(PC) ADDA #12,A7 MOVE D6,-(A7) JSR F156_afzz_(PC) ADDQ.L #2,A7 MOVE.L D0,A2 CMPI #10,D7 BNE.S L449 CMPI #12,D5 BLT.S L450 CMPI #13,D5 BGT.S L450 MOVE #0,D0 MOVE.L A2,D1 MOVE.L D1,A0 AND #3,D0 MOVE D0,D3 ASL #6,D3 ASL #8,D3 ANDI #16383,2(A0) OR D3,2(A0) MOVE G039_ai_Gr+4(A4),D0 SUB D0,G407_s_Par+3200(A4) JSR F337_akzz_(PC) BRA.S L451 L450: CMPI #10,D5 BLT.S L452 CMPI #11,D5 BGT.S L452 MOVE #0,D0 MOVE.L A2,D1 MOVE.L D1,A0 AND #3,D0 MOVE D0,D3 ASL #6,D3 ASL #8,D3 ANDI #16383,2(A0) OR D3,2(A0) L452: L451: L449: MOVE D7,-(A7) MOVE 8(A6),-(A7) JSR F291_xxxx_(PC) ADDQ.L #4,A7 MOVE -2(A6),D0 BEQ.S L453 ORI #16384,48(A3) L453: CMPI #2,D7 BCC L454(PC) CMPI #1,D7 BNE.S L455 ORI #-32768,48(A3) MOVE G506_i_Act(A4),D0 MOVE 8(A6),D1 ADDQ #1,D1 CMP D1,D0 BNE.S L456 JSR F388_rzzz_(PC) L456: CMPI #30,D5 BLT.S L457 CMPI #31,D5 BGT.S L457 MOVE #1,D0 MOVE.L A2,D1 MOVE.L D1,A0 AND #63,D0 MOVE D0,D3 ASL #2,D3 ASL #8,D3 ANDI #1023,2(A0) OR D3,2(A0) JSR F296_aizz_(PC) L457: L455: CMPI #4,D5 BLT.S L458 CMPI #7,D5 BGT.S L458 MOVE #0,D0 AND #1,D0 MOVE D0,D3 ASL #7,D3 ASL #8,D3 ANDI #32767,2(A2) OR D3,2(A2) JSR F337_akzz_(PC) JSR F296_aizz_(PC) L458: MOVE -2(A6),D0 BEQ.S L459 CMPI #1,D7 BNE.S L459 CMPI #144,D5 BNE.S L460 JSR F334_akzz_(PC) ORI #2048,48(A3) BRA.S L461 L460: CMPI #30,D5 BLT.S L462 CMPI #31,D5 BGT.S L462 ORI #2048,48(A3) L462: L461: L459: L454: MOVE D6,-(A7) JSR F140_yzzz_(PC) ADDQ.L #2,A7 SUB D0,272(A3) ORI #512,48(A3) MOVE D6,D0 L445: MOVEM.L (A7)+,D5-D7/A2-A3 UNLK A6 RTS L$444: .EQU #-2 F301_apzz_:/* global */ LINK A6,L$463 MOVEM.L A3-A2/D7-D4,-(A7) MOVE 8(A6),D7 MOVE 10(A6),D6 MOVE 12(A6),D5 CMPI #-1,D6 BNE.S L465 BRA L464(PC) L465: MOVE D7,D0 MULS #800,D0 LEA G407_s_Par(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,A3 CMPI #30,D5 BCS.S L466 MOVE D5,D0 ASL.L #1,D0 LEA G425_aT_Ch+-60(A4),A0 ADDA D0,A0 MOVE D6,(A0) BRA.S L467 L466: MOVE D5,D0 ASL.L #1,D0 LEA 212(A3),A0 ADDA D0,A0 MOVE D6,(A0) L467: MOVE D6,-(A7) JSR F140_yzzz_(PC) ADDQ.L #2,A7 ADD D0,272(A3) ORI #512,48(A3) MOVE D6,-(A7) JSR F033_aaaz_(PC) ADDQ.L #2,A7 MOVE D0,D4 MOVE D7,D0 ADDQ #1,D0 MOVE G423_i_Inv(A4),D1 CMP D1,D0 SEQ D0 AND #1,D0 MOVE D0,-2(A6) MOVE D6,-(A7) MOVE #1,-(A7) MOVE D4,-(A7) MOVE D5,-(A7) MOVE.L A3,-(A7) JSR F299_xxxx_(PC) ADDA #12,A7 MOVE D6,-(A7) JSR F156_afzz_(PC) ADDQ.L #2,A7 MOVE.L D0,A2 CMPI #2,D5 BCC L468(PC) CMPI #1,D5 BNE.S L469 ORI #-32768,48(A3) MOVE G506_i_Act(A4),D0 MOVE D7,D1 ADDQ #1,D1 CMP D1,D0 BNE.S L470 JSR F388_rzzz_(PC) L470: CMPI #30,D4 BLT.S L471 CMPI #31,D4 BGT.S L471 MOVE #0,D0 MOVE.L A2,D1 MOVE.L D1,A0 AND #63,D0 MOVE D0,D3 ASL #2,D3 ASL #8,D3 ANDI #1023,2(A0) OR D3,2(A0) JSR F296_aizz_(PC) L471: L469: CMPI #4,D4 BNE.S L472 MOVE #1,D0 AND #1,D0 MOVE D0,D3 ASL #7,D3 ASL #8,D3 ANDI #32767,2(A2) OR D3,2(A2) JSR F337_akzz_(PC) JSR F296_aizz_(PC) BRA.S L473 L472: MOVE -2(A6),D0 BEQ.S L474 CMPI #1,D5 BNE.S L474 CMPI #144,D4 BEQ.S L475 CMPI #30,D4 BLT.S L474 CMPI #31,D4 BGT.S L474 L475: ORI #2048,48(A3) L474: L473: BRA.S L476 L468: CMPI #10,D5 BNE.S L477 CMPI #12,D4 BLT.S L478 CMPI #13,D4 BGT.S L478 MOVE #1,D0 MOVE.L A2,D1 MOVE.L D1,A0 AND #3,D0 MOVE D0,D3 ASL #6,D3 ASL #8,D3 ANDI #16383,2(A0) OR D3,2(A0) MOVE G039_ai_Gr+4(A4),D0 ADD D0,G407_s_Par+3200(A4) JSR F337_akzz_(PC) ADDQ #1,D4 BRA.S L479 L478: CMPI #10,D4 BLT.S L480 CMPI #11,D4 BGT.S L480 MOVE #1,D0 MOVE.L A2,D1 MOVE.L D1,A0 AND #3,D0 MOVE D0,D3 ASL #6,D3 ASL #8,D3 ANDI #16383,2(A0) OR D3,2(A0) ADDQ #1,D4 L480: L479: L477: L476: MOVE D5,-(A7) MOVE D7,-(A7) JSR F291_xxxx_(PC) ADDQ.L #4,A7 MOVE -2(A6),D0 BEQ.S L481 ORI #16384,48(A3) L481: L464: MOVEM.L (A7)+,D4-D7/A2-A3 UNLK A6 RTS L$463: .EQU #-2 F302_mzzz_:/* global */ LINK A6,L$482 MOVEM.L D7-D4,-(A7) CMPI #8,8(A6) BCC.S L484 MOVE G299_ui_Ca(A4),D0 BEQ.S L485 BRA L483(PC) L485: MOVE 8(A6),D7 LSR #1,D7 MOVE D7,D0 CMP G305_ui_Pa(A4),D0 BCC.S L487 MOVE D7,D0 ADDQ #1,D0 MOVE G423_i_Inv(A4),D1 CMP D1,D0 BEQ.S L487 MOVE D7,D0 MULS #800,D0 LEA G407_s_Par+52(A4),A0 ADDA D0,A0 MOVE (A0),D0 BNE.S L486 L487: BRA L483(PC) L486: MOVE 8(A6),D6 AND #1,D6 BRA.S L488 L484: MOVE G423_i_Inv(A4),D7 SUBQ #1,D7 MOVE 8(A6),D6 SUBQ #8,D6 L488: MOVE G414_T_Lea(A4),D5 CMPI #30,D6 BCS.S L489 MOVE D6,D4 ASL.L #1,D4 LEA G425_aT_Ch+-60(A4),A0 ADDA D4,A0 MOVE (A0),D4 BRA.S L490 L489: MOVE D6,D4 MOVE D7,D1 MULS #800,D1 LEA G407_s_Par+212(A4),A0 ADDA D1,A0 ASL.L #1,D4 LEA (A0),A0 ADDA D4,A0 MOVE (A0),D4 L490: CMPI #-1,D4 BNE.S L491 CMPI #-1,D5 BNE.S L491 BRA.S L483 L491: CMPI #-1,D5 BEQ.S L492 MOVE D5,-(A7) JSR F141_anzz_(PC) ADDQ.L #2,A7 MULS #6,D0 LEA G237_as_Gr+4(A4),A0 ADDA D0,A0 MOVE (A0),D0 MOVE D6,D1 ASL.L #1,D1 LEA G038_ai_Gr(A4),A0 ADDA D1,A0 AND (A0),D0 BNE.S L492 BRA.S L483 L492: JSR F077_aA39_(PC) CMPI #-1,D5 BEQ.S L493 JSR F298_aqzz_(PC) L493: CMPI #-1,D4 BEQ.S L494 MOVE D6,-(A7) MOVE D7,-(A7) JSR F300_aozz_(PC) ADDQ.L #4,A7 CLR -(A7) MOVE D4,-(A7) JSR F297_atzz_(PC) ADDQ.L #4,A7 L494: CMPI #-1,D5 BEQ.S L495 MOVE D6,-(A7) MOVE D5,-(A7) MOVE D7,-(A7) JSR F301_apzz_(PC) ADDQ.L #6,A7 L495: MOVE D7,-(A7) JSR F292_arzz_(PC) ADDQ.L #2,A7 JSR F078_xzzz_(PC) L483: MOVEM.L (A7)+,D4-D7 UNLK A6 RTS L$482: .EQU #0 F303_AA09_:/* global */ LINK A6,L$496 MOVEM.L A3-A2/D7-D4,-(A7) MOVE G300_B_Par(A4),D0 BEQ.S L498 MOVE #1,D0 BRA L497(PC) L498: MOVE 10(A6),D0 AND #-32768,D0 MOVE D0,-2(A6) MOVE 10(A6),D0 AND #16384,D0 MOVE D0,-4(A6) ANDI #16383,10(A6) MOVE 8(A6),D0 MULS #800,D0 LEA G407_s_Par(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,A2 MOVE 10(A6),D0 MULS #6,D0 LEA 92(A2),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,A3 MOVE.L 2(A3),D7 MOVE -2(A6),D0 BNE.S L499 MOVE (A3),D0 EXT.L D0 ADD.L D0,D7 L499: CMPI #3,10(A6) BLS.S L500 MOVE 10(A6),D0 SUBQ #4,D0 LSR #2,D0 MULS #6,D0 LEA 92(A2),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,A3 ADD.L 2(A3),D7 MOVE -2(A6),D0 BNE.S L501 MOVE (A3),D0 EXT.L D0 ADD.L D0,D7 L501: MOVE.L D7,D0 ASR.L #1,D0 MOVE.L D0,D7 L500: MOVE #1,D6 BRA.S L502 L503: MOVE.L D7,D0 ASR.L #1,D0 MOVE.L D0,D7 ADDQ #1,D6 L502: CMPI.L #500,D7 BGE.S L503 L504: MOVE -4(A6),D0 BNE L505(PC) MOVE 214(A2),-(A7) JSR F033_aaaz_(PC) ADDQ.L #2,A7 MOVE D0,D4 CMPI #27,D0 BNE.S L506 ADDQ #1,D6 BRA.S L507 L506: CMPI #28,D4 BNE.S L508 ADDQ #2,D6 L508: L507: MOVE 232(A2),-(A7) JSR F033_aaaz_(PC) ADDQ.L #2,A7 MOVE D0,D5 MOVE 10(A6),D0 L509: CMP #3,D0 BEQ.S L510 BRA.S L512 L510: CMPI #124,D5 BNE.S L514 ADDQ #1,D6 L514: BRA.S L511 BRA.S L513 L512: CMP #15,D0 BEQ.S L513 BRA.S L515 L513: CMPI #121,D5 BNE.S L517 ADDQ #1,D6 L517: BRA.S L511 BRA.S L516 L515: CMP #13,D0 BEQ.S L516 BRA.S L518 L516: CMPI #120,D5 BEQ.S L521 CMPI #66,D4 BNE.S L520 L521: ADDQ #1,D6 L520: BRA.S L511 BRA.S L519 L518: CMP #14,D0 BEQ.S L519 BRA.S L522 L519: CMPI #122,D5 BNE.S L524 ADDQ #1,D6 L524: L522: L523: L511: L505: MOVE D6,D0 L497: MOVEM.L (A7)+,D4-D7/A2-A3 UNLK A6 RTS L$496: .EQU #-4 F304_apzz_:/* global */ LINK A6,L$525 MOVEM.L A3-A2/D7-D4,-(A7) MOVE 12(A6),D7 CMPI #4,10(A6) BCS.S L527 CMPI #11,10(A6) BHI.S L527 MOVE.L G361_l_Las(A4),D0 MOVE.L G313_ul_Ga(A4),D1 SUB.L #150,D1 CMP.L D1,D0 BGE.S L527 MOVE D7,D0 LSR #1,D0 MOVE D0,D7 L527: MOVE D7,D0 BEQ L528(PC) MOVE.L G269_ps_Cu(A4),A0 MOVE 12(A0),D6 AND #-4096,D6 LSR #4,D6 LSR #8,D6 BEQ.S L529 MOVE D7,D0 MULU D6,D0 MOVE D0,D7 L529: MOVE 8(A6),D0 MULS #800,D0 LEA G407_s_Par(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,A2 CMPI #4,10(A6) BCS.S L530 MOVE 10(A6),D5 SUBQ #4,D5 LSR #2,D5 BRA.S L531 L530: MOVE 10(A6),D5 L531: MOVE.L 2(A3),D4 MOVE D5,D0 OR #-16384,D0 MOVE D0,-(A7) MOVE 8(A6),-(A7) JSR F303_AA09_(PC) ADDQ.L #4,A7 MOVE D0,D6 CMPI #4,10(A6) BCS.S L532 MOVE.L G361_l_Las(A4),D0 MOVE.L G313_ul_Ga(A4),D1 SUB.L #25,D1 CMP.L D1,D0 BLE.S L532 MOVE D7,D0 ASL #1,D0 MOVE D0,D7 L532: MOVE 10(A6),D0 MULS #6,D0 LEA 92(A2),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,A3 MOVE D7,D0 AND.L #65535,D0 ADD.L D0,2(A3) CMPI #32000,(A3) BGE.S L533 MOVE #100,-(A7) MOVE D7,D0 LSR #3,D0 MOVE D0,-(A7) MOVE #1,-(A7) JSR F026_a003_(PC) ADDQ.L #6,A7 ADD D0,(A3) L533: MOVE D5,D0 MULS #6,D0 LEA 92(A2),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,A3 CMPI #4,10(A6) BCS.S L534 MOVE D7,D0 AND.L #65535,D0 ADD.L D0,2(A3) L534: MOVE D5,D0 OR #-16384,D0 MOVE D0,-(A7) MOVE 8(A6),-(A7) JSR F303_AA09_(PC) ADDQ.L #4,A7 MOVE D0,D7 MOVE D7,D0 CMP D6,D0 BLS L535(PC) MOVE D7,-6(A6) JSR F028_a000_(PC) MOVE D0,-2(A6) JSR F028_a000_(PC) MOVE.L D0,D1 MOVE #1,D0 ADD D1,D0 MOVE D0,-4(A6) JSR F028_a000_(PC) MOVE D0,D6 CMPI #2,D5 BEQ.S L536 AND D7,D6 L536: MOVE D6,D0 ADD.B D0,82(A2) MOVE 58(A2),D6 JSR F028_a000_(PC) MOVE D7,D1 NOT D1 AND D1,D0 ADD.B D0,88(A2) MOVE D5,D0 L537: CMP #0,D0 BEQ.S L538 BRA.S L540 L538: MOVE D6,D0 LSR #4,D0 MOVE D0,D6 MOVE D7,D0 MULU #3,D0 MOVE D0,D7 MOVE -4(A6),D0 ADD.B D0,73(A2) MOVE -2(A6),D0 ADD.B D0,76(A2) BRA L539(PC) BRA.S L541 L540: CMP #1,D0 BEQ.S L541 BRA.S L542 L541: MOVE D6,D0 AND.L #65535,D0 DIVU #21,D0 MOVE D0,D6 MOVE D7,D0 ASL #1,D0 MOVE D0,D7 MOVE -2(A6),D0 ADD.B D0,73(A2) MOVE -4(A6),D0 ADD.B D0,76(A2) BRA L539(PC) BRA.S L543 L542: CMP #3,D0 BEQ.S L543 BRA.S L544 L543: MOVE D6,D0 LSR #5,D0 MOVE D0,D6 MOVE D7,D0 MOVE D7,D1 LSR #1,D1 ADD D1,D0 ADD D0,62(A2) MOVE -4(A6),D0 ADD.B D0,79(A2) BRA.S L27T304_016 BRA.S L545 L544: CMP #2,D0 BEQ.S L545 BRA.S L546 L545: MOVE D6,D0 AND.L #65535,D0 DIVU #25,D0 MOVE D0,D6 MOVE D7,D0 ADD D0,62(A2) MOVE D7,D0 ADDQ #1,D0 LSR #1,D0 ADD D0,D7 MOVE -2(A6),D0 ADD.B D0,79(A2) L27T304_016: MOVE -6(A6),D0 SUBQ #1,D0 MOVE D0,-(A7) JSR F029_AA19_(PC) MOVE D0,-(A7) JSR F024_aatz_(PC) ADDQ.L #4,A7 MOVE.L D0,D1 MOVE 62(A2),D0 ADD D1,D0 MOVE D0,62(A2) CMPI #900,D0 BLE.S L548 MOVE #900,62(A2) L548: JSR F027_AA59_(PC) AND.L #65535,D0 DIVU #3,D0 SWAP D0 ADD.B D0,85(A2) L546: L547: L539: JSR F027_AA59_(PC) MOVE.L D0,D1 MOVE D7,D0 LSR #1,D0 ADDQ #1,D0 AND.L #65535,D1 DIVU D0,D1 SWAP D1 MOVE D1,-16(A6) MOVE D7,D1 ADD -16(A6),D1 MOVE 54(A2),D0 ADD D1,D0 MOVE D0,54(A2) CMP #999,D0 BLE.S L549 MOVE #999,54(A2) L549: JSR F027_AA59_(PC) MOVE.L D0,D1 MOVE D6,D0 LSR #1,D0 ADDQ #1,D0 AND.L #65535,D1 DIVU D0,D1 SWAP D1 MOVE D1,-26(A6) MOVE D6,D1 ADD -26(A6),D1 MOVE 58(A2),D0 ADD D1,D0 MOVE D0,58(A2) CMP #9999,D0 BLE.S L550 MOVE #9999,58(A2) L550: ORI #256,48(A2) MOVE 8(A6),-(A7) JSR F292_arzz_(PC) ADDQ.L #2,A7 JSR F051_AA19_(PC) LEA (A2),A0 MOVE.L A0,-(A7) MOVE 8(A6),D0 LEA G046_auc_G(A4),A0 ADDA D0,A0 MOVE.B (A0),D0 AND #255,D0 MOVE D0,D7 MOVE D0,-(A7) JSR F047_xzzz_(PC) ADDQ.L #6,A7 DATA SEG "s!" DATA 20 48 41 54 20 53 4F 45 42 45 4E 20 00 00 CODE SEG "player" PEA s!+112(A4) MOVE D7,-(A7) JSR F047_xzzz_(PC) ADDQ.L #6,A7 MOVE D5,D0 ASL.L #2,D0 LEA G417_apc_B(A4),A0 ADDA D0,A0 MOVE.L (A0),-(A7) MOVE D7,-(A7) JSR F047_xzzz_(PC) ADDQ.L #6,A7 DATA SEG "s!" DATA 20 53 54 55 46 45 20 45 52 52 45 49 43 48 54 21 00 00 CODE SEG "player" PEA s!+126(A4) MOVE D7,-(A7) JSR F047_xzzz_(PC) ADDQ.L #6,A7 L535: L528: L526: MOVEM.L (A7)+,D4-D7/A2-A3 UNLK A6 RTS L$525: .EQU #-26 F305_xxxx_:/* global */ LINK A6,L$551 MOVEM.L D7-D6,-(A7) MOVE #10,-(A7) MOVE 8(A6),-(A7) JSR F140_yzzz_(PC) ADDQ.L #2,A7 LSR #1,D0 MOVE D0,D7 MOVE D0,-(A7) MOVE #1,-(A7) JSR F026_a003_(PC) ADDQ.L #6,A7 MOVE D0,D6 BRA.S L553 L554: MOVE D7,D0 ASR #1,D0 ADD D0,D6 L553: MOVE D7,D0 SUB #10,D0 MOVE D0,D7 CMPI #0,D0 BGT.S L554 L555: MOVE D6,D0 L552: MOVEM.L (A7)+,D6-D7 UNLK A6 RTS L$551: .EQU #0 F306_xxxx_:/* global */ LINK A6,L$556 MOVEM.L A3/D7-D6,-(A7) MOVE.L 8(A6),A3 MOVE 56(A3),D0 MOVE D0,D7 MOVE 58(A3),D1 ASR #1,D1 MOVE D1,D6 CMP D1,D0 BGE.S L558 MOVE 12(A6),D0 ASR #1,D0 MOVE D0,12(A6) MOVE 12(A6),D1 EXT.L D1 MOVE D7,D2 EXT.L D2 MOVE.L D1,-(A7) MOVE.L D2,D1 MOVE.L D1,-(A7) JSR _lmul(PC) MOVE.L (A7)+,D1 MOVE.L D1,-(A7) MOVE D6,D1 EXT.L D1 MOVE.L D1,-(A7) JSR _ldiv(PC) MOVE.L (A7)+,D1 ADDQ.L #4,A7 ADD D1,D0 BRA.S L557 L558: MOVE 12(A6),D0 L557: MOVEM.L (A7)+,D6-D7/A3 UNLK A6 RTS L$556: .EQU #0 F307_fzzz_:/* global */ LINK A6,L$559 MOVE D7,-(A7) MOVE 12(A6),D0 MOVE.L 8(A6),A0 MULS #3,D0 LEA 71(A0),A0 ADDA D0,A0 MOVE.B (A0),D0 MOVE D0,-10(A6) MOVE #170,D0 MOVE.B -10(A6),D3 AND #255,D3 SUB D3,D0 MOVE D0,D7 CMPI #16,D0 BGE.S L561 MOVE 14(A6),D0 LSR #3,D0 BRA.S L560 L561: MOVE D7,-(A7) MOVE #7,-(A7) MOVE 14(A6),-(A7) JSR F030_aaaW_(PC) ADDQ.L #6,A7 L560: MOVE (A7)+,D7 UNLK A6 RTS L$559: .EQU #-10 F308_vzzz_:/* global */ LINK A6,L$562 MOVEM.L A3/D7,-(A7) MOVE 12(A6),D7 JSR F028_a000_(PC) TST D0 BEQ.S L564 JSR F027_AA59_(PC) AND.L #65535,D0 DIVU #100,D0 SWAP D0 CMP D7,D0 BLS.S L564 MOVE #1,D0 BRA.S L563 L564: MOVE.L 8(A6),A0 LEA 70(A0),A0 MOVE.L A0,A3 JSR F027_AA59_(PC) MOVE.B 1(A3),D1 AND #255,D1 AND.L #65535,D0 DIVU D1,D0 SWAP D0 CMP D7,D0 SHI D0 AND #1,D0 MOVE D0,D7 MOVE.B (A3),D0 AND #255,D0 MOVE D0,-(A7) MOVE.B 1(A3),D0 MOVE D7,D1 BEQ.S L565 MOVE #-2,D1 BRA.S L566 L565: MOVE #2,D1 L566: AND #255,D0 ADD D1,D0 MOVE D0,-(A7) MOVE.B 2(A3),D0 AND #255,D0 MOVE D0,-(A7) JSR F026_a003_(PC) ADDQ.L #6,A7 MOVE.B D0,1(A3) MOVE D7,D0 L563: MOVEM.L (A7)+,D7/A3 UNLK A6 RTS L$562: .EQU #0 F309_awzz_:/* global */ LINK A6,L$567 MOVEM.L A3/D7-D6,-(A7) MOVE.L 8(A6),A3 MOVE.B 74(A3),D7 AND #255,D7 ASL #3,D7 ADD #100,D7 MOVE D7,-(A7) MOVE.L A3,-(A7) JSR F306_xxxx_(PC) ADDQ.L #6,A7 MOVE D0,D7 MOVE 50(A3),D6 BEQ.S L569 MOVE D7,D0 MOVE D6,D1 AND #16,D1 BEQ.S L570 MOVE #2,D1 BRA.S L571 L570: MOVE #3,D1 L571: LSR D1,D0 SUB D0,D7 L569: MOVE 222(A3),-(A7) JSR F033_aaaz_(PC) ADDQ.L #2,A7 CMPI #119,D0 BNE.S L572 MOVE D7,D0 LSR #4,D0 ADD D0,D7 L572: ADD #9,D7 MOVE D7,D0 AND.L #65535,D0 DIVU #10,D0 SWAP D0 SUB D0,D7 MOVE D7,D0 L568: MOVEM.L (A7)+,D6-D7/A3 UNLK A6 RTS L$567: .EQU #0 F310_AA08_:/* global */ LINK A6,L$573 MOVEM.L A3/D7-D5,-(A7) MOVE.L 8(A6),A3 MOVE.L A3,-(A7) JSR F309_awzz_(PC) ADDQ.L #4,A7 MOVE D0,D6 MOVE 272(A3),D1 MOVE D1,D7 CMP D1,D0 BLS.S L575 MOVE #2,D5 MOVE D7,D0 AND.L #65535,D0 ASL.L #3,D0 MOVE D6,D1 AND.L #65535,D1 MOVE.L D1,-(A7) MOVE.L #5,D1 MOVE.L D1,-(A7) JSR _lmul(PC) MOVE.L (A7)+,D1 CMP.L D1,D0 BLE.S L576 ADDQ #1,D5 L576: MOVE #1,D7 BRA.S L577 L575: MOVE #4,D5 MOVE D7,D1 SUB D6,D1 ASL #2,D1 AND.L #65535,D1 DIVU D6,D1 ADD D1,D5 MOVE #2,D7 L577: MOVE 50(A3),D0 AND #32,D0 BEQ.S L578 ADD D7,D5 L578: MOVE 222(A3),-(A7) JSR F033_aaaz_(PC) ADDQ.L #2,A7 CMPI #194,D0 BNE.S L579 SUBQ #1,D5 L579: MOVE D5,D0 L574: MOVEM.L (A7)+,D5-D7/A3 UNLK A6 RTS L$573: .EQU #0 F311_wzzz_:/* global */ LINK A6,L$580 MOVEM.L A3/D7,-(A7) MOVE.L 8(A6),A3 JSR F027_AA59_(PC) AND #7,D0 MOVE.B 77(A3),D3 AND #255,D3 ADD D3,D0 MOVE D0,D7 MOVE D7,D0 ASR #1,D0 EXT.L D0 MOVE 272(A3),D1 AND.L #65535,D1 MOVE.L D0,-(A7) MOVE.L D1,D0 MOVE.L D0,-(A7) JSR _lmul(PC) MOVE.L (A7)+,D0 MOVE.L D0,-(A7) MOVE.L A3,-(A7) JSR F309_awzz_(PC) ADDQ.L #4,A7 MOVE.L D0,D1 MOVE.L (A7)+,D0 MOVE.L D0,-(A7) MOVE D1,D0 AND.L #65535,D0 MOVE.L D0,-(A7) JSR _ldiv(PC) MOVE.L (A7)+,D0 ADDQ.L #4,A7 SUB D0,D7 MOVE G300_B_Par(A4),D0 BEQ.S L582 MOVE D7,D0 ASR #1,D0 MOVE D0,D7 L582: JSR F027_AA59_(PC) MOVE.L D0,D1 AND #7,D1 MOVE #100,D0 SUB D1,D0 MOVE D0,-(A7) MOVE D7,D0 ASR #1,D0 MOVE D0,-(A7) JSR F027_AA59_(PC) MOVE.L D0,D1 AND #7,D1 MOVE #1,D0 ADD D1,D0 MOVE D0,-(A7) JSR F026_a003_(PC) ADDQ.L #6,A7 L581: MOVEM.L (A7)+,D7/A3 UNLK A6 RTS L$580: .EQU #0 F312_xzzz_:/* global */ LINK A6,L$583 MOVEM.L A3-A2/D7-D4,-(A7) MOVE 8(A6),D0 MULS #800,D0 LEA G407_s_Par(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,A3 JSR F027_AA59_(PC) AND #15,D0 MOVE.B 74(A3),D3 AND #255,D3 ADD D3,D0 MOVE D0,D7 MOVE 10(A6),D4 ASL.L #1,D4 LEA 212(A3),A0 ADDA D4,A0 MOVE (A0),D4 MOVE D4,-(A7) JSR F140_yzzz_(PC) ADDQ.L #2,A7 MOVE D0,D6 MOVE.L D0,-(A7) MOVE.L A3,-(A7) JSR F309_awzz_(PC) ADDQ.L #4,A7 MOVE.L D0,D1 MOVE.L (A7)+,D0 LSR #4,D1 MOVE D1,D5 CMP D1,D0 BHI.S L585 MOVE D6,D0 SUB #12,D0 ADD D0,D7 BRA.S L586 L585: MOVE D5,D0 MOVE D5,D1 SUB #12,D1 LSR #1,D1 ADD D1,D0 MOVE D0,-2(A6) MOVE D0,-12(A6) MOVE D6,D0 CMP -12(A6),D0 BHI.S L587 MOVE D6,D0 SUB D5,D0 LSR #1,D0 ADD D0,D7 BRA.S L588 L587: MOVE D6,D0 SUB -2(A6),D0 ASL #1,D0 SUB D0,D7 L588: L586: MOVE D4,D0 AND #15360,D0 LSR #2,D0 LSR #8,D0 CMPI #5,D0 BNE.S L589 MOVE D4,-(A7) JSR F158_ayzz_(PC) ADDQ.L #2,A7 MOVE.L D0,A2 MOVE.B 2(A2),D0 AND #255,D0 ADD D0,D7 CLR D6 MOVE.B 1(A2),D5 AND #255,D5 CMPI #0,D5 BEQ.S L591 CMPI #2,D5 BNE.S L590 L591: MOVE #4,-(A7) MOVE 8(A6),-(A7) JSR F303_AA09_(PC) ADDQ.L #4,A7 MOVE D0,D6 L590: CMPI #0,D5 BEQ.S L592 CMPI #16,D5 BCC.S L592 MOVE #10,-(A7) MOVE 8(A6),-(A7) JSR F303_AA09_(PC) ADDQ.L #4,A7 ADD D0,D6 L592: CMPI #16,D5 BCS.S L593 CMPI #112,D5 BCC.S L593 MOVE #11,-(A7) MOVE 8(A6),-(A7) JSR F303_AA09_(PC) ADDQ.L #4,A7 ADD D0,D6 L593: MOVE D6,D0 ASL #1,D0 ADD D0,D7 L589: MOVE D7,-(A7) MOVE.L A3,-(A7) JSR F306_xxxx_(PC) ADDQ.L #6,A7 MOVE D0,D7 MOVE 50(A3),D0 CMPI #0,10(A6) BNE.S L595 MOVE #1,D1 BRA.S L596 L595: MOVE #2,D1 L596: AND D1,D0 BEQ.S L594 MOVE D7,D0 ASR #1,D0 MOVE D0,D7 L594: MOVE #100,-(A7) MOVE D7,D0 ASR #1,D0 MOVE D0,-(A7) CLR -(A7) JSR F026_a003_(PC) ADDQ.L #6,A7 L584: MOVEM.L (A7)+,D4-D7/A2-A3 UNLK A6 RTS L$583: .EQU #-12 F313_xxxx_:/* global */ LINK A6,L$597 MOVEM.L A3-A2/D7-D4,-(A7) MOVE 8(A6),D0 MULS #800,D0 LEA G407_s_Par(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,A3 MOVE 10(A6),D5 AND #-32768,D5 BEQ.S L599 ANDI #32767,10(A6) L599: MOVE #0,D0 MOVE D0,D6 MOVE #0,D0 MOVE D0,D7 BRA L600(PC) L601: MOVE D7,D0 ASL.L #1,D0 LEA 212(A3),A0 ADDA D0,A0 MOVE (A0),D0 MOVE D0,D4 AND #15360,D0 LSR #2,D0 LSR #8,D0 CMPI #6,D0 BNE.S L604 MOVE D4,-(A7) JSR F156_afzz_(PC) ADDQ.L #2,A7 MOVE.L D0,A2 MOVE.L A2,D0 MOVE.L D0,A0 MOVE 2(A0),D0 AND #127,D0 ASL.L #2,D0 LEA G239_as_Gr(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,A2 MOVE.B 2(A2),D0 AND #255,D0 AND #128,D0 BEQ.S L605 MOVE D7,-(A7) MOVE 8(A6),-(A7) JSR F312_xzzz_(PC) ADDQ.L #4,A7 MOVE.L D0,-(A7) MOVE D5,-(A7) MOVE.L A2,-(A7) JSR F143_mzzz_(PC) ADDQ.L #6,A7 MOVE.L D0,D1 MOVE.L (A7)+,D0 ADD D1,D0 MOVE 10(A6),D1 LEA G050_auc_G(A4),A0 ADDA D1,A0 MOVE.B (A0),D1 AND #255,D1 MULU D1,D0 MOVE D7,D1 CMP 10(A6),D1 BNE.S L606 MOVE #4,D1 BRA.S L607 L606: MOVE #5,D1 L607: LSR D1,D0 ADD D0,D6 L605: L604: L602: ADDQ #1,D7 L600: CMPI #1,D7 BLE L601(PC) L603: JSR F027_AA59_(PC) MOVE.B 83(A3),D1 AND #255,D1 ASR #3,D1 ADDQ #1,D1 AND.L #65535,D0 DIVU D1,D0 SWAP D0 MOVE D0,D7 MOVE D5,D0 BEQ.S L608 MOVE D7,D0 ASR #1,D0 MOVE D0,D7 L608: MOVE 64(A3),D0 ADD 274(A3),D0 ADD G407_s_Par+3204(A4),D0 ADD D6,D0 ADD D0,D7 CMPI #1,10(A6) BLS.S L609 MOVE 10(A6),D0 ASL.L #1,D0 LEA 212(A3),A0 ADDA D0,A0 MOVE (A0),D0 MOVE D0,D4 AND #15360,D0 LSR #2,D0 LSR #8,D0 CMPI #6,D0 BNE.S L609 MOVE D4,-(A7) JSR F156_afzz_(PC) ADDQ.L #2,A7 MOVE.L D0,A2 MOVE D5,-(A7) MOVE.L A2,D0 MOVE.L D0,A0 MOVE 2(A0),D0 AND #127,D0 ASL.L #2,D0 LEA G239_as_Gr(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,-(A7) JSR F143_mzzz_(PC) ADDQ.L #6,A7 ADD D0,D7 L609: MOVE 50(A3),D0 MOVE #1,D1 MOVE 10(A6),D3 ASL D3,D1 AND D1,D0 BEQ.S L610 JSR F029_AA19_(PC) MOVE.L D0,D1 MOVE #8,D0 ADD D1,D0 SUB D0,D7 L610: MOVE G300_B_Par(A4),D0 BEQ.S L611 MOVE D7,D0 ASR #1,D0 MOVE D0,D7 L611: MOVE #100,-(A7) MOVE D7,D0 ASR #1,D0 MOVE D0,-(A7) CLR -(A7) JSR F026_a003_(PC) ADDQ.L #6,A7 L598: MOVEM.L (A7)+,D4-D7/A2-A3 UNLK A6 RTS L$597: .EQU #0 F314_gzzz_:/* global */ LINK A6,L$612 MOVE #1,G321_B_Sto(A4) CLR G300_B_Par(A4) MOVE #10,G318_i_Wai(A4) JSR F098_rzzz_(PC) LEA G447_as_Gr(A4),A0 MOVE.L A0,G441_ps_Pr(A4) LEA G448_as_Gr(A4),A0 MOVE.L A0,G442_ps_Se(A4) LEA G458_as_Gr(A4),A0 MOVE.L A0,G443_ps_Pr(A4) LEA G459_as_Gr(A4),A0 MOVE.L A0,G444_ps_Se(A4) JSR F357_qzzz_(PC) JSR F457_AA08_(PC) L613: UNLK A6 RTS L$612: .EQU #-2 F315_arzz_:/* global */ LINK A6,L$614 MOVEM.L A3/D7-D6,-(A7) MOVE.B G407_s_Par+3210(A4),D6 AND #255,D6 BEQ.S L616 MOVE 8(A6),D0 AND #31,D0 MOVE D0,D3 ANDI #-32,-2(A6) OR D3,-2(A6) MOVE 10(A6),D0 AND #31,D0 MOVE D0,D3 ASL #5,D3 ANDI #-993,-2(A6) OR D3,-2(A6) MOVE G272_i_Cur(A4),D0 AND #63,D0 MOVE D0,D3 ASL #2,D3 ASL #8,D3 ANDI #1023,-2(A6) OR D3,-2(A6) MOVE -2(A6),D7 MOVE D6,D0 SUBQ #1,D6 ASL.L #1,D0 LEA G407_s_Par+3214(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,D0 MOVE.L D0,A3 L617: MOVE -(A3),D0 CMP D7,D0 BNE.S L620 MOVE D6,D0 ADDQ #1,D0 BRA.S L615 L620: L618: MOVE D6,D0 SUBQ #1,D6 TST D0 BNE.S L617 L619: L616: MOVE #0,D0 L615: MOVEM.L (A7)+,D6-D7/A3 UNLK A6 RTS L$614: .EQU #-2 F316_aizz_:/* global */ LINK A6,L$621 MOVEM.L D7-D6,-(A7) MOVE 8(A6),D7 AND #255,D6 SUBQ.B #1,G407_s_Par+3210(A4) MOVE.B G407_s_Par+3210(A4),D6 AND #255,D6 SUB D7,D6 BEQ.S L623 MOVE D6,D0 MULU #2,D0 MOVE D0,-(A7) MOVE D7,D0 ASL.L #1,D0 LEA G407_s_Par+3214(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,-(A7) MOVE D7,D0 ASL.L #1,D0 LEA G407_s_Par+3216(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,-(A7) JSR F007_aAA7_(PC) ADDA #10,A7 MOVE D6,-(A7) MOVE D7,D0 LEA G407_s_Par+3262(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,-(A7) MOVE D7,D0 LEA G407_s_Par+3263(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,-(A7) JSR F007_aAA7_(PC) ADDA #10,A7 L623: MOVE D7,D0 MOVE.B G407_s_Par+3212(A4),D1 AND #255,D1 CMP D1,D0 BCC.S L624 SUBQ.B #1,G407_s_Par+3212(A4) L624: MOVE D7,D0 MOVE.B G407_s_Par+3213(A4),D1 AND #255,D1 CMP D1,D0 BCC.S L625 SUBQ.B #1,G407_s_Par+3213(A4) L625: L622: MOVEM.L (A7)+,D6-D7 UNLK A6 RTS L$621: .EQU #0 F317_adzz_:/* global */ LINK A6,L$626 MOVEM.L A3/D7-D4,-(A7) MOVE 12(A6),D7 MOVE.B G407_s_Par+3210(A4),D6 AND #255,D6 BEQ L628(PC) MOVE D7,D5 AND #-32768,D5 BEQ.S L629 AND #32767,D7 L629: MOVE 8(A6),D0 AND #31,D0 MOVE D0,D3 ANDI #-32,-2(A6) OR D3,-2(A6) MOVE 10(A6),D0 AND #31,D0 MOVE D0,D3 ASL #5,D3 ANDI #-993,-2(A6) OR D3,-2(A6) MOVE G272_i_Cur(A4),D0 AND #63,D0 MOVE D0,D3 ASL #2,D3 ASL #8,D3 ANDI #1023,-2(A6) OR D3,-2(A6) LEA G407_s_Par+3214(A4),A0 MOVE.L A0,A3 CLR D4 BRA.S L630 L631: MOVE.L A3,A0 ADDQ.L #2,A3 LEA (A0),A1 LEA -2(A6),A0 MOVEQ #0,D0 JSR _blockcmp(PC) MOVE D4,D0 BNE.S L633 MOVE #1,D4 MOVE D5,D0 BEQ.S L634 MOVE D7,-(A7) LEA G407_s_Par+3262(A4),A0 ADDA D6,A0 MOVE.B (A0),D0 AND #255,D0 MOVE D0,-(A7) JSR F025_aatz_(PC) ADDQ.L #4,A7 MOVE D0,D7 BRA.S L635 L634: LEA G407_s_Par+3262(A4),A0 ADDA D6,A0 MOVE.B (A0),D0 AND #255,D0 ADD D7,D0 MOVE D0,-(A7) MOVE #80,-(A7) JSR F024_aatz_(PC) ADDQ.L #4,A7 MOVE D0,D7 L635: L633: MOVE D7,D0 LEA G407_s_Par+3262(A4),A0 ADDA D6,A0 MOVE.B D0,(A0) L630: MOVE D6,D0 SUBQ #1,D6 TST D0 BNE.S L631 L632: L628: L627: MOVEM.L (A7)+,D4-D7/A3 UNLK A6 RTS L$626: .EQU #-2 F318_xxxx_:/* global */ LINK A6,L$636 MOVEM.L D7-D4,-(A7) MOVE 8(A6),D7 MOVE D7,D6 MULS #800,D6 LEA G407_s_Par+29(A4),A0 ADDA D6,A0 MOVE.B (A0),D6 AND #255,D6 CLR D4 BRA.S L638 L639: MOVE D4,D0 ASL.L #1,D0 LEA G057_ai_Gr(A4),A0 ADDA D0,A0 MOVE (A0),-(A7) MOVE D7,-(A7) JSR F300_aozz_(PC) ADDQ.L #4,A7 MOVE D0,D5 CMPI #-1,D0 BEQ.S L642 MOVE G307_i_Par(A4),-(A7) MOVE G306_i_Par(A4),-(A7) CLR -(A7) MOVE #-1,-(A7) MOVE D5,D0 AND #16383,D0 MOVE D6,D1 ASL #6,D1 ASL #8,D1 OR D1,D0 MOVE D0,-(A7) JSR F267_dzzz_(PC) ADDA #10,A7 L642: L640: ADDQ #1,D4 L638: CMPI #30,D4 BCS.S L639 L641: L637: MOVEM.L (A7)+,D4-D7 UNLK A6 RTS L$636: .EQU #0 F319_xxxx_:/* global */ LINK A6,L$643 MOVEM.L A3-A2/D7-D4,-(A7) MOVE 8(A6),D7 MOVE D7,D0 MULS #800,D0 LEA G407_s_Par(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,A3 CLR 52(A3) ORI #4096,48(A3) MOVE D7,D0 ADDQ #1,D0 MOVE G423_i_Inv(A4),D1 CMP D1,D0 BNE.S L645 MOVE G331_B_Pre(A4),D0 BEQ.S L646 CLR G331_B_Pre(A4) CLR G597_B_Ign(A4) MOVE G415_B_Lea(A4),D0 BNE.S L647 MOVE G414_T_Lea(A4),-(A7) JSR F034_aaau_(PC) ADDQ.L #2,A7 L647: MOVE #1,G587_i_Hid(A4) JSR F078_xzzz_(PC) BRA.S L648 L646: MOVE G333_B_Pre(A4),D0 BEQ.S L649 CLR G333_B_Pre(A4) CLR G597_B_Ign(A4) MOVE #1,G587_i_Hid(A4) JSR F078_xzzz_(PC) L649: L648: MOVE #4,-(A7) JSR F355_hzzz_(PC) ADDQ.L #2,A7 L645: MOVE D7,-(A7) JSR F318_xxxx_(PC) ADDQ.L #2,A7 MOVE #-32758,-(A7) JSR F166_szzz_(PC) ADDQ.L #2,A7 MOVE D0,D4 CMPI #-1,D4 BNE.S L650 BRA.S L651 L650: MOVE D4,-(A7) JSR F156_afzz_(PC) ADDQ.L #2,A7 MOVE.L D0,A2 MOVE #5,D0 AND #127,D0 MOVE D0,D3 ANDI #-128,2(A2) OR D3,2(A2) MOVE #1,D0 AND #1,D0 MOVE D0,D3 ASL #7,D3 ANDI #-129,2(A2) OR D3,2(A2) MOVE D7,D0 AND #3,D0 MOVE D0,D3 ASL #6,D3 ASL #8,D3 ANDI #16383,2(A2) OR D3,2(A2) MOVE.B 29(A3),D6 AND #255,D6 MOVE G307_i_Par(A4),-(A7) MOVE G306_i_Par(A4),-(A7) CLR -(A7) MOVE #-1,-(A7) MOVE D4,D0 AND #16383,D0 MOVE D6,D1 ASL #6,D1 ASL #8,D1 OR D1,D0 MOVE D0,-(A7) JSR F267_dzzz_(PC) ADDA #10,A7 L651: CLR.B 33(A3) CLR.B 34(A3) MOVE G308_i_Par(A4),D0 MOVE.B D0,28(A3) CLR.B 41(A3) MOVE D6,D0 ADDQ #4,D0 SUB G308_i_Par(A4),D0 AND #3,D0 MOVE D0,D6 MOVE D6,D0 ADDQ #1,D0 CMP G599_ui_Us(A4),D0 BNE.S L652 MOVE #1,G598_B_Mou(A4) CLR G599_ui_Us(A4) MOVE #1,G592_B_Bui(A4) L652: MOVE.B 42(A3),D0 BEQ.S L653 MOVE D7,-(A7) JSR F323_xxxx_(PC) ADDQ.L #2,A7 L653: CLR G578_B_Use(A4) MOVE #160,-(A7) CLR -(A7) MOVE D6,D0 ASL #2,D0 ASL.L #1,D0 LEA G054_ai_Gr(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,-(A7) MOVE.L G348_pl_Bi(A4),-(A7) JSR F135_xzzz_(PC) ADDA #12,A7 MOVE D7,-(A7) JSR F292_arzz_(PC) ADDQ.L #2,A7 MOVE #0,D0 MOVE D0,D5 LEA G407_s_Par(A4),A0 MOVE.L A0,D0 MOVE.L D0,A3 BRA.S L654 L655: MOVE 52(A3),D0 BEQ.S L658 BRA.S L657 L658: L656: MOVE D5,D0 ADDQ #1,D5 MOVE.L A3,D0 ADDA #800,A3 L654: MOVE D5,D0 CMP G305_ui_Pa(A4),D0 BCS.S L655 L657: MOVE D5,D0 CMP G305_ui_Pa(A4),D0 BNE.S L659 MOVE #1,G303_B_Par(A4) BRA.S L644 L659: MOVE D7,D0 MOVE G411_i_Lea(A4),D1 CMP D1,D0 BNE.S L660 MOVE D5,-(A7) JSR F368_fzzz_(PC) ADDQ.L #2,A7 L660: MOVE D7,D0 MOVE G514_i_Mag(A4),D1 CMP D1,D0 BNE.S L661 MOVE D5,-(A7) JSR F394_ozzz_(PC) ADDQ.L #2,A7 BRA.S L644 L661: MOVE G514_i_Mag(A4),-(A7) JSR F393_lzzz_(PC) ADDQ.L #2,A7 L644: MOVEM.L (A7)+,D4-D7/A2-A3 UNLK A6 RTS L$643: .EQU #0 F320_akzz_:/* global */ LINK A6,L$662 MOVEM.L A3-A2/D7-D4,-(A7) LEA G407_s_Par(A4),A0 MOVE.L A0,A3 CLR D7 BRA L664(PC) L665: MOVE D7,D0 ASL.L #1,D0 LEA G410_ai_Ch(A4),A0 ADDA D0,A0 MOVE (A0),D0 MOVE D0,D4 OR D0,50(A3) MOVE D7,D0 ASL.L #1,D0 LEA G410_ai_Ch(A4),A0 ADDA D0,A0 CLR (A0) MOVE D7,D0 ASL.L #1,D0 LEA G409_ai_Ch(A4),A0 ADDA D0,A0 MOVE (A0),D0 MOVE D0,D6 BNE.S L668 BRA L666(PC) L668: MOVE D7,D0 ASL.L #1,D0 LEA G409_ai_Ch(A4),A0 ADDA D0,A0 CLR (A0) MOVE 52(A3),D0 MOVE D0,D5 BNE.S L669 BRA L666(PC) L669: MOVE D5,D0 SUB D6,D0 MOVE D0,D5 CMPI #0,D0 BGT.S L670 MOVE D7,-(A7) JSR F319_xxxx_(PC) ADDQ.L #2,A7 BRA L671(PC) L670: MOVE D5,52(A3) ORI #256,48(A3) MOVE D4,D0 BEQ.S L672 ORI #8192,48(A3) L672: MOVE D7,D5 MULU #69,D5 CLR -16(A6) JSR F077_aA39_(PC) MOVE D7,D0 ADDQ #1,D0 MOVE G423_i_Inv(A4),D1 CMP D1,D0 BNE.S L673 MOVE #28,-14(A6) MOVE D5,D0 ADDQ #7,D0 MOVE D0,-20(A6) ADD #31,D0 MOVE D0,-18(A6) MOVE #10,-(A7) MOVE #16,-(A7) PEA -20(A6) MOVE #16,-(A7) JSR F489_ayzz_(PC) ADDQ.L #2,A7 MOVE.L D0,-(A7) JSR F021_a002_(PC) ADDA #12,A7 CMPI #10,D6 BCC.S L674 ADD #21,D5 BRA.S L675 L674: CMPI #100,D6 BCC.S L676 ADD #18,D5 BRA.S L677 L676: ADD #15,D5 L677: L675: MOVE #16,-2(A6) BRA.S L678 L673: MOVE #6,-14(A6) MOVE D5,D0 MOVE D0,-20(A6) ADD #47,D0 MOVE D0,-18(A6) MOVE #10,-(A7) MOVE #24,-(A7) PEA -20(A6) MOVE #15,-(A7) JSR F489_ayzz_(PC) ADDQ.L #2,A7 MOVE.L D0,-(A7) JSR F021_a002_(PC) ADDA #12,A7 CMPI #10,D6 BCC.S L679 ADD #19,D5 BRA.S L680 L679: CMPI #100,D6 BCC.S L681 ADD #16,D5 BRA.S L682 L681: ADD #13,D5 L682: L680: MOVE #5,-2(A6) L678: MOVE #3,-(A7) CLR -(A7) MOVE D6,-(A7) JSR F288_xxxx_(PC) ADDQ.L #6,A7 MOVE.L D0,-(A7) MOVE #8,-(A7) MOVE #15,-(A7) MOVE -2(A6),-(A7) MOVE D5,-(A7) JSR F053_aajz_(PC) ADDA #12,A7 MOVE 46(A3),D0 MOVE D0,D5 CMPI #-1,D0 BNE.S L683 MOVE.B #12,-8(A6) MOVE.L G313_ul_Ga(A4),D0 ADDQ.L #5,D0 MOVE G309_i_Par(A4),D1 EXT.L D1 MOVE.L #24,D3 ASL.L D3,D1 OR.L D1,D0 MOVE.L D0,-12(A6) MOVE D7,D0 MOVE.B D0,-7(A6) PEA -12(A6) JSR F238_pzzz_(PC) ADDQ.L #4,A7 MOVE D0,46(A3) BRA.S L684 L683: MOVE D5,D0 MULS #10,D0 MOVE.L G370_ps_Ev(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,A2 MOVE.L G313_ul_Ga(A4),D0 ADDQ.L #5,D0 MOVE G309_i_Par(A4),D1 EXT.L D1 MOVE.L #24,D3 ASL.L D3,D1 OR.L D1,D0 MOVE.L D0,(A2) MOVE D5,-(A7) JSR F235_bzzz_(PC) ADDQ.L #2,A7 MOVE D0,-(A7) JSR F236_pzzz_(PC) ADDQ.L #2,A7 L684: MOVE D7,-(A7) JSR F292_arzz_(PC) ADDQ.L #2,A7 JSR F078_xzzz_(PC) L671: L666: MOVE D7,D0 ADDQ #1,D7 MOVE.L A3,D0 ADDA #800,A3 L664: MOVE D7,D0 CMP G305_ui_Pa(A4),D0 BCS L665(PC) L667: L663: MOVEM.L (A7)+,D4-D7/A2-A3 UNLK A6 RTS L$662: .EQU #-20 F321_AA29_:/* global */ LINK A6,L$685 MOVEM.L A3/D7-D4,-(A7) MOVE 10(A6),D7 CMPI #-1,8(A6) BEQ.S L688 MOVE 8(A6),D0 ADDQ #1,D0 CMP G299_ui_Ca(A4),D0 BEQ.S L689 MOVE G302_B_Gam(A4),D0 BEQ.S L687 L689: L688: BRA L686(PC) L687: CMPI #0,D7 BGT.S L690 MOVE #0,D0 BRA L686(PC) L690: MOVE 8(A6),D0 MULS #800,D0 LEA G407_s_Par(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,A3 MOVE 52(A3),D0 BNE.S L691 L44T321_004: MOVE #0,D0 BRA L686(PC) L691: CMPI #0,14(A6) BEQ L692(PC) MOVE #0,D0 MOVE D0,D4 MOVE #0,D0 MOVE D0,D6 MOVE #0,D0 MOVE D0,D5 BRA.S L693 L694: MOVE 12(A6),D0 MOVE #1,D1 ASL D6,D1 AND D1,D0 BEQ.S L697 ADDQ #1,D4 MOVE D6,D0 CMPI #4,14(A6) BNE.S L698 MOVE #-32768,D1 BRA.S L699 L698: MOVE #0,D1 L699: OR D1,D0 MOVE D0,-(A7) MOVE 8(A6),-(A7) JSR F313_xxxx_(PC) ADDQ.L #4,A7 ADD D0,D5 L697: L695: ADDQ #1,D6 L693: CMPI #5,D6 BLE.S L694 L696: MOVE D4,D0 BEQ.S L700 MOVE D5,D0 AND.L #65535,D0 DIVU D4,D0 MOVE D0,D5 L700: MOVE 14(A6),D0 L701: CMP #6,D0 BEQ.S L702 BRA.S L704 L702: MOVE #115,D0 MOVE.B 80(A3),D3 AND #255,D3 SUB D3,D0 MOVE D0,D6 CMPI #0,D0 BGT.S L706 CLR D7 BRA.S L707 L706: MOVE D6,-(A7) MOVE #6,-(A7) MOVE D7,-(A7) JSR F030_aaaW_(PC) ADDQ.L #6,A7 MOVE D0,D7 L707: BRA L44T321_024(PC) BRA.S L705 L704: CMP #5,D0 BEQ.S L705 BRA.S L708 L705: MOVE D7,-(A7) MOVE #5,-(A7) MOVE.L A3,-(A7) JSR F307_fzzz_(PC) ADDQ.L #8,A7 MOVE D0,D7 SUB G407_s_Par+3208(A4),D7 BRA.S L44T321_024 BRA.S L709 L708: CMP #1,D0 BEQ.S L709 BRA.S L710 L709: MOVE D7,-(A7) MOVE #6,-(A7) MOVE.L A3,-(A7) JSR F307_fzzz_(PC) ADDQ.L #8,A7 MOVE D0,D7 SUB G407_s_Par+3206(A4),D7 BRA.S L703 BRA.S L711 L710: CMP #2,D0 BEQ.S L711 BRA.S L712 L711: MOVE D5,D0 LSR #1,D0 MOVE D0,D5 BRA.S L713 L712: CMP #3,D0 BEQ.S L713 L714: CMP #4,D0 BEQ.S L713 L715: CMP #7,D0 L716: L713: L703: CMPI #0,D7 BGT.S L717 BRA L44T321_004(PC) L717: MOVE #130,D0 SUB D5,D0 MOVE D0,-(A7) MOVE #6,-(A7) MOVE D7,-(A7) JSR F030_aaaW_(PC) ADDQ.L #6,A7 MOVE D0,D7 L44T321_024: CMPI #0,D7 BGT.S L718 BRA L44T321_004(PC) L718: JSR F027_AA59_(PC) AND #127,D0 ADD #10,D0 MOVE D0,-(A7) MOVE #4,-(A7) MOVE.L A3,-(A7) JSR F307_fzzz_(PC) ADDQ.L #8,A7 MOVE D0,D6 MOVE D0,-10(A6) MOVE D7,D0 CMP -10(A6),D0 BLE.S L719 L720: JSR F027_AA59_(PC) MOVE.L D0,D1 AND #7,D1 MOVE D1,-20(A6) MOVE #1,D1 MOVE -20(A6),D3 ASL D3,D1 AND 12(A6),D1 MOVE 8(A6),D0 ASL.L #1,D0 LEA G410_ai_Ch(A4),A0 ADDA D0,A0 MOVE (A0),D0 OR D1,D0 MOVE D0,(A0) L721: MOVE D6,D0 ASL #1,D0 MOVE D0,D6 MOVE D0,-30(A6) MOVE D7,D0 CMP -30(A6),D0 BLE.S L723 MOVE D6,D0 BNE.S L720 L723: L722: L719: MOVE G300_B_Par(A4),D0 BEQ.S L724 JSR F314_gzzz_(PC) L724: L692: CMPI #0,D7 BGT.S L725 CLR D7 L725: MOVE 8(A6),D0 ASL.L #1,D0 LEA G409_ai_Ch(A4),A0 ADDA D0,A0 MOVE (A0),D0 ADD D7,D0 MOVE D0,(A0) MOVE D7,D0 L686: MOVEM.L (A7)+,D4-D7/A3 UNLK A6 RTS L$685: .EQU #-30 F322_lzzz_:/* global */ LINK A6,L$726 CMPI #-1,8(A6) BEQ.S L729 MOVE 8(A6),D0 ADDQ #1,D0 CMP G299_ui_Ca(A4),D0 BNE.S L728 L729: BRA L727(PC) L728: MOVE 8(A6),D0 MULS #800,D0 LEA G407_s_Par(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,-14(A6) CLR -(A7) CLR -(A7) MOVE 10(A6),D0 LSR #6,D0 MOVE D0,-(A7) MOVE #1,-(A7) JSR F025_aatz_(PC) ADDQ.L #4,A7 MOVE D0,-(A7) MOVE 8(A6),-(A7) JSR F321_AA29_(PC) ADDQ.L #8,A7 MOVE.L -14(A6),A0 ORI #256,48(A0) MOVE 8(A6),D0 ADDQ #1,D0 CMP G423_i_Inv(A4),D0 BNE.S L730 CMPI #0,G424_i_Pan(A4) BNE.S L730 MOVE.L -14(A6),A0 ORI #2048,48(A0) L730: SUBQ #1,10(A6) BEQ.S L731 MOVE.L -14(A6),A0 ADDQ.B #1,42(A0) MOVE.B #75,-6(A6) MOVE 8(A6),D0 MOVE.B D0,-5(A6) MOVE.L G313_ul_Ga(A4),D0 ADD.L #36,D0 MOVE G309_i_Par(A4),D1 EXT.L D1 MOVE.L #24,D3 ASL.L D3,D1 OR.L D1,D0 MOVE.L D0,-10(A6) MOVE 10(A6),-4(A6) PEA -10(A6) JSR F238_pzzz_(PC) ADDQ.L #4,A7 L731: MOVE 8(A6),-(A7) JSR F292_arzz_(PC) ADDQ.L #2,A7 L727: UNLK A6 RTS L$726: .EQU #-14 F323_xxxx_:/* global */ LINK A6,L$732 MOVEM.L A3/D7,-(A7) CMPI #-1,8(A6) BNE.S L734 BRA.S L733 L734: MOVE #0,D0 MOVE D0,D7 MOVE.L G370_ps_Ev(A4),D0 MOVE.L D0,A3 BRA.S L735 L736: MOVE.B 4(A3),D0 AND #255,D0 CMP #75,D0 BNE.S L739 MOVE.B 5(A3),D0 AND #255,D0 CMP 8(A6),D0 BNE.S L739 MOVE D7,-(A7) JSR F237_rzzz_(PC) ADDQ.L #2,A7 L739: L737: MOVE.L A3,D0 ADDA #10,A3 MOVE D7,D0 ADDQ #1,D7 L735: MOVE D7,D0 CMP G369_ui_Ev(A4),D0 BCS.S L736 L738: MOVE 8(A6),D0 MULS #800,D0 LEA G407_s_Par+42(A4),A0 ADDA D0,A0 CLR.B (A0) L733: MOVEM.L (A7)+,D7/A3 UNLK A6 RTS L$732: .EQU #0 F324_aezz_:/* global */ LINK A6,L$740 MOVEM.L A3/D7-D4,-(A7) MOVE 8(A6),D7 MOVE D7,D0 BNE.S L742 BRA.S L741 L742: MOVE D7,D0 LSR #3,D0 ADDQ #1,D0 MOVE D0,D5 SUB D0,D7 MOVE D5,D0 ASL #1,D0 MOVE D0,D5 MOVE #0,D0 MOVE D0,D4 MOVE #0,D0 MOVE D0,D6 BRA.S L743 L744: MOVE 12(A6),-(A7) MOVE 10(A6),-(A7) JSR F027_AA59_(PC) MOVE.L D0,D1 AND.L #65535,D1 DIVU D5,D1 SWAP D1 MOVE D7,D0 ADD D1,D0 MOVE D0,-(A7) MOVE #1,-(A7) JSR F025_aatz_(PC) ADDQ.L #4,A7 MOVE D0,-(A7) MOVE D6,-(A7) JSR F321_AA29_(PC) ADDQ.L #8,A7 TST D0 BEQ.S L747 ADDQ #1,D4 L747: L745: ADDQ #1,D6 L743: MOVE D6,D0 CMP G305_ui_Pa(A4),D0 BCS.S L744 L746: MOVE D4,D0 L741: MOVEM.L (A7)+,D4-D7/A3 UNLK A6 RTS L$740: .EQU #0 F325_bzzz_:/* global */ LINK A6,L$748 MOVEM.L A3/D7,-(A7) CMPI #-1,8(A6) BNE.S L750 BRA.S L749 L750: MOVE 8(A6),D0 MULS #800,D0 LEA G407_s_Par(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,A3 MOVE 56(A3),D0 SUB 10(A6),D0 MOVE D0,56(A3) MOVE D0,D7 CMPI #0,D0 BGT.S L751 CLR 56(A3) CLR -(A7) CLR -(A7) MOVE D7,D0 NEG D0 ASR #1,D0 MOVE D0,-(A7) MOVE 8(A6),-(A7) JSR F321_AA29_(PC) ADDQ.L #8,A7 BRA.S L752 L751: MOVE D7,D0 CMP 58(A3),D0 BLE.S L753 MOVE 58(A3),56(A3) L753: L752: ORI #768,48(A3) L749: MOVEM.L (A7)+,D7/A3 UNLK A6 RTS L$748: .EQU #0 F326_ozzz_:/* global */ LINK A6,L$754 MOVEM.L A3/D7,-(A7) MOVE.L 8(A6),A3 MOVE.B 28(A3),D7 AND #255,D7 MOVE 18(A6),-(A7) MOVE 16(A6),-(A7) MOVE 14(A6),-(A7) MOVE D7,-(A7) MOVE.B 29(A3),D0 AND #255,D0 SUB D7,D0 ADDQ #1,D0 AND #2,D0 LSR #1,D0 ADD D7,D0 AND #3,D0 MOVE D0,-(A7) MOVE G307_i_Par(A4),-(A7) MOVE G306_i_Par(A4),-(A7) MOVE 12(A6),-(A7) JSR F212_mzzz_(PC) ADDA #16,A7 L755: MOVEM.L (A7)+,D7/A3 UNLK A6 RTS L$754: .EQU #0 F327_kzzz_:/* global */ LINK A6,L$756 MOVEM.L A3/D7-D6,-(A7) MOVE 12(A6),D7 MOVE 8(A6),D0 MULS #800,D0 LEA G407_s_Par(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,A3 MOVE 60(A3),D0 CMP 14(A6),D0 BCC.S L758 MOVE #0,D0 BRA.S L757 L758: MOVE 14(A6),D0 SUB D0,60(A3) ORI #256,48(A3) MOVE 62(A3),D0 ASR #3,D0 MOVE D0,-(A7) MOVE #8,-(A7) JSR F024_aatz_(PC) ADDQ.L #4,A7 MOVE.L D0,D1 MOVE #10,D0 SUB D1,D0 MOVE D0,D6 MOVE D7,D0 MOVE D6,D1 ASL #2,D1 CMP D1,D0 BGE.S L759 ADDQ #3,D7 SUBQ #1,D6 L759: MOVE D6,-(A7) MOVE #90,-(A7) MOVE D7,-(A7) MOVE 10(A6),-(A7) MOVE.L A3,-(A7) JSR F326_ozzz_(PC) ADDA #12,A7 L757: MOVEM.L (A7)+,D6-D7/A3 UNLK A6 RTS L$756: .EQU #0 F328_nzzz_:/* global */ LINK A6,L$760 MOVEM.L A3-A2/D7-D4,-(A7) CLR -4(A6) CMPI #0,10(A6) BGE.S L762 MOVE G415_B_Lea(A4),D0 BEQ.S L763 MOVE #0,D0 BRA L761(PC) L763: JSR F298_aqzz_(PC) MOVE D0,D4 MOVE 8(A6),D0 MULS #800,D0 LEA G407_s_Par(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,A3 MOVE 214(A3),-2(A6) MOVE D4,214(A3) MOVE #1,10(A6) MOVE #1,-4(A6) L762: MOVE 10(A6),-(A7) MOVE 8(A6),-(A7) JSR F312_xzzz_(PC) ADDQ.L #4,A7 MOVE D0,D7 MOVE -4(A6),D0 BEQ.S L764 MOVE 10(A6),D0 ASL.L #1,D0 LEA 212(A3),A0 ADDA D0,A0 MOVE -2(A6),(A0) BRA.S L765 L764: MOVE 10(A6),-(A7) MOVE 8(A6),-(A7) JSR F300_aozz_(PC) ADDQ.L #4,A7 MOVE D0,D4 CMPI #-1,D0 BNE.S L766 MOVE #0,D0 BRA L761(PC) L766: L765: MOVE #1,-(A7) MOVE G307_i_Par(A4),-(A7) MOVE G306_i_Par(A4),-(A7) MOVE #16,-(A7) JSR F064_aadz_(PC) ADDQ.L #8,A7 MOVE D4,-(A7) JSR F305_xxxx_(PC) ADDQ.L #2,A7 MOVE D0,-(A7) MOVE 8(A6),-(A7) JSR F325_bzzz_(PC) ADDQ.L #4,A7 MOVE #4,-(A7) MOVE 8(A6),-(A7) JSR F330_szzz_(PC) ADDQ.L #4,A7 MOVE #8,D6 MOVE #1,D5 MOVE D4,D0 AND #15360,D0 LSR #2,D0 LSR #8,D0 CMPI #5,D0 BNE.S L767 ADDQ #4,D6 MOVE D4,-(A7) JSR F158_ayzz_(PC) ADDQ.L #2,A7 MOVE.L D0,A2 MOVE.B 1(A2),D0 AND #255,D0 CMP #12,D0 BGT.S L768 MOVE.B 3(A2),D0 AND #255,D0 MOVE D0,D5 ASR #2,D0 ADD D0,D6 L768: L767: MOVE D6,-(A7) MOVE #10,-(A7) MOVE 8(A6),-(A7) JSR F304_apzz_(PC) ADDQ.L #6,A7 ADD D5,D7 MOVE #10,-(A7) MOVE 8(A6),-(A7) JSR F303_AA09_(PC) ADDQ.L #4,A7 MOVE D0,D5 JSR F027_AA59_(PC) AND #15,D0 MOVE D7,D1 ASR #1,D1 ADD D1,D0 ADD D5,D0 ADD D0,D7 MOVE #200,-(A7) JSR F027_AA59_(PC) MOVE.L D0,D1 AND #31,D1 MOVE D5,D0 ASL #3,D0 ADD D1,D0 MOVE D0,-(A7) MOVE #40,-(A7) JSR F026_a003_(PC) ADDQ.L #6,A7 MOVE D0,D6 MOVE #11,D0 SUB D5,D0 MOVE D0,-(A7) MOVE #5,-(A7) JSR F025_aatz_(PC) ADDQ.L #4,A7 MOVE D0,D5 MOVE D5,-(A7) MOVE D6,-(A7) MOVE D7,-(A7) MOVE G308_i_Par(A4),-(A7) MOVE G308_i_Par(A4),D0 ADD 12(A6),D0 AND #3,D0 MOVE D0,-(A7) MOVE G307_i_Par(A4),-(A7) MOVE G306_i_Par(A4),-(A7) MOVE D4,-(A7) JSR F212_mzzz_(PC) ADDA #16,A7 MOVE #4,G311_i_Pro(A4) MOVE G308_i_Par(A4),G312_i_Las(A4) MOVE 8(A6),-(A7) JSR F292_arzz_(PC) ADDQ.L #2,A7 MOVE #1,D0 L761: MOVEM.L (A7)+,D4-D7/A2-A3 UNLK A6 RTS L$760: .EQU #-4 F329_hzzz_:/* global */ LINK A6,L$769 CMPI #-1,G411_i_Lea(A4) BNE.S L771 MOVE #0,D0 BRA.S L770 L771: MOVE 8(A6),-(A7) MOVE #-1,-(A7) MOVE G411_i_Lea(A4),-(A7) JSR F328_nzzz_(PC) ADDQ.L #6,A7 L770: UNLK A6 RTS L$769: .EQU #0 F330_szzz_:/* global */ LINK A6,L$772 MOVEM.L A3/D7-D5,-(A7) MOVE 8(A6),D0 MULS #800,D0 LEA G407_s_Par(A4),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,A3 MOVE.L G313_ul_Ga(A4),D7 MOVE 10(A6),D3 AND.L #65535,D3 ADD.L D3,D7 MOVE.B #11,-6(A6) MOVE 8(A6),D0 MOVE.B D0,-5(A6) CLR.B -4(A6) MOVE 44(A3),D0 MOVE D0,D5 CMPI #0,D0 BLT.S L774 MOVE D5,D6 MULS #10,D6 MOVE.L G370_ps_Ev(A4),A0 ADDA D6,A0 MOVE.L (A0),D6 AND.L #16777215,D6 MOVE.L D7,D0 CMP.L D6,D0 BLT.S L775 MOVE.L D6,D0 SUB.L G313_ul_Ga(A4),D0 ASR.L #1,D0 ADD.L D0,D7 BRA.S L776 L775: MOVE.L D6,D7 MOVE 10(A6),D1 LSR #1,D1 AND.L #65535,D1 ADD.L D1,D7 L776: MOVE D5,-(A7) JSR F237_rzzz_(PC) ADDQ.L #2,A7 BRA.S L777 L774: ORI #-32760,48(A3) MOVE 8(A6),-(A7) JSR F292_arzz_(PC) ADDQ.L #2,A7 L777: MOVE.L D7,D0 MOVE G309_i_Par(A4),D1 EXT.L D1 MOVE.L #24,D3 ASL.L D3,D1 OR.L D1,D0 MOVE.L D0,-10(A6) PEA -10(A6) JSR F238_pzzz_(PC) ADDQ.L #4,A7 MOVE D0,44(A3) L773: MOVEM.L (A7)+,D5-D7/A3 UNLK A6 RTS L$772: .EQU #-10 F331_auzz_:/* global */ LINK A6,L$778 MOVEM.L A3-A2/D7-D4,-(A7) MOVE G305_ui_Pa(A4),D0 BNE.S L780 BRA L779(PC) L780: MOVE G306_i_Par(A4),D0 AND #31,D0 MOVE D0,D3 ANDI #-32,-6(A6) OR D3,-6(A6) MOVE G307_i_Par(A4),D0 AND #31,D0 MOVE D0,D3 ASL #5,D3 ANDI #-993,-6(A6) OR D3,-6(A6) MOVE G309_i_Par(A4),D0 AND #63,D0 MOVE D0,D3 ASL #2,D3 ASL #8,D3 ANDI #1023,-6(A6) OR D3,-6(A6) CLR D6 BRA.S L781 L782: MOVE D6,D0 ASL.L #1,D0 LEA G407_s_Par+3214(A4),A0 ADDA D0,A0 LEA (A0),A1 LEA -6(A6),A0 MOVEQ #0,D0 JSR _blockcmp(PC) MOVE D6,D0 LEA G407_s_Par+3262(A4),A0 ADDA D0,A0 MOVE.B (A0),D0 AND #255,D0 SUBQ #1,D0 MOVE D0,-(A7) CLR -(A7) JSR F025_aatz_(PC) ADDQ.L #4,A7 MOVE D6,D1 LEA G407_s_Par+3262(A4),A0 ADDA D1,A0 MOVE.B D0,(A0) BNE.S L784 MOVE D6,D0 BNE.S L784 CLR -(A7) JSR F316_aizz_(PC) ADDQ.L #2,A7 BRA.S L781 L784: ADDQ #1,D6 L781: MOVE D6,D0 MOVE.B G407_s_Par+3210(A4),D1 AND #255,D1 SUBQ #1,D1 CMP D1,D0 BLT.S L782 L783: MOVE.L G313_ul_Ga(A4),D7 MOVE D7,D0 AND #128,D0 MOVE D7,D1 AND #256,D1 LSR #2,D1 ADD D1,D0 MOVE D7,D1 AND #64,D1 ASL #2,D1 ADD D1,D0 LSR #2,D0 MOVE D0,-2(A6) MOVE #0,D0 MOVE D0,D7 LEA G407_s_Par(A4),A0 MOVE.L A0,D0 MOVE.L D0,A3 BRA L785(PC) L786: MOVE 52(A3),D0 BEQ L789(PC) MOVE D7,D0 ADDQ #1,D0 CMP G299_ui_Ca(A4),D0 BEQ L789(PC) MOVE 60(A3),D0 CMP 62(A3),D0 BGE L790(PC) MOVE #3,-(A7) MOVE D7,-(A7) JSR F303_AA09_(PC) ADDQ.L #4,A7 MOVE.L D0,-(A7) MOVE #2,-(A7) MOVE D7,-(A7) JSR F303_AA09_(PC) ADDQ.L #4,A7 MOVE.L D0,D1 MOVE.L (A7)+,D0 ADD D1,D0 MOVE D0,D5 MOVE D0,-16(A6) MOVE.B 80(A3),D0 AND #255,D0 ADD -16(A6),D0 MOVE D0,-16(A6) MOVE -2(A6),D0 CMP -16(A6),D0 BCC.S L790 MOVE 62(A3),D6 EXT.L D6 DIVS #40,D6 MOVE G300_B_Par(A4),D0 BEQ.S L791 MOVE D6,D0 ASL #1,D0 MOVE D0,D6 L791: ADDQ #1,D6 MOVE #16,D0 SUB D5,D0 MOVE D0,-(A7) MOVE #7,-(A7) JSR F025_aatz_(PC) ADDQ.L #4,A7 MOVE.L D0,D1 MOVE D6,D0 MULU D1,D0 MOVE D0,-(A7) MOVE D7,-(A7) JSR F325_bzzz_(PC) ADDQ.L #4,A7 MOVE 62(A3),D0 SUB 60(A3),D0 MOVE D0,-(A7) MOVE D6,-(A7) JSR F024_aatz_(PC) ADDQ.L #4,A7 ADD D0,60(A3) BRA.S L792 L790: MOVE 60(A3),D0 CMP 62(A3),D0 BLE.S L793 SUBQ #1,60(A3) L793: L792: MOVE #19,D4 BRA.S L794 L795: MOVE D4,D0 MULS #6,D0 LEA 92(A3),A0 ADDA D0,A0 CMPI #0,(A0) BLE.S L798 MOVE D4,D0 MULS #6,D0 LEA 92(A3),A0 ADDA D0,A0 SUBQ #1,(A0) L798: L796: SUBQ #1,D4 L794: CMPI #0,D4 BGE.S L795 L797: MOVE #4,D6 MOVE 58(A3),D4 BRA.S L799 L800: ADDQ #2,D6 L799: MOVE D4,D0 ASR #1,D0 MOVE D0,D4 MOVE D0,-26(A6) MOVE 56(A3),D0 CMP -26(A6),D0 BLT.S L800 L801: CLR D4 MOVE #6,-(A7) MOVE 58(A3),D0 ASR #8,D0 SUBQ #1,D0 MOVE D0,-(A7) MOVE #1,-(A7) JSR F026_a003_(PC) ADDQ.L #6,A7 MOVE D0,-4(A6) MOVE G300_B_Par(A4),D0 BEQ.S L802 MOVE -4(A6),D0 ASL #1,D0 MOVE D0,-4(A6) L802: MOVE.L G313_ul_Ga(A4),D0 SUB.L G362_l_Las(A4),D0 MOVE D0,D5 CMPI #80,D0 BLS.S L803 ADDQ #1,-4(A6) CMPI #250,D5 BLS.S L804 ADDQ #1,-4(A6) L804: L803: L805: CMPI #4,D6 SLS D5 AND #1,D5 CMPI #-512,66(A3) BGE.S L808 MOVE D5,D0 BEQ.S L809 ADD -4(A6),D4 SUBQ #2,66(A3) L809: BRA.S L810 L808: CMPI #0,66(A3) BLT.S L811 SUB -4(A6),D4 L811: MOVE D5,D0 BEQ.S L812 MOVE #2,D0 BRA.S L813 L812: MOVE D6,D0 LSR #1,D0 L813: SUB D0,66(A3) L810: CMPI #-512,68(A3) BGE.S L814 MOVE D5,D0 BEQ.S L815 ADD -4(A6),D4 SUBQ #1,68(A3) L815: BRA.S L816 L814: CMPI #0,68(A3) BLT.S L817 SUB -4(A6),D4 L817: MOVE D5,D0 BEQ.S L818 MOVE #1,D0 BRA.S L819 L818: MOVE D6,D0 LSR #2,D0 L819: SUB D0,68(A3) L816: SUBQ #1,D6 L806: MOVE D6,D0 BEQ.S L820 MOVE 56(A3),D0 SUB D4,D0 CMP 58(A3),D0 BLT L805(PC) L820: L807: MOVE D4,-(A7) MOVE D7,-(A7) JSR F325_bzzz_(PC) ADDQ.L #4,A7 CMPI #-1024,66(A3) BGE.S L821 MOVE #-1024,66(A3) L821: CMPI #-1024,68(A3) BGE.S L822 MOVE #-1024,68(A3) L822: MOVE 52(A3),D0 CMP 54(A3),D0 BGE.S L823 MOVE 56(A3),D0 MOVE 58(A3),D1 ASR #2,D1 CMP D1,D0 BLT.S L823 MOVE -2(A6),D0 MOVE.B 83(A3),D1 AND #255,D1 ADD #12,D1 CMP D1,D0 BCC.S L823 MOVE 54(A3),D0 ASR #7,D0 ADDQ #1,D0 MOVE D0,-4(A6) MOVE G300_B_Par(A4),D0 BEQ.S L824 MOVE -4(A6),D0 ASL #1,D0 MOVE D0,-4(A6) L824: MOVE 232(A3),-(A7) JSR F033_aaaz_(PC) ADDQ.L #2,A7 CMPI #121,D0 BNE.S L825 MOVE -4(A6),D0 ASR #1,D0 ADDQ #1,D0 ADD D0,-4(A6) L825: MOVE 54(A3),D0 SUB 52(A3),D0 MOVE D0,-(A7) MOVE -4(A6),-(A7) JSR F024_aatz_(PC) ADDQ.L #4,A7 ADD D0,52(A3) L823: MOVE.L G313_ul_Ga(A4),D0 MOVE G300_B_Par(A4),D1 BEQ.S L827 MOVE #63,D1 BRA.S L828 L827: MOVE #255,D1 L828: AND D1,D0 BNE.S L826 CLR D6 BRA.S L829 L830: MOVE D6,D0 MULS #3,D0 LEA 70(A3),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,A2 MOVE.B (A2),D5 AND #255,D5 MOVE.B 1(A2),D0 AND #255,D0 CMP D5,D0 BCC.S L832 ADDQ.B #1,1(A2) BRA.S L833 L832: MOVE.B 1(A2),D0 AND #255,D0 CMP D5,D0 BLS.S L834 MOVE.B 1(A2),D0 AND #255,D0 AND.L #65535,D0 DIVU D5,D0 SUB.B D0,1(A2) L834: L833: ADDQ #1,D6 L829: CMPI #6,D6 BLS.S L830 L831: L826: MOVE G300_B_Par(A4),D0 BNE.S L835 MOVE.B 28(A3),D0 AND #255,D0 CMP G308_i_Par(A4),D0 BEQ.S L835 MOVE.L G361_l_Las(A4),D0 MOVE.L G313_ul_Ga(A4),D1 SUB.L #60,D1 CMP.L D1,D0 BGE.S L835 MOVE G308_i_Par(A4),D0 MOVE.B D0,28(A3) CLR.B 41(A3) ORI #1024,48(A3) L835: ORI #256,48(A3) MOVE D7,D0 ADDQ #1,D0 MOVE G423_i_Inv(A4),D1 CMP D1,D0 BNE.S L836 MOVE G333_B_Pre(A4),D0 BNE.S L838 MOVE G331_B_Pre(A4),D0 BNE.S L838 CMPI #0,G424_i_Pan(A4) BNE.S L837 L838: ORI #2048,48(A3) L837: L836: L789: L787: MOVE D7,D0 ADDQ #1,D7 MOVE.L A3,D0 ADDA #800,A3 L785: MOVE D7,D0 CMP G305_ui_Pa(A4),D0 BCS L786(PC) L788: JSR F293_ahzz_(PC) L779: MOVEM.L (A7)+,D4-D7/A2-A3 UNLK A6 RTS L$778: .EQU #-26
411
0.817516
1
0.817516
game-dev
MEDIA
0.588296
game-dev
0.962879
1
0.962879
Esteemed-Innovation/Esteemed-Innovation
1,100
src/main/java/eiteam/esteemedinnovation/engineeringtable/SlotEngineerableUpgradeOnly.java
package eiteam.esteemedinnovation.engineeringtable; import eiteam.esteemedinnovation.api.Engineerable; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.SlotItemHandler; import javax.annotation.Nonnull; public class SlotEngineerableUpgradeOnly extends SlotItemHandler { SlotEngineerableUpgradeOnly(IItemHandler engineerableContainer, int index, int xPosition, int yPosition) { super(engineerableContainer, index, xPosition, yPosition); } @Override public boolean isItemValid(@Nonnull ItemStack check) { ItemStack engineerableStack = getItemHandler().getStackInSlot(0); Item engineerableItem = engineerableStack.getItem(); if (engineerableItem instanceof Engineerable) { Engineerable engineerable = (Engineerable) engineerableItem; return engineerable.canPutInSlot(engineerableStack, getSlotIndex() - 1, check); } return false; } @Override public int getSlotStackLimit() { return 1; } }
411
0.52845
1
0.52845
game-dev
MEDIA
0.822623
game-dev
0.610704
1
0.610704
Cluster-ry/titeenipeli_25
6,821
src/backend/Titeenipeli/Controllers/CtfController.cs
using System.Text.Json; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Titeenipeli.Common.Database.Schema; using Titeenipeli.Common.Database.Services.Interfaces; using Titeenipeli.Common.Enums; using Titeenipeli.Common.Results; using Titeenipeli.Extensions; using Titeenipeli.Grpc.ChangeEntities; using Titeenipeli.InMemoryProvider.UserProvider; using Titeenipeli.Inputs; using Titeenipeli.Services; using Titeenipeli.Services.Grpc; using PowerUp = Titeenipeli.Common.Database.Schema.PowerUp; namespace Titeenipeli.Controllers; [ApiController] [Authorize] [Route("ctf")] public class CtfController : ControllerBase { private readonly ICtfFlagRepositoryService _ctfFlagRepositoryService; private readonly IGuildRepositoryService _guildRepositoryService; private readonly IUserProvider _userProvider; private readonly IJwtService _jwtService; private readonly IMiscGameStateUpdateCoreService _miscGameStateUpdateCoreService; private readonly ILogger<CtfController> _logger; public CtfController(ICtfFlagRepositoryService ctfFlagRepositoryService, IGuildRepositoryService guildRepositoryService, IUserProvider userProvider, IJwtService jwtService, IMiscGameStateUpdateCoreService miscGameStateUpdateCoreService, ILogger<CtfController> logger) { _ctfFlagRepositoryService = ctfFlagRepositoryService; _guildRepositoryService = guildRepositoryService; _userProvider = userProvider; _jwtService = jwtService; _miscGameStateUpdateCoreService = miscGameStateUpdateCoreService; _logger = logger; } [HttpGet] public IActionResult GetCtf() { return Ok("#GOOD_FOR_YOU"); } [HttpPost] [Authorize] public async Task<IActionResult> PostCtf([FromBody] PostCtfInput ctfInput) { var user = HttpContext.GetUser(_jwtService, _userProvider); var guild = _guildRepositoryService.GetById(user.Guild.Id)!; _logger.LogInformation("HTTP POST /ctf user:{user} guild:{guild} flag:{flag} timestamp:{datetime}", user.Id, guild.Id, ctfInput.Token, DateTime.Now); var ctfFlag = _ctfFlagRepositoryService.GetByToken(ctfInput.Token); if (ctfFlag is null) return BadRequest(new ErrorResult { Title = "Invalid flag", Code = ErrorCode.InvalidCtfFlag, Description = "Better luck next time" }); List<CtfFlag> activeCtfFlags; if (guild.ActiveCtfFlags != null) { activeCtfFlags = JsonSerializer.Deserialize<List<CtfFlag>>(guild.ActiveCtfFlags) ?? []; } else { activeCtfFlags = []; } var match = activeCtfFlags?.FirstOrDefault(flag => flag.Id == ctfFlag.Id); if (match is not null) return BadRequest(new ErrorResult { Title = "Flag already used", Code = ErrorCode.InvalidCtfFlag, Description = "Good try" }); activeCtfFlags?.Add(ctfFlag); var newFlags = JsonSerializer.Serialize(activeCtfFlags); guild.ActiveCtfFlags = newFlags; _guildRepositoryService.Update(guild); await _guildRepositoryService.SaveChangesAsync(); if (ctfFlag.Powerup is null) { await HandleGuildPowerUp(user, ctfFlag); } else { HandleUserPowerUp(user, ctfFlag.Powerup); } return Ok(CreateCtfResult(ctfFlag)); } private PostCtfResult CreateCtfResult(CtfFlag flag) { return new PostCtfResult() { Title = "Flag captured", Message = GetGoodEndingMessage(), Benefits = GetBenefits(flag), }; } private static string GetGoodEndingMessage() { string[] messages = [ "You nailed it like a last-minute assignment!", "Flag captured! Time to celebrate with ramen and Netflix.", "Great job! You deserve a break... or maybe just a coffee.", "You did it! Now go binge-watch your favorite series.", "Victory! Just like acing that surprise quiz.", "Well done! Treat yourself to some instant noodles.", "You captured the flag! Now back to procrastinating.", "Awesome! This calls for a pizza party.", "You rock! Time to update your social media status.", "Flag secured! Now you can finally take that nap.", "The cake is a lie, but not this ctf flag!", "You did it! You finally got a ctf token right! Hooray! #WeAreProudOfYou", "You know there is no prize for this, right? Just bragging rights.", "You know that there other stuff to do at titeens'? Like, you know, the game?", "You know that you can't actually eat the flag, right?", "Titeens' is not responsible for any injuries sustained during the capture of this flag." ]; return Random.Shared.GetItems(messages, 1)[0]; } private static List<String> GetBenefits(CtfFlag flag) { var benefits = new List<String>(); if (flag.BaserateMultiplier != 0) benefits.Add($"Base rate limit increased by {flag.BaserateMultiplier}x"); if (flag.FogOfWarIncrease != 0) benefits.Add($"Field of view range increased by {flag.FogOfWarIncrease}"); if (flag.BucketSizeIncrease != 0) benefits.Add($"Pixel bucket size increased by {flag.BucketSizeIncrease}"); if (flag.Powerup != null) { benefits.Add($"You got {flag.Powerup.Name}!\n"); } return benefits; } private async Task HandleGuildPowerUp(User user, CtfFlag ctfFlag) { var guild = user.Guild; if (ctfFlag.BaserateMultiplier != 0) guild.BaseRateLimit *= ctfFlag.BaserateMultiplier; if (ctfFlag.FogOfWarIncrease != 0) guild.FogOfWarDistance += ctfFlag.FogOfWarIncrease; if (ctfFlag.BucketSizeIncrease != 0) guild.PixelBucketSize += ctfFlag.BucketSizeIncrease; _guildRepositoryService.Update(guild); await _guildRepositoryService.SaveChangesAsync(); SendGameUpdate(user); } private void HandleUserPowerUp(User user, PowerUp powerUp) { user.PowerUps.Add(powerUp); _userProvider.Update(user); SendGameUpdate(user); } private void SendGameUpdate(User user) { GrpcMiscGameStateUpdateInput stateUpdate = new() { User = user, MaximumPixelBucket = user.Guild.PixelBucketSize, PowerUps = user.PowerUps.ToList() }; _miscGameStateUpdateCoreService.UpdateMiscGameState(stateUpdate); } }
411
0.887426
1
0.887426
game-dev
MEDIA
0.766095
game-dev,web-backend
0.953901
1
0.953901
CraftTweaker/CraftTweaker-Documentation
2,023
docs_exported/1.19/crafttweaker/docs/forge/api/event/entity/living/LivingHurtEvent.md
# LivingHurtEvent This event is fired just before an entity is hurt. This allows you to modify the damage received, cancel the attack, or run additional effects. The event is cancelable. If the event is canceled, the entity is not hurt The event does not have a result. ## Importing the class It might be required for you to import the package if you encounter any issues (like casting an Array), so better be safe than sorry and add the import at the very top of the file. ```zenscript import crafttweaker.api.event.entity.living.LivingHurtEvent; ``` ## Extending LivingEvent LivingHurtEvent extends [LivingEvent](/forge/api/event/entity/LivingEvent). That means all methods available in [LivingEvent](/forge/api/event/entity/LivingEvent) are also available in LivingHurtEvent ## Methods :::group{name=getAmount} Gets the amount of damage. Returns: The amount of damage. Return Type: float ```zenscript // LivingHurtEvent.getAmount() as float event.getAmount(); ``` ::: :::group{name=getSource} Gets the source of the damage. Returns: The source of the damage. Return Type: [DamageSource](/vanilla/api/world/DamageSource) ```zenscript // LivingHurtEvent.getSource() as DamageSource event.getSource(); ``` ::: :::group{name=setAmount} Sets the amount of damage. ```zenscript // LivingHurtEvent.setAmount(amount as float) event.setAmount(0.5); ``` | Parameter | Type | Description | |-----------|-------|-----------------------| | amount | float | The amount of damage. | ::: ## Properties | Name | Type | Has Getter | Has Setter | Description | |--------|-------------------------------------------------|------------|------------|--------------------------------| | amount | float | true | true | Gets the amount of damage. | | source | [DamageSource](/vanilla/api/world/DamageSource) | true | false | Gets the source of the damage. |
411
0.733212
1
0.733212
game-dev
MEDIA
0.979312
game-dev
0.757168
1
0.757168
magarena/magarena
1,124
release/Magarena/scripts/Volrath_the_Fallen.groovy
[ new MagicPermanentActivation( new MagicActivationHints(MagicTiming.Pump), "Pump" ) { @Override public Iterable<? extends MagicEvent> getCostEvent(final MagicPermanent source) { return [ new MagicPayManaCostEvent(source, "{1}{B}"), new MagicDiscardChosenEvent(source, A_CREATURE_CARD_FROM_HAND) ]; } @Override public MagicEvent getPermanentEvent(final MagicPermanent permanent, final MagicPayedCost payedCost) { return new MagicEvent( permanent, payedCost.getTarget(), this, "SN gets +X/+X until end of turn, where X is the discarded card's converted mana cost." ); } @Override public void executeEvent(final MagicGame game, final MagicEvent event) { final int amount = event.getRefCard().getConvertedCost(); game.logAppendValue(event.getPlayer(),amount); game.doAction(new ChangeTurnPTAction(event.getPermanent(), +amount, +amount)); } } ]
411
0.835044
1
0.835044
game-dev
MEDIA
0.90521
game-dev
0.957384
1
0.957384
ReikaKalseki/RotaryCraft
2,091
ModInterface/ContainerBundledBus.java
/******************************************************************************* * @author Reika Kalseki * * Copyright 2017 * * All rights reserved. * Distribution of the software in any form is only allowed with * explicit, prior permission from the owner. ******************************************************************************/ package Reika.RotaryCraft.ModInterface; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import Reika.DragonAPI.Base.CoreContainer; import Reika.DragonAPI.Instantiable.GUI.Slot.GhostSlot; import Reika.DragonAPI.Libraries.Registry.ReikaItemHelper; public class ContainerBundledBus extends CoreContainer { private TileEntityBundledBus tile; public ContainerBundledBus(EntityPlayer player, TileEntityBundledBus te) { super(player, te); tile = te; for (int i = 0; i < tile.NSLOTS; i++) { int dx = 50+(i%4)*20; int dy = 19+(i/4)*20; this.addSlotToContainer(new GhostSlot(i, dx, dy)); } this.addPlayerInventoryWithOffset(player, 0, 26); } @Override public boolean allowShiftClicking(EntityPlayer player, int slot, ItemStack stack) { return false; } @Override public ItemStack slotClick(int slot, int mouse, int action, EntityPlayer ep) { /* if (slot >= 18 && slot < tile.getSizeInventory()) { ItemStack held = ep.inventory.getItemStack(); tile.setMapping(slot, ReikaItemHelper.getSizedItemStack(held, 1)); return held; } */ if (slot >= 0 && slot < tile.NSLOTS) { ItemStack held = ep.inventory.getItemStack(); int idx = ((Slot)inventorySlots.get(slot)).getSlotIndex(); if (mouse == 0) { tile.setMapping(idx, ReikaItemHelper.getSizedItemStack(held, 1)); } //else if (mouse == 1) { // tile.toggleFuzzy(idx%tile.NSLOTS); //} //this.detectAndSendChanges(); return held; } ItemStack is = super.slotClick(slot, mouse, action, ep); InventoryPlayer ip = ep.inventory; return is; //ReikaJavaLibrary.pConsole(ip.getItemStack()); } }
411
0.816244
1
0.816244
game-dev
MEDIA
0.993036
game-dev
0.939819
1
0.939819
EpicSentry/P2ASW
2,206
src/game/shared/template/weapon_mp5.cpp
//========= Copyright 1996-2008, Valve Corporation, All rights reserved. ============// // // Purpose: // //=====================================================================================// #include "cbase.h" #include "weapon_sdkbase.h" #if defined( CLIENT_DLL ) #define CWeaponMP5 C_WeaponMP5 #include "c_sdk_player.h" #else #include "sdk_player.h" #endif class CWeaponMP5 : public CWeaponSDKBase { public: DECLARE_CLASS( CWeaponMP5, CWeaponSDKBase ); DECLARE_NETWORKCLASS(); DECLARE_PREDICTABLE(); DECLARE_ACTTABLE(); CWeaponMP5(); private: CWeaponMP5( const CWeaponMP5 & ); }; IMPLEMENT_NETWORKCLASS_ALIASED( WeaponMP5, DT_WeaponMP5 ) BEGIN_NETWORK_TABLE( CWeaponMP5, DT_WeaponMP5 ) END_NETWORK_TABLE() BEGIN_PREDICTION_DATA( CWeaponMP5 ) END_PREDICTION_DATA() LINK_ENTITY_TO_CLASS( weapon_mp5, CWeaponMP5 ); PRECACHE_WEAPON_REGISTER( weapon_mp5 ); CWeaponMP5::CWeaponMP5() { } acttable_t CWeaponMP5::m_acttable[] = { { ACT_MP_STAND_IDLE, ACT_DOD_STAND_IDLE_TOMMY, false }, { ACT_MP_CROUCH_IDLE, ACT_DOD_CROUCH_IDLE_TOMMY, false }, //{ ACT_MP_PRONE_IDLE, ACT_DOD_PRONE_AIM_TOMMY, false }, { ACT_MP_RUN, ACT_DOD_RUN_AIM_TOMMY, false }, { ACT_MP_WALK, ACT_DOD_WALK_AIM_TOMMY, false }, { ACT_MP_CROUCHWALK, ACT_DOD_CROUCHWALK_AIM_TOMMY, false }, //{ ACT_MP_PRONE_CRAWL, ACT_DOD_PRONEWALK_IDLE_TOMMY, false }, //{ ACT_SPRINT, ACT_DOD_SPRINT_IDLE_TOMMY, false }, { ACT_MP_ATTACK_STAND_PRIMARYFIRE, ACT_DOD_PRIMARYATTACK_TOMMY, false }, { ACT_MP_ATTACK_CROUCH_PRIMARYFIRE, ACT_DOD_PRIMARYATTACK_TOMMY, false }, //{ ACT_MP_ATTACK_PRONE_PRIMARYFIRE, ACT_DOD_PRIMARYATTACK_PRONE_TOMMY, false }, { ACT_MP_ATTACK_STAND_SECONDARYFIRE, ACT_DOD_SECONDARYATTACK_TOMMY, false }, { ACT_MP_ATTACK_CROUCH_SECONDARYFIRE, ACT_DOD_SECONDARYATTACK_CROUCH_TOMMY, false }, //{ ACT_MP_ATTACK_PRONE_SECONDARYFIRE, ACT_DOD_SECONDARYATTACK_PRONE_TOMMY, false }, { ACT_MP_RELOAD_STAND, ACT_DOD_RELOAD_TOMMY, false }, { ACT_MP_RELOAD_CROUCH, ACT_DOD_RELOAD_CROUCH_TOMMY, false }, //{ ACT_MP_RELOAD_PRONE, ACT_DOD_RELOAD_PRONE_TOMMY, false }, }; IMPLEMENT_ACTTABLE( CWeaponMP5 );
411
0.929992
1
0.929992
game-dev
MEDIA
0.269973
game-dev
0.84044
1
0.84044
miw-upm/IWVG
1,452
doo/src/main/java/ticTacToe/v380/controllers/local/LocalColocateControllerBuilder.java
package ticTacToe.v380.controllers.local; import ticTacToe.v380.models.Game; import ticTacToe.v380.utils.ClosedInterval; class LocalColocateControllerBuilder { private LocalColocateController[][] colocateControllerArray; private Game game; LocalColocateControllerBuilder(Game game) { this.game = game; colocateControllerArray = new LocalColocateController[game.getNumPlayers()][2]; } void build(int users) { assert new ClosedInterval(0, game.getNumPlayers()).includes(users); LocalCoordinateController[][] coordinateController = new LocalCoordinateController[2][2]; for (int i = 0; i < game.getNumPlayers(); i++) { for (int j = 0; j < 2; j++) { if (i < users) { coordinateController[i][j] = new LocalUserCoordinateController( game); } else { coordinateController[i][j] = new LocalRandomCoordinateController( game); } } } for (int i = 0; i < game.getNumPlayers(); i++) { for (int j = 0; j < 2; j++) { if (j == 0) { colocateControllerArray[i][j] = new LocalPutController(game, coordinateController[i][j]); } else { colocateControllerArray[i][j] = new LocalMoveController(game, coordinateController[i][j]); } } } } LocalColocateController getColocateController() { int player = game.take().ordinal(); if (!game.complete()) { return colocateControllerArray[player][0]; } else { return colocateControllerArray[player][1]; } } }
411
0.614522
1
0.614522
game-dev
MEDIA
0.899174
game-dev
0.739589
1
0.739589
sinbad/SUSS
1,773
Source/SUSS/Private/SussAction.cpp
 #include "SussAction.h" #include "SussBrainComponent.h" void USussAction::PerformAction_Implementation(const FSussContext& Context, const TMap<FName, FSussParameter>& Params, TSubclassOf<USussAction> PrevActionClass) { // Subclasses must implement } void USussAction::ContinueAction_Implementation(const FSussContext& Context, const TMap<FName, FSussParameter>& Params) { // Optional for subclasses to use this } void USussAction::CancelAction_Implementation(TSubclassOf<USussAction> InterruptedByActionClass) { // Subclasses must implement } bool USussAction::CanBeInterrupted_Implementation() const { return bAllowInterruptions; } void USussAction::Reset_Implementation() { // Subclasses should implement } UWorld* USussAction::GetWorld() const { if (IsValid(Brain)) { return Brain->GetWorld(); } /// This is to allow this to function in the BP event graph and allow access to Delay() etc return Cast<UWorld>(GetOuter()); } void USussAction::ActionCompleted() { // Allow BP to do something OnActionCompleted(); InternalOnActionCompleted.ExecuteIfBound(this); } void USussAction::SetTemporaryActionScoreAdjustment(float Value, float CooldownTime) { if (IsValid(Brain)) { Brain->SetTemporaryActionScoreAdjustment(BrainActionIndex, Value, CooldownTime); } } void USussAction::AddTemporaryScoreAdjustment(float Value, float CooldownTime) { if (IsValid(Brain)) { Brain->AddTemporaryActionScoreAdjustment(BrainActionIndex, Value, CooldownTime); } } void USussAction::ResetTemporaryScoreAdjustment() { if (IsValid(Brain)) { Brain->ResetTemporaryActionScoreAdjustment(BrainActionIndex); } } void USussAction::DebugLocations_Implementation(TArray<FVector>& OutLocations, bool bIncludeDetails) const { // Subclasses should implement }
411
0.860135
1
0.860135
game-dev
MEDIA
0.35903
game-dev
0.780572
1
0.780572
Isarhamster/chessx
1,997
src/database/streamdatabase.cpp
/**************************************************************************** * Copyright (C) 2016 by Jens Nissen jens-chessx@gmx.net * ****************************************************************************/ #include "streamdatabase.h" #include "tags.h" #include "index.h" using namespace chessx; #if defined(_MSC_VER) && defined(_DEBUG) #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif // _MSC_VER bool StreamDatabase::parseFile() { // Does not do anything return true; } bool StreamDatabase::loadNextGame(GameX& game) { //indexing game positions in the file, game contents are ignored int oldFp = -3; while(!m_file->atEnd()) { IndexBaseType fp = skipJunk(); if(fp == oldFp) { skipLine(); fp = skipJunk(); } oldFp = fp; if(fp != -1) { if(!m_currentLine.isEmpty()) { int index = m_index.add(); m_count = 1+index; parseTagsIntoIndex(); // This will parse the tags into memory game.clear(); game.setResult(ResultUnknown); loadGameHeaders(index, game); QString fen = m_index.tagValue(TagNameFEN, index); QString variant = m_index.tagValue(TagNameVariant, index).toLower(); bool chess960 = (variant.startsWith("fischer", Qt::CaseInsensitive) || variant.endsWith("960")); if(fen != "?") { game.dbSetStartingBoard(fen, chess960); } bool ok = parseMoves(&game); m_index.setValidFlag(index, ok); QString valLength = QString::number((game.plyCount() + 1) / 2); game.setTag(TagNameLength, valLength); setMissingTagsToIndex(game, index); return true; } } } return false; }
411
0.870987
1
0.870987
game-dev
MEDIA
0.876833
game-dev
0.880424
1
0.880424
Shmaug/UnityPlanets
1,610
Assets/PostProcessing/Editor/Utils/EditorResources.cs
using UnityEngine; namespace UnityEditor.PostProcessing { using UnityObject = Object; static class EditorResources { static string m_EditorResourcesPath = string.Empty; internal static string editorResourcesPath { get { if (string.IsNullOrEmpty(m_EditorResourcesPath)) { string path; if (SearchForEditorResourcesPath(out path)) m_EditorResourcesPath = path; else Debug.LogError("Unable to locate editor resources. Make sure the PostProcessing package has been installed correctly."); } return m_EditorResourcesPath; } } internal static T Load<T>(string name) where T : UnityObject { return AssetDatabase.LoadAssetAtPath<T>(editorResourcesPath + name); } static bool SearchForEditorResourcesPath(out string path) { path = string.Empty; string searchStr = "/PostProcessing/Editor Resources/"; string str = null; foreach (var assetPath in AssetDatabase.GetAllAssetPaths()) { if (assetPath.Contains(searchStr)) { str = assetPath; break; } } if (str == null) return false; path = str.Substring(0, str.LastIndexOf(searchStr) + searchStr.Length); return true; } } }
411
0.823489
1
0.823489
game-dev
MEDIA
0.676827
game-dev
0.797989
1
0.797989
cmdbug/TChat
1,847
uikit/src/com/netease/nim/uikit/common/ui/popupmenu/PopupMenuItem.java
package com.netease.nim.uikit.common.ui.popupmenu; import android.content.Context; import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum; /** * 菜单显示条目 */ public class PopupMenuItem { private int tag; private int icon; private String title; private Context context; private String sessionId; private SessionTypeEnum sessionTypeEnum; public PopupMenuItem(int tag, int icon, String title) { this.tag = tag; this.icon = icon; this.title = title; } /** * 只有文字 * * @param tag * @param title */ public PopupMenuItem(int tag, String title) { this(tag, 0, title); } public PopupMenuItem(Context context, int tag, String sessionId, SessionTypeEnum sessionTypeEnum, String title) { this(tag, title); this.context = context; this.sessionId = sessionId; this.sessionTypeEnum = sessionTypeEnum; } public int getTag() { return tag; } public void setTag(int tag) { this.tag = tag; } public int getIcon() { return icon; } public void setIcon(int icon) { this.icon = icon; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Context getContext() { return context; } public void setContext(Context context) { this.context = context; } public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public SessionTypeEnum getSessionTypeEnum() { return sessionTypeEnum; } public void setSessionTypeEnum(SessionTypeEnum sessionTypeEnum) { this.sessionTypeEnum = sessionTypeEnum; } }
411
0.512492
1
0.512492
game-dev
MEDIA
0.372606
game-dev
0.529377
1
0.529377
josh-m/RW-Decompile
2,260
RimWorld/Mineable.cs
using System; using UnityEngine; using Verse; namespace RimWorld { public class Mineable : Building { private float yieldPct; private const float YieldChanceOnNonMiningKill = 0.2f; public override void ExposeData() { base.ExposeData(); Scribe_Values.Look<float>(ref this.yieldPct, "yieldPct", 0f, false); } public override void PreApplyDamage(ref DamageInfo dinfo, out bool absorbed) { base.PreApplyDamage(ref dinfo, out absorbed); if (absorbed) { return; } if (this.def.building.mineableThing != null && this.def.building.mineableYieldWasteable && dinfo.Def == DamageDefOf.Mining && dinfo.Instigator != null && dinfo.Instigator is Pawn) { this.Notify_TookMiningDamage(GenMath.RoundRandom(dinfo.Amount), (Pawn)dinfo.Instigator); } absorbed = false; } public void DestroyMined(Pawn pawn) { Map map = base.Map; base.Destroy(DestroyMode.KillFinalize); this.TrySpawnYield(map, this.yieldPct, true, pawn); } public override void Destroy(DestroyMode mode) { Map map = base.Map; base.Destroy(mode); if (mode == DestroyMode.KillFinalize) { this.TrySpawnYield(map, 0.2f, false, null); } } private void TrySpawnYield(Map map, float yieldChance, bool moteOnWaste, Pawn pawn) { if (this.def.building.mineableThing == null) { return; } if (Rand.Value > this.def.building.mineableDropChance) { return; } int num = Mathf.Max(1, Mathf.RoundToInt((float)this.def.building.mineableYield * Find.Storyteller.difficulty.mineYieldFactor)); if (this.def.building.mineableYieldWasteable) { num = Mathf.Max(1, GenMath.RoundRandom((float)num * this.yieldPct)); } Thing thing = ThingMaker.MakeThing(this.def.building.mineableThing, null); thing.stackCount = num; GenSpawn.Spawn(thing, base.Position, map, WipeMode.Vanish); if ((pawn == null || !pawn.IsColonist) && thing.def.EverHaulable && !thing.def.designateHaulable) { thing.SetForbidden(true, true); } } public void Notify_TookMiningDamage(int amount, Pawn miner) { int num = Mathf.Min(amount, this.HitPoints); float num2 = (float)num / (float)base.MaxHitPoints; this.yieldPct += num2 * miner.GetStatValue(StatDefOf.MiningYield, true); } } }
411
0.860585
1
0.860585
game-dev
MEDIA
0.993355
game-dev
0.961632
1
0.961632
Goob-Station/Goob-Station
8,221
Content.Benchmarks/ComponentQueryBenchmark.cs
// SPDX-FileCopyrightText: 2025 Aiden <28298836+Aidenkrz@users.noreply.github.com> // SPDX-FileCopyrightText: 2025 Leon Friedrich <60421075+ElectroJr@users.noreply.github.com> // // SPDX-License-Identifier: AGPL-3.0-or-later #nullable enable using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Configs; using Content.IntegrationTests; using Content.IntegrationTests.Pair; using Content.Shared.Clothing.Components; using Content.Shared.Doors.Components; using Content.Shared.Item; using Robust.Shared; using Robust.Shared.Analyzers; using Robust.Shared.EntitySerialization; using Robust.Shared.EntitySerialization.Systems; using Robust.Shared.GameObjects; using Robust.Shared.Map.Components; using Robust.Shared.Random; using Robust.Shared.Utility; namespace Content.Benchmarks; /// <summary> /// Benchmarks for comparing the speed of various component fetching/lookup related methods, including directed event /// subscriptions /// </summary> [Virtual] [GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)] [CategoriesColumn] public class ComponentQueryBenchmark { public const string Map = "Maps/saltern.yml"; private TestPair _pair = default!; private IEntityManager _entMan = default!; private EntityQuery<ItemComponent> _itemQuery; private EntityQuery<ClothingComponent> _clothingQuery; private EntityQuery<MapComponent> _mapQuery; private EntityUid[] _items = default!; [GlobalSetup] public void Setup() { ProgramShared.PathOffset = "../../../../"; PoolManager.Startup(typeof(QueryBenchSystem).Assembly); _pair = PoolManager.GetServerClient().GetAwaiter().GetResult(); _entMan = _pair.Server.ResolveDependency<IEntityManager>(); _itemQuery = _entMan.GetEntityQuery<ItemComponent>(); _clothingQuery = _entMan.GetEntityQuery<ClothingComponent>(); _mapQuery = _entMan.GetEntityQuery<MapComponent>(); _pair.Server.ResolveDependency<IRobustRandom>().SetSeed(42); _pair.Server.WaitPost(() => { var map = new ResPath(Map); var opts = DeserializationOptions.Default with {InitializeMaps = true}; if (!_entMan.System<MapLoaderSystem>().TryLoadMap(map, out _, out _, opts)) throw new Exception("Map load failed"); }).GetAwaiter().GetResult(); _items = new EntityUid[_entMan.Count<ItemComponent>()]; var i = 0; var enumerator = _entMan.AllEntityQueryEnumerator<ItemComponent>(); while (enumerator.MoveNext(out var uid, out _)) { _items[i++] = uid; } } [GlobalCleanup] public async Task Cleanup() { await _pair.DisposeAsync(); PoolManager.Shutdown(); } #region TryComp /// <summary> /// Baseline TryComp benchmark. When the benchmark was created, around 40% of the items were clothing. /// </summary> [Benchmark(Baseline = true)] [BenchmarkCategory("TryComp")] public int TryComp() { var hashCode = 0; foreach (var uid in _items) { if (_clothingQuery.TryGetComponent(uid, out var clothing)) hashCode = HashCode.Combine(hashCode, clothing.GetHashCode()); } return hashCode; } /// <summary> /// Variant of <see cref="TryComp"/> that is meant to always fail to get a component. /// </summary> [Benchmark] [BenchmarkCategory("TryComp")] public int TryCompFail() { var hashCode = 0; foreach (var uid in _items) { if (_mapQuery.TryGetComponent(uid, out var map)) hashCode = HashCode.Combine(hashCode, map.GetHashCode()); } return hashCode; } /// <summary> /// Variant of <see cref="TryComp"/> that is meant to always succeed getting a component. /// </summary> [Benchmark] [BenchmarkCategory("TryComp")] public int TryCompSucceed() { var hashCode = 0; foreach (var uid in _items) { if (_itemQuery.TryGetComponent(uid, out var item)) hashCode = HashCode.Combine(hashCode, item.GetHashCode()); } return hashCode; } /// <summary> /// Variant of <see cref="TryComp"/> that uses `Resolve()` to try get the component. /// </summary> [Benchmark] [BenchmarkCategory("TryComp")] public int Resolve() { var hashCode = 0; foreach (var uid in _items) { DoResolve(uid, ref hashCode); } return hashCode; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void DoResolve(EntityUid uid, ref int hash, ClothingComponent? clothing = null) { if (_clothingQuery.Resolve(uid, ref clothing, false)) hash = HashCode.Combine(hash, clothing.GetHashCode()); } #endregion #region Enumeration [Benchmark] [BenchmarkCategory("Item Enumerator")] public int SingleItemEnumerator() { var hashCode = 0; var enumerator = _entMan.AllEntityQueryEnumerator<ItemComponent>(); while (enumerator.MoveNext(out var item)) { hashCode = HashCode.Combine(hashCode, item.GetHashCode()); } return hashCode; } [Benchmark] [BenchmarkCategory("Item Enumerator")] public int DoubleItemEnumerator() { var hashCode = 0; var enumerator = _entMan.AllEntityQueryEnumerator<ClothingComponent, ItemComponent>(); while (enumerator.MoveNext(out _, out var item)) { hashCode = HashCode.Combine(hashCode, item.GetHashCode()); } return hashCode; } [Benchmark] [BenchmarkCategory("Item Enumerator")] public int TripleItemEnumerator() { var hashCode = 0; var enumerator = _entMan.AllEntityQueryEnumerator<ClothingComponent, ItemComponent, TransformComponent>(); while (enumerator.MoveNext(out _, out _, out var xform)) { hashCode = HashCode.Combine(hashCode, xform.GetHashCode()); } return hashCode; } [Benchmark] [BenchmarkCategory("Airlock Enumerator")] public int SingleAirlockEnumerator() { var hashCode = 0; var enumerator = _entMan.AllEntityQueryEnumerator<AirlockComponent>(); while (enumerator.MoveNext(out var airlock)) { hashCode = HashCode.Combine(hashCode, airlock.GetHashCode()); } return hashCode; } [Benchmark] [BenchmarkCategory("Airlock Enumerator")] public int DoubleAirlockEnumerator() { var hashCode = 0; var enumerator = _entMan.AllEntityQueryEnumerator<AirlockComponent, DoorComponent>(); while (enumerator.MoveNext(out _, out var door)) { hashCode = HashCode.Combine(hashCode, door.GetHashCode()); } return hashCode; } [Benchmark] [BenchmarkCategory("Airlock Enumerator")] public int TripleAirlockEnumerator() { var hashCode = 0; var enumerator = _entMan.AllEntityQueryEnumerator<AirlockComponent, DoorComponent, TransformComponent>(); while (enumerator.MoveNext(out _, out _, out var xform)) { hashCode = HashCode.Combine(hashCode, xform.GetHashCode()); } return hashCode; } #endregion [Benchmark(Baseline = true)] [BenchmarkCategory("Events")] public int StructEvents() { var ev = new QueryBenchEvent(); foreach (var uid in _items) { _entMan.EventBus.RaiseLocalEvent(uid, ref ev); } return ev.HashCode; } } [ByRefEvent] public struct QueryBenchEvent { public int HashCode; } public sealed class QueryBenchSystem : EntitySystem { public override void Initialize() { base.Initialize(); SubscribeLocalEvent<ClothingComponent, QueryBenchEvent>(OnEvent); } private void OnEvent(EntityUid uid, ClothingComponent component, ref QueryBenchEvent args) { args.HashCode = HashCode.Combine(args.HashCode, component.GetHashCode()); } }
411
0.863239
1
0.863239
game-dev
MEDIA
0.266821
game-dev
0.953378
1
0.953378
maekitalo/cxxtools
67,714
include/cxxtools/signal.tpp
// BEGIN_Signal 10 /** Multicast Signal A Signal can be connected to multiple targets. The return value of the target(s) is/are ignored. */ template <class A1 = Void, class A2 = Void, class A3 = Void, class A4 = Void, class A5 = Void, class A6 = Void, class A7 = Void, class A8 = Void, class A9 = Void, class A10 = Void> class Signal : public SignalBase { public: typedef Invokable<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10> InvokableT; public: /** Connects slot to this signal, such that firing this signal will invoke slot. */ template <typename R> Connection connect(const BasicSlot<R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>& slot) { return Connection(*this, slot.clone() ); } /** The converse of connect(). */ template <typename R> void disconnect(const BasicSlot<R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>& slot) { this->disconnectSlot(slot); } /** Invokes all slots connected to this signal, in an undefined order. Their return values are ignored. Calling of connected slots will be interrupted if a slot deletes this Signal object or throws an exception. */ inline void send(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8, A9 a9, A10 a10) const { // The sentry will set the Signal to the sending state and // reset it to not-sending upon destruction. In the sending // state, removing connection will leave invalid connections // in the connection list to keep the iterator valid, but mark // the Signal dirty. If the Signal is dirty, all invalid // connections will be removed by the Sentry when it destructs.. SignalBase::Sentry sentry(this); std::list<Connection>::const_iterator it = Connectable::connections().begin(); std::list<Connection>::const_iterator end = Connectable::connections().end(); for(; it != end; ++it) { if( false == it->valid() || &( it->sender() ) != this ) continue; // The following scenarios must be considered when the // slot is called: // - The slot might get deleted and thus disconnected from // this signal // - The slot might delete this signal and we must end // calling any slots immediately // - A new Connection might get added to this Signal in // the slot const InvokableT* invokable = static_cast<const InvokableT*>( it->slot().callable() ); invokable->invoke(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10); // if this signal gets deleted by the slot, the Sentry // will be detached. In this case we bail out immediately if( !sentry ) return; } } /** Same as send(...). */ inline void operator()(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8, A9 a9, A10 a10) const { this->send(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10); } }; // END_Signal 10 // BEGIN_SignalSlot 10 /** SignalSlot is a "slot wrapper" for Signal objects. That is, it effectively converts a Signal object into a Slot object, so that it can be used as the target of another Signal. This allows chaining of Signals. */ template <class A1 = Void, class A2 = Void, class A3 = Void, class A4 = Void, class A5 = Void, class A6 = Void, class A7 = Void, class A8 = Void, class A9 = Void, class A10 = Void> class SignalSlot : public BasicSlot<void, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10> { public: /** Wraps signal. */ SignalSlot(Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>& signal) : _method( signal, &Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>::send ) {} /** Creates a clone of this object and returns it. Caller owns the returned object. */ Slot* clone() const { return new SignalSlot(*this); } /** Returns a pointer to this object's internal Callable object. */ virtual const void* callable() const { return &_method; } /** ??? */ virtual void onConnect(const Connection& c) { _method.object().onConnectionOpen(c); } /** ??? */ virtual void onDisconnect(const Connection& c) { _method.object().onConnectionClose(c); } /** returns true if this object and rhs are equivalent. */ virtual bool equals(const Slot& rhs) const { const SignalSlot* ss = dynamic_cast<const SignalSlot*>(&rhs); return ss ? (_method == ss->_method) : false; } private: mutable ConstMethod<void, Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10 > _method; }; /** Creates a SignalSlot object from an equivalent Signal. */ template <class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10> SignalSlot<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10> slot( Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10> & signal ) { return SignalSlot<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>( signal ); } /** Connects the given signal and slot objects and returns that Connection object (which can normally be ignored). */ template <typename R, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10> Connection connect(Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>& signal, const BasicSlot<R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>& slot) { return signal.connect( slot ); } //! Connects a Signal to a function. template <typename R, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10> Connection connect(Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>& signal, R(*func)(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)) { return signal.connect(slot(func)); } //! Connects a Signal to a std::function. template <typename R, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10> Connection connect(Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>& signal, std::function<R(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)>& func) { return signal.connect(slot(func)); } //! Connects a Signal to a member function. template <typename R, class BaseT, typename ClassT, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10> Connection connect(Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>& signal, BaseT& object, R(ClassT::*memFunc)(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)) { return signal.connect(slot(object, memFunc)); } //! Connects a Signal to a const member function. template <typename R, class BaseT, typename ClassT, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10> Connection connect(Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>& signal, BaseT& object, R(ClassT::*memFunc)(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10) const) { return signal.connect(slot(object, memFunc)); } /// Connects a Signal to another Signal /** template <class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10> Connection connect(Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>& sender, Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>& receiver) { return sender.connect(slot(receiver)); } */ template <typename R, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10> void disconnect(Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>& signal, const BasicSlot<R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>& slot) { return signal.disconnect( slot ); } template <typename R, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10> void disconnect(Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>& signal, R(*func)(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)) { signal.disconnect( slot(func) ); } template <typename R, typename BaseT, typename ClassT, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10> void disconnect(Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>& signal, BaseT & object, R(ClassT::*memFunc)(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)) { signal.disconnect( slot( object, memFunc ) ); } template <typename R, class BaseT, typename ClassT, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10> void disconnect(Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>& signal, BaseT& object, R(ClassT::*memFunc)(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10) const) { signal.disconnect( slot( object, memFunc ) ); } template <typename R, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10> void disconnect( Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>& sender, Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>& receiver ) { sender.disconnect( slot(receiver) ); } /** Connects a Signal to another Signal. */ template <class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10> Connection connect(Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>& sender, Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>& receiver) { return sender.connect(slot(receiver)); } // END_SignalSlot 10 // BEGIN_Signal 9 // specialization template <class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9> class Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9, Void> : public SignalBase { public: typedef Invokable<A1, A2, A3, A4, A5, A6, A7, A8, A9, Void> InvokableT; public: /** Connects slot to this signal, such that firing this signal will invoke slot. */ template <typename R> Connection connect(const BasicSlot<R, A1, A2, A3, A4, A5, A6, A7, A8, A9, Void>& slot) { return Connection(*this, slot.clone() ); } /** The converse of connect(). */ template <typename R> void disconnect(const BasicSlot<R, A1, A2, A3, A4, A5, A6, A7, A8, A9, Void>& slot) { this->disconnectSlot(slot); } /** Invokes all slots connected to this signal, in an undefined order. Their return values are ignored. Calling of connected slots will be interrupted if a slot deletes this Signal object or throws an exception. */ inline void send(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8, A9 a9) const { // The sentry will set the Signal to the sending state and // reset it to not-sending upon destruction. In the sending // state, removing connection will leave invalid connections // in the connection list to keep the iterator valid, but mark // the Signal dirty. If the Signal is dirty, all invalid // connections will be removed by the Sentry when it destructs.. SignalBase::Sentry sentry(this); std::list<Connection>::const_iterator it = Connectable::connections().begin(); std::list<Connection>::const_iterator end = Connectable::connections().end(); for(; it != end; ++it) { if( false == it->valid() || &( it->sender() ) != this ) continue; // The following scenarios must be considered when the // slot is called: // - The slot might get deleted and thus disconnected from // this signal // - The slot might delete this signal and we must end // calling any slots immediately // - A new Connection might get added to this Signal in // the slot const InvokableT* invokable = static_cast<const InvokableT*>( it->slot().callable() ); invokable->invoke(a1, a2, a3, a4, a5, a6, a7, a8, a9); // if this signal gets deleted by the slot, the Sentry // will be detached. In this case we bail out immediately if( !sentry ) return; } } /** Same as send(...). */ inline void operator()(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8, A9 a9) const { this->send(a1, a2, a3, a4, a5, a6, a7, a8, a9); } }; // END_Signal 9 // BEGIN_SignalSlot 9 //! Connects a Signal to a function. template <typename F, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9> Connection connect(Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9>& signal, F&& func) { return signal.connect(FunctionSlot<void, A1, A2, A3, A4, A5, A6, A7, A8, A9>(std::function<void(A1, A2, A3, A4, A5, A6, A7, A8, A9)>(func))); } //! Connects a Signal to a member function. template <typename R, class BaseT, typename ClassT, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9> Connection connect(Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9>& signal, BaseT& object, R(ClassT::*memFunc)(A1, A2, A3, A4, A5, A6, A7, A8, A9)) { return signal.connect(slot(object, memFunc)); } //! Connects a Signal to a const member function. template <typename R, class BaseT, typename ClassT, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9> Connection connect(Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9>& signal, BaseT& object, R(ClassT::*memFunc)(A1, A2, A3, A4, A5, A6, A7, A8, A9) const) { return signal.connect(slot(object, memFunc)); } /// Connects a Signal to another Signal /** template <class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9> Connection connect(Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9>& sender, Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9>& receiver) { return sender.connect(slot(receiver)); } */ template <typename R, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9> void disconnect(Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9>& signal, R(*func)(A1, A2, A3, A4, A5, A6, A7, A8, A9)) { signal.disconnect( slot(func) ); } template <typename R, typename BaseT, typename ClassT, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9> void disconnect(Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9>& signal, BaseT & object, R(ClassT::*memFunc)(A1, A2, A3, A4, A5, A6, A7, A8, A9)) { signal.disconnect( slot( object, memFunc ) ); } template <typename R, class BaseT, typename ClassT, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9> void disconnect(Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9>& signal, BaseT& object, R(ClassT::*memFunc)(A1, A2, A3, A4, A5, A6, A7, A8, A9) const) { signal.disconnect( slot( object, memFunc ) ); } template <typename R, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9> void disconnect( Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9>& sender, Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9>& receiver ) { sender.disconnect( slot(receiver) ); } /** Connects a Signal to another Signal. */ template <class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9> Connection connect(Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9>& sender, Signal<A1, A2, A3, A4, A5, A6, A7, A8, A9>& receiver) { return sender.connect(slot(receiver)); } // END_SignalSlot 9 // BEGIN_Signal 8 // specialization template <class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8> class Signal<A1, A2, A3, A4, A5, A6, A7, A8, Void, Void> : public SignalBase { public: typedef Invokable<A1, A2, A3, A4, A5, A6, A7, A8, Void, Void> InvokableT; public: /** Connects slot to this signal, such that firing this signal will invoke slot. */ template <typename R> Connection connect(const BasicSlot<R, A1, A2, A3, A4, A5, A6, A7, A8, Void, Void>& slot) { return Connection(*this, slot.clone() ); } /** The converse of connect(). */ template <typename R> void disconnect(const BasicSlot<R, A1, A2, A3, A4, A5, A6, A7, A8, Void, Void>& slot) { this->disconnectSlot(slot); } /** Invokes all slots connected to this signal, in an undefined order. Their return values are ignored. Calling of connected slots will be interrupted if a slot deletes this Signal object or throws an exception. */ inline void send(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8) const { // The sentry will set the Signal to the sending state and // reset it to not-sending upon destruction. In the sending // state, removing connection will leave invalid connections // in the connection list to keep the iterator valid, but mark // the Signal dirty. If the Signal is dirty, all invalid // connections will be removed by the Sentry when it destructs.. SignalBase::Sentry sentry(this); std::list<Connection>::const_iterator it = Connectable::connections().begin(); std::list<Connection>::const_iterator end = Connectable::connections().end(); for(; it != end; ++it) { if( false == it->valid() || &( it->sender() ) != this ) continue; // The following scenarios must be considered when the // slot is called: // - The slot might get deleted and thus disconnected from // this signal // - The slot might delete this signal and we must end // calling any slots immediately // - A new Connection might get added to this Signal in // the slot const InvokableT* invokable = static_cast<const InvokableT*>( it->slot().callable() ); invokable->invoke(a1, a2, a3, a4, a5, a6, a7, a8); // if this signal gets deleted by the slot, the Sentry // will be detached. In this case we bail out immediately if( !sentry ) return; } } /** Same as send(...). */ inline void operator()(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8) const { this->send(a1, a2, a3, a4, a5, a6, a7, a8); } }; // END_Signal 8 // BEGIN_SignalSlot 8 //! Connects a Signal to a function. template <typename F, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8> Connection connect(Signal<A1, A2, A3, A4, A5, A6, A7, A8>& signal, F&& func) { return signal.connect(FunctionSlot<void, A1, A2, A3, A4, A5, A6, A7, A8>(std::function<void(A1, A2, A3, A4, A5, A6, A7, A8)>(func))); } //! Connects a Signal to a member function. template <typename R, class BaseT, typename ClassT, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8> Connection connect(Signal<A1, A2, A3, A4, A5, A6, A7, A8>& signal, BaseT& object, R(ClassT::*memFunc)(A1, A2, A3, A4, A5, A6, A7, A8)) { return signal.connect(slot(object, memFunc)); } //! Connects a Signal to a const member function. template <typename R, class BaseT, typename ClassT, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8> Connection connect(Signal<A1, A2, A3, A4, A5, A6, A7, A8>& signal, BaseT& object, R(ClassT::*memFunc)(A1, A2, A3, A4, A5, A6, A7, A8) const) { return signal.connect(slot(object, memFunc)); } /// Connects a Signal to another Signal /** template <class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8> Connection connect(Signal<A1, A2, A3, A4, A5, A6, A7, A8>& sender, Signal<A1, A2, A3, A4, A5, A6, A7, A8>& receiver) { return sender.connect(slot(receiver)); } */ template <typename R, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8> void disconnect(Signal<A1, A2, A3, A4, A5, A6, A7, A8>& signal, R(*func)(A1, A2, A3, A4, A5, A6, A7, A8)) { signal.disconnect( slot(func) ); } template <typename R, typename BaseT, typename ClassT, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8> void disconnect(Signal<A1, A2, A3, A4, A5, A6, A7, A8>& signal, BaseT & object, R(ClassT::*memFunc)(A1, A2, A3, A4, A5, A6, A7, A8)) { signal.disconnect( slot( object, memFunc ) ); } template <typename R, class BaseT, typename ClassT, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8> void disconnect(Signal<A1, A2, A3, A4, A5, A6, A7, A8>& signal, BaseT& object, R(ClassT::*memFunc)(A1, A2, A3, A4, A5, A6, A7, A8) const) { signal.disconnect( slot( object, memFunc ) ); } template <typename R, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8> void disconnect( Signal<A1, A2, A3, A4, A5, A6, A7, A8>& sender, Signal<A1, A2, A3, A4, A5, A6, A7, A8>& receiver ) { sender.disconnect( slot(receiver) ); } /** Connects a Signal to another Signal. */ template <class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8> Connection connect(Signal<A1, A2, A3, A4, A5, A6, A7, A8>& sender, Signal<A1, A2, A3, A4, A5, A6, A7, A8>& receiver) { return sender.connect(slot(receiver)); } // END_SignalSlot 8 // BEGIN_Signal 7 // specialization template <class A1, class A2, class A3, class A4, class A5, class A6, class A7> class Signal<A1, A2, A3, A4, A5, A6, A7, Void, Void, Void> : public SignalBase { public: typedef Invokable<A1, A2, A3, A4, A5, A6, A7, Void, Void, Void> InvokableT; public: /** Connects slot to this signal, such that firing this signal will invoke slot. */ template <typename R> Connection connect(const BasicSlot<R, A1, A2, A3, A4, A5, A6, A7, Void, Void, Void>& slot) { return Connection(*this, slot.clone() ); } /** The converse of connect(). */ template <typename R> void disconnect(const BasicSlot<R, A1, A2, A3, A4, A5, A6, A7, Void, Void, Void>& slot) { this->disconnectSlot(slot); } /** Invokes all slots connected to this signal, in an undefined order. Their return values are ignored. Calling of connected slots will be interrupted if a slot deletes this Signal object or throws an exception. */ inline void send(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7) const { // The sentry will set the Signal to the sending state and // reset it to not-sending upon destruction. In the sending // state, removing connection will leave invalid connections // in the connection list to keep the iterator valid, but mark // the Signal dirty. If the Signal is dirty, all invalid // connections will be removed by the Sentry when it destructs.. SignalBase::Sentry sentry(this); std::list<Connection>::const_iterator it = Connectable::connections().begin(); std::list<Connection>::const_iterator end = Connectable::connections().end(); for(; it != end; ++it) { if( false == it->valid() || &( it->sender() ) != this ) continue; // The following scenarios must be considered when the // slot is called: // - The slot might get deleted and thus disconnected from // this signal // - The slot might delete this signal and we must end // calling any slots immediately // - A new Connection might get added to this Signal in // the slot const InvokableT* invokable = static_cast<const InvokableT*>( it->slot().callable() ); invokable->invoke(a1, a2, a3, a4, a5, a6, a7); // if this signal gets deleted by the slot, the Sentry // will be detached. In this case we bail out immediately if( !sentry ) return; } } /** Same as send(...). */ inline void operator()(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7) const { this->send(a1, a2, a3, a4, a5, a6, a7); } }; // END_Signal 7 // BEGIN_SignalSlot 7 //! Connects a Signal to a function. template <typename F, class A1, class A2, class A3, class A4, class A5, class A6, class A7> Connection connect(Signal<A1, A2, A3, A4, A5, A6, A7>& signal, F&& func) { return signal.connect(FunctionSlot<void, A1, A2, A3, A4, A5, A6, A7>(std::function<void(A1, A2, A3, A4, A5, A6, A7)>(func))); } //! Connects a Signal to a member function. template <typename R, class BaseT, typename ClassT, class A1, class A2, class A3, class A4, class A5, class A6, class A7> Connection connect(Signal<A1, A2, A3, A4, A5, A6, A7>& signal, BaseT& object, R(ClassT::*memFunc)(A1, A2, A3, A4, A5, A6, A7)) { return signal.connect(slot(object, memFunc)); } //! Connects a Signal to a const member function. template <typename R, class BaseT, typename ClassT, class A1, class A2, class A3, class A4, class A5, class A6, class A7> Connection connect(Signal<A1, A2, A3, A4, A5, A6, A7>& signal, BaseT& object, R(ClassT::*memFunc)(A1, A2, A3, A4, A5, A6, A7) const) { return signal.connect(slot(object, memFunc)); } /// Connects a Signal to another Signal /** template <class A1, class A2, class A3, class A4, class A5, class A6, class A7> Connection connect(Signal<A1, A2, A3, A4, A5, A6, A7>& sender, Signal<A1, A2, A3, A4, A5, A6, A7>& receiver) { return sender.connect(slot(receiver)); } */ template <typename R, class A1, class A2, class A3, class A4, class A5, class A6, class A7> void disconnect(Signal<A1, A2, A3, A4, A5, A6, A7>& signal, R(*func)(A1, A2, A3, A4, A5, A6, A7)) { signal.disconnect( slot(func) ); } template <typename R, typename BaseT, typename ClassT, class A1, class A2, class A3, class A4, class A5, class A6, class A7> void disconnect(Signal<A1, A2, A3, A4, A5, A6, A7>& signal, BaseT & object, R(ClassT::*memFunc)(A1, A2, A3, A4, A5, A6, A7)) { signal.disconnect( slot( object, memFunc ) ); } template <typename R, class BaseT, typename ClassT, class A1, class A2, class A3, class A4, class A5, class A6, class A7> void disconnect(Signal<A1, A2, A3, A4, A5, A6, A7>& signal, BaseT& object, R(ClassT::*memFunc)(A1, A2, A3, A4, A5, A6, A7) const) { signal.disconnect( slot( object, memFunc ) ); } template <typename R, class A1, class A2, class A3, class A4, class A5, class A6, class A7> void disconnect( Signal<A1, A2, A3, A4, A5, A6, A7>& sender, Signal<A1, A2, A3, A4, A5, A6, A7>& receiver ) { sender.disconnect( slot(receiver) ); } /** Connects a Signal to another Signal. */ template <class A1, class A2, class A3, class A4, class A5, class A6, class A7> Connection connect(Signal<A1, A2, A3, A4, A5, A6, A7>& sender, Signal<A1, A2, A3, A4, A5, A6, A7>& receiver) { return sender.connect(slot(receiver)); } // END_SignalSlot 7 // BEGIN_Signal 6 // specialization template <class A1, class A2, class A3, class A4, class A5, class A6> class Signal<A1, A2, A3, A4, A5, A6, Void, Void, Void, Void> : public SignalBase { public: typedef Invokable<A1, A2, A3, A4, A5, A6, Void, Void, Void, Void> InvokableT; public: /** Connects slot to this signal, such that firing this signal will invoke slot. */ template <typename R> Connection connect(const BasicSlot<R, A1, A2, A3, A4, A5, A6, Void, Void, Void, Void>& slot) { return Connection(*this, slot.clone() ); } /** The converse of connect(). */ template <typename R> void disconnect(const BasicSlot<R, A1, A2, A3, A4, A5, A6, Void, Void, Void, Void>& slot) { this->disconnectSlot(slot); } /** Invokes all slots connected to this signal, in an undefined order. Their return values are ignored. Calling of connected slots will be interrupted if a slot deletes this Signal object or throws an exception. */ inline void send(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) const { // The sentry will set the Signal to the sending state and // reset it to not-sending upon destruction. In the sending // state, removing connection will leave invalid connections // in the connection list to keep the iterator valid, but mark // the Signal dirty. If the Signal is dirty, all invalid // connections will be removed by the Sentry when it destructs.. SignalBase::Sentry sentry(this); std::list<Connection>::const_iterator it = Connectable::connections().begin(); std::list<Connection>::const_iterator end = Connectable::connections().end(); for(; it != end; ++it) { if( false == it->valid() || &( it->sender() ) != this ) continue; // The following scenarios must be considered when the // slot is called: // - The slot might get deleted and thus disconnected from // this signal // - The slot might delete this signal and we must end // calling any slots immediately // - A new Connection might get added to this Signal in // the slot const InvokableT* invokable = static_cast<const InvokableT*>( it->slot().callable() ); invokable->invoke(a1, a2, a3, a4, a5, a6); // if this signal gets deleted by the slot, the Sentry // will be detached. In this case we bail out immediately if( !sentry ) return; } } /** Same as send(...). */ inline void operator()(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) const { this->send(a1, a2, a3, a4, a5, a6); } }; // END_Signal 6 // BEGIN_SignalSlot 6 //! Connects a Signal to a function. template <typename F, class A1, class A2, class A3, class A4, class A5, class A6> Connection connect(Signal<A1, A2, A3, A4, A5, A6>& signal, F&& func) { return signal.connect(FunctionSlot<void, A1, A2, A3, A4, A5, A6>(std::function<void(A1, A2, A3, A4, A5, A6)>(func))); } //! Connects a Signal to a member function. template <typename R, class BaseT, typename ClassT, class A1, class A2, class A3, class A4, class A5, class A6> Connection connect(Signal<A1, A2, A3, A4, A5, A6>& signal, BaseT& object, R(ClassT::*memFunc)(A1, A2, A3, A4, A5, A6)) { return signal.connect(slot(object, memFunc)); } //! Connects a Signal to a const member function. template <typename R, class BaseT, typename ClassT, class A1, class A2, class A3, class A4, class A5, class A6> Connection connect(Signal<A1, A2, A3, A4, A5, A6>& signal, BaseT& object, R(ClassT::*memFunc)(A1, A2, A3, A4, A5, A6) const) { return signal.connect(slot(object, memFunc)); } /// Connects a Signal to another Signal /** template <class A1, class A2, class A3, class A4, class A5, class A6> Connection connect(Signal<A1, A2, A3, A4, A5, A6>& sender, Signal<A1, A2, A3, A4, A5, A6>& receiver) { return sender.connect(slot(receiver)); } */ template <typename R, class A1, class A2, class A3, class A4, class A5, class A6> void disconnect(Signal<A1, A2, A3, A4, A5, A6>& signal, R(*func)(A1, A2, A3, A4, A5, A6)) { signal.disconnect( slot(func) ); } template <typename R, typename BaseT, typename ClassT, class A1, class A2, class A3, class A4, class A5, class A6> void disconnect(Signal<A1, A2, A3, A4, A5, A6>& signal, BaseT & object, R(ClassT::*memFunc)(A1, A2, A3, A4, A5, A6)) { signal.disconnect( slot( object, memFunc ) ); } template <typename R, class BaseT, typename ClassT, class A1, class A2, class A3, class A4, class A5, class A6> void disconnect(Signal<A1, A2, A3, A4, A5, A6>& signal, BaseT& object, R(ClassT::*memFunc)(A1, A2, A3, A4, A5, A6) const) { signal.disconnect( slot( object, memFunc ) ); } template <typename R, class A1, class A2, class A3, class A4, class A5, class A6> void disconnect( Signal<A1, A2, A3, A4, A5, A6>& sender, Signal<A1, A2, A3, A4, A5, A6>& receiver ) { sender.disconnect( slot(receiver) ); } /** Connects a Signal to another Signal. */ template <class A1, class A2, class A3, class A4, class A5, class A6> Connection connect(Signal<A1, A2, A3, A4, A5, A6>& sender, Signal<A1, A2, A3, A4, A5, A6>& receiver) { return sender.connect(slot(receiver)); } // END_SignalSlot 6 // BEGIN_Signal 5 // specialization template <class A1, class A2, class A3, class A4, class A5> class Signal<A1, A2, A3, A4, A5, Void, Void, Void, Void, Void> : public SignalBase { public: typedef Invokable<A1, A2, A3, A4, A5, Void, Void, Void, Void, Void> InvokableT; public: /** Connects slot to this signal, such that firing this signal will invoke slot. */ template <typename R> Connection connect(const BasicSlot<R, A1, A2, A3, A4, A5, Void, Void, Void, Void, Void>& slot) { return Connection(*this, slot.clone() ); } /** The converse of connect(). */ template <typename R> void disconnect(const BasicSlot<R, A1, A2, A3, A4, A5, Void, Void, Void, Void, Void>& slot) { this->disconnectSlot(slot); } /** Invokes all slots connected to this signal, in an undefined order. Their return values are ignored. Calling of connected slots will be interrupted if a slot deletes this Signal object or throws an exception. */ inline void send(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) const { // The sentry will set the Signal to the sending state and // reset it to not-sending upon destruction. In the sending // state, removing connection will leave invalid connections // in the connection list to keep the iterator valid, but mark // the Signal dirty. If the Signal is dirty, all invalid // connections will be removed by the Sentry when it destructs.. SignalBase::Sentry sentry(this); std::list<Connection>::const_iterator it = Connectable::connections().begin(); std::list<Connection>::const_iterator end = Connectable::connections().end(); for(; it != end; ++it) { if( false == it->valid() || &( it->sender() ) != this ) continue; // The following scenarios must be considered when the // slot is called: // - The slot might get deleted and thus disconnected from // this signal // - The slot might delete this signal and we must end // calling any slots immediately // - A new Connection might get added to this Signal in // the slot const InvokableT* invokable = static_cast<const InvokableT*>( it->slot().callable() ); invokable->invoke(a1, a2, a3, a4, a5); // if this signal gets deleted by the slot, the Sentry // will be detached. In this case we bail out immediately if( !sentry ) return; } } /** Same as send(...). */ inline void operator()(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) const { this->send(a1, a2, a3, a4, a5); } }; // END_Signal 5 // BEGIN_SignalSlot 5 //! Connects a Signal to a function. template <typename F, class A1, class A2, class A3, class A4, class A5> Connection connect(Signal<A1, A2, A3, A4, A5>& signal, F&& func) { return signal.connect(FunctionSlot<void, A1, A2, A3, A4, A5>(std::function<void(A1, A2, A3, A4, A5)>(func))); } //! Connects a Signal to a member function. template <typename R, class BaseT, typename ClassT, class A1, class A2, class A3, class A4, class A5> Connection connect(Signal<A1, A2, A3, A4, A5>& signal, BaseT& object, R(ClassT::*memFunc)(A1, A2, A3, A4, A5)) { return signal.connect(slot(object, memFunc)); } //! Connects a Signal to a const member function. template <typename R, class BaseT, typename ClassT, class A1, class A2, class A3, class A4, class A5> Connection connect(Signal<A1, A2, A3, A4, A5>& signal, BaseT& object, R(ClassT::*memFunc)(A1, A2, A3, A4, A5) const) { return signal.connect(slot(object, memFunc)); } /// Connects a Signal to another Signal /** template <class A1, class A2, class A3, class A4, class A5> Connection connect(Signal<A1, A2, A3, A4, A5>& sender, Signal<A1, A2, A3, A4, A5>& receiver) { return sender.connect(slot(receiver)); } */ template <typename R, class A1, class A2, class A3, class A4, class A5> void disconnect(Signal<A1, A2, A3, A4, A5>& signal, R(*func)(A1, A2, A3, A4, A5)) { signal.disconnect( slot(func) ); } template <typename R, typename BaseT, typename ClassT, class A1, class A2, class A3, class A4, class A5> void disconnect(Signal<A1, A2, A3, A4, A5>& signal, BaseT & object, R(ClassT::*memFunc)(A1, A2, A3, A4, A5)) { signal.disconnect( slot( object, memFunc ) ); } template <typename R, class BaseT, typename ClassT, class A1, class A2, class A3, class A4, class A5> void disconnect(Signal<A1, A2, A3, A4, A5>& signal, BaseT& object, R(ClassT::*memFunc)(A1, A2, A3, A4, A5) const) { signal.disconnect( slot( object, memFunc ) ); } template <typename R, class A1, class A2, class A3, class A4, class A5> void disconnect( Signal<A1, A2, A3, A4, A5>& sender, Signal<A1, A2, A3, A4, A5>& receiver ) { sender.disconnect( slot(receiver) ); } /** Connects a Signal to another Signal. */ template <class A1, class A2, class A3, class A4, class A5> Connection connect(Signal<A1, A2, A3, A4, A5>& sender, Signal<A1, A2, A3, A4, A5>& receiver) { return sender.connect(slot(receiver)); } // END_SignalSlot 5 // BEGIN_Signal 4 // specialization template <class A1, class A2, class A3, class A4> class Signal<A1, A2, A3, A4, Void, Void, Void, Void, Void, Void> : public SignalBase { public: typedef Invokable<A1, A2, A3, A4, Void, Void, Void, Void, Void, Void> InvokableT; public: /** Connects slot to this signal, such that firing this signal will invoke slot. */ template <typename R> Connection connect(const BasicSlot<R, A1, A2, A3, A4, Void, Void, Void, Void, Void, Void>& slot) { return Connection(*this, slot.clone() ); } /** The converse of connect(). */ template <typename R> void disconnect(const BasicSlot<R, A1, A2, A3, A4, Void, Void, Void, Void, Void, Void>& slot) { this->disconnectSlot(slot); } /** Invokes all slots connected to this signal, in an undefined order. Their return values are ignored. Calling of connected slots will be interrupted if a slot deletes this Signal object or throws an exception. */ inline void send(A1 a1, A2 a2, A3 a3, A4 a4) const { // The sentry will set the Signal to the sending state and // reset it to not-sending upon destruction. In the sending // state, removing connection will leave invalid connections // in the connection list to keep the iterator valid, but mark // the Signal dirty. If the Signal is dirty, all invalid // connections will be removed by the Sentry when it destructs.. SignalBase::Sentry sentry(this); std::list<Connection>::const_iterator it = Connectable::connections().begin(); std::list<Connection>::const_iterator end = Connectable::connections().end(); for(; it != end; ++it) { if( false == it->valid() || &( it->sender() ) != this ) continue; // The following scenarios must be considered when the // slot is called: // - The slot might get deleted and thus disconnected from // this signal // - The slot might delete this signal and we must end // calling any slots immediately // - A new Connection might get added to this Signal in // the slot const InvokableT* invokable = static_cast<const InvokableT*>( it->slot().callable() ); invokable->invoke(a1, a2, a3, a4); // if this signal gets deleted by the slot, the Sentry // will be detached. In this case we bail out immediately if( !sentry ) return; } } /** Same as send(...). */ inline void operator()(A1 a1, A2 a2, A3 a3, A4 a4) const { this->send(a1, a2, a3, a4); } }; // END_Signal 4 // BEGIN_SignalSlot 4 //! Connects a Signal to a function. template <typename F, class A1, class A2, class A3, class A4> Connection connect(Signal<A1, A2, A3, A4>& signal, F&& func) { return signal.connect(FunctionSlot<void, A1, A2, A3, A4>(std::function<void(A1, A2, A3, A4)>(func))); } //! Connects a Signal to a member function. template <typename R, class BaseT, typename ClassT, class A1, class A2, class A3, class A4> Connection connect(Signal<A1, A2, A3, A4>& signal, BaseT& object, R(ClassT::*memFunc)(A1, A2, A3, A4)) { return signal.connect(slot(object, memFunc)); } //! Connects a Signal to a const member function. template <typename R, class BaseT, typename ClassT, class A1, class A2, class A3, class A4> Connection connect(Signal<A1, A2, A3, A4>& signal, BaseT& object, R(ClassT::*memFunc)(A1, A2, A3, A4) const) { return signal.connect(slot(object, memFunc)); } /// Connects a Signal to another Signal /** template <class A1, class A2, class A3, class A4> Connection connect(Signal<A1, A2, A3, A4>& sender, Signal<A1, A2, A3, A4>& receiver) { return sender.connect(slot(receiver)); } */ template <typename R, class A1, class A2, class A3, class A4> void disconnect(Signal<A1, A2, A3, A4>& signal, R(*func)(A1, A2, A3, A4)) { signal.disconnect( slot(func) ); } template <typename R, typename BaseT, typename ClassT, class A1, class A2, class A3, class A4> void disconnect(Signal<A1, A2, A3, A4>& signal, BaseT & object, R(ClassT::*memFunc)(A1, A2, A3, A4)) { signal.disconnect( slot( object, memFunc ) ); } template <typename R, class BaseT, typename ClassT, class A1, class A2, class A3, class A4> void disconnect(Signal<A1, A2, A3, A4>& signal, BaseT& object, R(ClassT::*memFunc)(A1, A2, A3, A4) const) { signal.disconnect( slot( object, memFunc ) ); } template <typename R, class A1, class A2, class A3, class A4> void disconnect( Signal<A1, A2, A3, A4>& sender, Signal<A1, A2, A3, A4>& receiver ) { sender.disconnect( slot(receiver) ); } /** Connects a Signal to another Signal. */ template <class A1, class A2, class A3, class A4> Connection connect(Signal<A1, A2, A3, A4>& sender, Signal<A1, A2, A3, A4>& receiver) { return sender.connect(slot(receiver)); } // END_SignalSlot 4 // BEGIN_Signal 3 // specialization template <class A1, class A2, class A3> class Signal<A1, A2, A3, Void, Void, Void, Void, Void, Void, Void> : public SignalBase { public: typedef Invokable<A1, A2, A3, Void, Void, Void, Void, Void, Void, Void> InvokableT; public: /** Connects slot to this signal, such that firing this signal will invoke slot. */ template <typename R> Connection connect(const BasicSlot<R, A1, A2, A3, Void, Void, Void, Void, Void, Void, Void>& slot) { return Connection(*this, slot.clone() ); } /** The converse of connect(). */ template <typename R> void disconnect(const BasicSlot<R, A1, A2, A3, Void, Void, Void, Void, Void, Void, Void>& slot) { this->disconnectSlot(slot); } /** Invokes all slots connected to this signal, in an undefined order. Their return values are ignored. Calling of connected slots will be interrupted if a slot deletes this Signal object or throws an exception. */ inline void send(A1 a1, A2 a2, A3 a3) const { // The sentry will set the Signal to the sending state and // reset it to not-sending upon destruction. In the sending // state, removing connection will leave invalid connections // in the connection list to keep the iterator valid, but mark // the Signal dirty. If the Signal is dirty, all invalid // connections will be removed by the Sentry when it destructs.. SignalBase::Sentry sentry(this); std::list<Connection>::const_iterator it = Connectable::connections().begin(); std::list<Connection>::const_iterator end = Connectable::connections().end(); for(; it != end; ++it) { if( false == it->valid() || &( it->sender() ) != this ) continue; // The following scenarios must be considered when the // slot is called: // - The slot might get deleted and thus disconnected from // this signal // - The slot might delete this signal and we must end // calling any slots immediately // - A new Connection might get added to this Signal in // the slot const InvokableT* invokable = static_cast<const InvokableT*>( it->slot().callable() ); invokable->invoke(a1, a2, a3); // if this signal gets deleted by the slot, the Sentry // will be detached. In this case we bail out immediately if( !sentry ) return; } } /** Same as send(...). */ inline void operator()(A1 a1, A2 a2, A3 a3) const { this->send(a1, a2, a3); } }; // END_Signal 3 // BEGIN_SignalSlot 3 //! Connects a Signal to a function. template <typename F, class A1, class A2, class A3> Connection connect(Signal<A1, A2, A3>& signal, F&& func) { return signal.connect(FunctionSlot<void, A1, A2, A3>(std::function<void(A1, A2, A3)>(func))); } //! Connects a Signal to a member function. template <typename R, class BaseT, typename ClassT, class A1, class A2, class A3> Connection connect(Signal<A1, A2, A3>& signal, BaseT& object, R(ClassT::*memFunc)(A1, A2, A3)) { return signal.connect(slot(object, memFunc)); } //! Connects a Signal to a const member function. template <typename R, class BaseT, typename ClassT, class A1, class A2, class A3> Connection connect(Signal<A1, A2, A3>& signal, BaseT& object, R(ClassT::*memFunc)(A1, A2, A3) const) { return signal.connect(slot(object, memFunc)); } /// Connects a Signal to another Signal /** template <class A1, class A2, class A3> Connection connect(Signal<A1, A2, A3>& sender, Signal<A1, A2, A3>& receiver) { return sender.connect(slot(receiver)); } */ template <typename R, class A1, class A2, class A3> void disconnect(Signal<A1, A2, A3>& signal, R(*func)(A1, A2, A3)) { signal.disconnect( slot(func) ); } template <typename R, typename BaseT, typename ClassT, class A1, class A2, class A3> void disconnect(Signal<A1, A2, A3>& signal, BaseT & object, R(ClassT::*memFunc)(A1, A2, A3)) { signal.disconnect( slot( object, memFunc ) ); } template <typename R, class BaseT, typename ClassT, class A1, class A2, class A3> void disconnect(Signal<A1, A2, A3>& signal, BaseT& object, R(ClassT::*memFunc)(A1, A2, A3) const) { signal.disconnect( slot( object, memFunc ) ); } template <typename R, class A1, class A2, class A3> void disconnect( Signal<A1, A2, A3>& sender, Signal<A1, A2, A3>& receiver ) { sender.disconnect( slot(receiver) ); } /** Connects a Signal to another Signal. */ template <class A1, class A2, class A3> Connection connect(Signal<A1, A2, A3>& sender, Signal<A1, A2, A3>& receiver) { return sender.connect(slot(receiver)); } // END_SignalSlot 3 // BEGIN_Signal 2 // specialization template <class A1, class A2> class Signal<A1, A2, Void, Void, Void, Void, Void, Void, Void, Void> : public SignalBase { public: typedef Invokable<A1, A2, Void, Void, Void, Void, Void, Void, Void, Void> InvokableT; public: /** Connects slot to this signal, such that firing this signal will invoke slot. */ template <typename R> Connection connect(const BasicSlot<R, A1, A2, Void, Void, Void, Void, Void, Void, Void, Void>& slot) { return Connection(*this, slot.clone() ); } /** The converse of connect(). */ template <typename R> void disconnect(const BasicSlot<R, A1, A2, Void, Void, Void, Void, Void, Void, Void, Void>& slot) { this->disconnectSlot(slot); } /** Invokes all slots connected to this signal, in an undefined order. Their return values are ignored. Calling of connected slots will be interrupted if a slot deletes this Signal object or throws an exception. */ inline void send(A1 a1, A2 a2) const { // The sentry will set the Signal to the sending state and // reset it to not-sending upon destruction. In the sending // state, removing connection will leave invalid connections // in the connection list to keep the iterator valid, but mark // the Signal dirty. If the Signal is dirty, all invalid // connections will be removed by the Sentry when it destructs.. SignalBase::Sentry sentry(this); std::list<Connection>::const_iterator it = Connectable::connections().begin(); std::list<Connection>::const_iterator end = Connectable::connections().end(); for(; it != end; ++it) { if( false == it->valid() || &( it->sender() ) != this ) continue; // The following scenarios must be considered when the // slot is called: // - The slot might get deleted and thus disconnected from // this signal // - The slot might delete this signal and we must end // calling any slots immediately // - A new Connection might get added to this Signal in // the slot const InvokableT* invokable = static_cast<const InvokableT*>( it->slot().callable() ); invokable->invoke(a1, a2); // if this signal gets deleted by the slot, the Sentry // will be detached. In this case we bail out immediately if( !sentry ) return; } } /** Same as send(...). */ inline void operator()(A1 a1, A2 a2) const { this->send(a1, a2); } }; // END_Signal 2 // BEGIN_SignalSlot 2 //! Connects a Signal to a function. template <typename F, class A1, class A2> Connection connect(Signal<A1, A2>& signal, F&& func) { return signal.connect(FunctionSlot<void, A1, A2>(std::function<void(A1, A2)>(func))); } //! Connects a Signal to a member function. template <typename R, class BaseT, typename ClassT, class A1, class A2> Connection connect(Signal<A1, A2>& signal, BaseT& object, R(ClassT::*memFunc)(A1, A2)) { return signal.connect(slot(object, memFunc)); } //! Connects a Signal to a const member function. template <typename R, class BaseT, typename ClassT, class A1, class A2> Connection connect(Signal<A1, A2>& signal, BaseT& object, R(ClassT::*memFunc)(A1, A2) const) { return signal.connect(slot(object, memFunc)); } /// Connects a Signal to another Signal /** template <class A1, class A2> Connection connect(Signal<A1, A2>& sender, Signal<A1, A2>& receiver) { return sender.connect(slot(receiver)); } */ template <typename R, class A1, class A2> void disconnect(Signal<A1, A2>& signal, R(*func)(A1, A2)) { signal.disconnect( slot(func) ); } template <typename R, typename BaseT, typename ClassT, class A1, class A2> void disconnect(Signal<A1, A2>& signal, BaseT & object, R(ClassT::*memFunc)(A1, A2)) { signal.disconnect( slot( object, memFunc ) ); } template <typename R, class BaseT, typename ClassT, class A1, class A2> void disconnect(Signal<A1, A2>& signal, BaseT& object, R(ClassT::*memFunc)(A1, A2) const) { signal.disconnect( slot( object, memFunc ) ); } template <typename R, class A1, class A2> void disconnect( Signal<A1, A2>& sender, Signal<A1, A2>& receiver ) { sender.disconnect( slot(receiver) ); } /** Connects a Signal to another Signal. */ template <class A1, class A2> Connection connect(Signal<A1, A2>& sender, Signal<A1, A2>& receiver) { return sender.connect(slot(receiver)); } // END_SignalSlot 2 // BEGIN_Signal 1 // specialization template <class A1> class Signal<A1, Void, Void, Void, Void, Void, Void, Void, Void, Void> : public SignalBase { public: typedef Invokable<A1, Void, Void, Void, Void, Void, Void, Void, Void, Void> InvokableT; public: /** Connects slot to this signal, such that firing this signal will invoke slot. */ template <typename R> Connection connect(const BasicSlot<R, A1, Void, Void, Void, Void, Void, Void, Void, Void, Void>& slot) { return Connection(*this, slot.clone() ); } /** The converse of connect(). */ template <typename R> void disconnect(const BasicSlot<R, A1, Void, Void, Void, Void, Void, Void, Void, Void, Void>& slot) { this->disconnectSlot(slot); } /** Invokes all slots connected to this signal, in an undefined order. Their return values are ignored. Calling of connected slots will be interrupted if a slot deletes this Signal object or throws an exception. */ inline void send(A1 a1) const { // The sentry will set the Signal to the sending state and // reset it to not-sending upon destruction. In the sending // state, removing connection will leave invalid connections // in the connection list to keep the iterator valid, but mark // the Signal dirty. If the Signal is dirty, all invalid // connections will be removed by the Sentry when it destructs.. SignalBase::Sentry sentry(this); std::list<Connection>::const_iterator it = Connectable::connections().begin(); std::list<Connection>::const_iterator end = Connectable::connections().end(); for(; it != end; ++it) { if( false == it->valid() || &( it->sender() ) != this ) continue; // The following scenarios must be considered when the // slot is called: // - The slot might get deleted and thus disconnected from // this signal // - The slot might delete this signal and we must end // calling any slots immediately // - A new Connection might get added to this Signal in // the slot const InvokableT* invokable = static_cast<const InvokableT*>( it->slot().callable() ); invokable->invoke(a1); // if this signal gets deleted by the slot, the Sentry // will be detached. In this case we bail out immediately if( !sentry ) return; } } /** Same as send(...). */ inline void operator()(A1 a1) const { this->send(a1); } }; // END_Signal 1 // BEGIN_SignalSlot 1 //! Connects a Signal to a function. template <typename F, class A1> Connection connect(Signal<A1>& signal, F&& func) { return signal.connect(FunctionSlot<void, A1>(std::function<void(A1)>(func))); } //! Connects a Signal to a member function. template <typename R, class BaseT, typename ClassT, class A1> Connection connect(Signal<A1>& signal, BaseT& object, R(ClassT::*memFunc)(A1)) { return signal.connect(slot(object, memFunc)); } //! Connects a Signal to a const member function. template <typename R, class BaseT, typename ClassT, class A1> Connection connect(Signal<A1>& signal, BaseT& object, R(ClassT::*memFunc)(A1) const) { return signal.connect(slot(object, memFunc)); } /// Connects a Signal to another Signal /** template <class A1> Connection connect(Signal<A1>& sender, Signal<A1>& receiver) { return sender.connect(slot(receiver)); } */ template <typename R, class A1> void disconnect(Signal<A1>& signal, R(*func)(A1)) { signal.disconnect( slot(func) ); } template <typename R, typename BaseT, typename ClassT, class A1> void disconnect(Signal<A1>& signal, BaseT & object, R(ClassT::*memFunc)(A1)) { signal.disconnect( slot( object, memFunc ) ); } template <typename R, class BaseT, typename ClassT, class A1> void disconnect(Signal<A1>& signal, BaseT& object, R(ClassT::*memFunc)(A1) const) { signal.disconnect( slot( object, memFunc ) ); } template <typename R, class A1> void disconnect( Signal<A1>& sender, Signal<A1>& receiver ) { sender.disconnect( slot(receiver) ); } /** Connects a Signal to another Signal. */ template <class A1> Connection connect(Signal<A1>& sender, Signal<A1>& receiver) { return sender.connect(slot(receiver)); } // END_SignalSlot 1 // BEGIN_Signal 0 // specialization template <> class Signal<Void, Void, Void, Void, Void, Void, Void, Void, Void, Void> : public SignalBase { public: typedef Invokable<Void, Void, Void, Void, Void, Void, Void, Void, Void, Void> InvokableT; public: /** Connects slot to this signal, such that firing this signal will invoke slot. */ template <typename R> Connection connect(const BasicSlot<R, Void, Void, Void, Void, Void, Void, Void, Void, Void, Void>& slot) { return Connection(*this, slot.clone() ); } /** The converse of connect(). */ template <typename R> void disconnect(const BasicSlot<R, Void, Void, Void, Void, Void, Void, Void, Void, Void, Void>& slot) { this->disconnectSlot(slot); } /** Invokes all slots connected to this signal, in an undefined order. Their return values are ignored. Calling of connected slots will be interrupted if a slot deletes this Signal object or throws an exception. */ inline void send() const { // The sentry will set the Signal to the sending state and // reset it to not-sending upon destruction. In the sending // state, removing connection will leave invalid connections // in the connection list to keep the iterator valid, but mark // the Signal dirty. If the Signal is dirty, all invalid // connections will be removed by the Sentry when it destructs.. SignalBase::Sentry sentry(this); std::list<Connection>::const_iterator it = Connectable::connections().begin(); std::list<Connection>::const_iterator end = Connectable::connections().end(); for(; it != end; ++it) { if( false == it->valid() || &( it->sender() ) != this ) continue; // The following scenarios must be considered when the // slot is called: // - The slot might get deleted and thus disconnected from // this signal // - The slot might delete this signal and we must end // calling any slots immediately // - A new Connection might get added to this Signal in // the slot const InvokableT* invokable = static_cast<const InvokableT*>( it->slot().callable() ); invokable->invoke(); // if this signal gets deleted by the slot, the Sentry // will be detached. In this case we bail out immediately if( !sentry ) return; } } /** Same as send(...). */ inline void operator()() const { this->send(); } }; // END_Signal 0 // BEGIN_SignalSlot 0 //! Connects a Signal to a function. template <typename F> Connection connect(Signal<>& signal, F&& func) { return signal.connect(FunctionSlot<void>(std::function<void()>(func))); } template <typename R, class BaseT, typename ClassT> Connection connect(Signal<>& signal, BaseT& object, R(ClassT::*memFunc)()) { return signal.connect(slot(object, memFunc)); } //! Connects a Signal to a const member function. template <typename R, class BaseT, typename ClassT> Connection connect(Signal<>& signal, BaseT& object, R(ClassT::*memFunc)() const) { return signal.connect(slot(object, memFunc)); } template <typename R> void disconnect(Signal<>& signal, R(*func)()) { signal.disconnect( slot(func) ); } template <typename R, typename BaseT, typename ClassT> void disconnect(Signal<>& signal, BaseT & object, R(ClassT::*memFunc)()) { signal.disconnect( slot( object, memFunc ) ); } template <typename R, class BaseT, typename ClassT> void disconnect(Signal<>& signal, BaseT& object, R(ClassT::*memFunc)() const) { signal.disconnect( slot( object, memFunc ) ); } template <typename R> void disconnect( Signal<>& sender, Signal<>& receiver ) { sender.disconnect( slot(receiver) ); } /** Connects a Signal to another Signal. */ inline Connection connect(Signal<>& sender, Signal<>& receiver) { return sender.connect(slot(receiver)); } // END_SignalSlot 0
411
0.883453
1
0.883453
game-dev
MEDIA
0.162252
game-dev
0.81985
1
0.81985
GameCult/Aetheria-Economy
1,645
Assets/Plugins/UniRx/Scripts/UnityEngineBridge/UnityGraphicExtensions.cs
// for uGUI(from 4.6) #if !(UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5) using System; using UnityEngine.Events; using UnityEngine.UI; namespace UniRx { public static partial class UnityGraphicExtensions { public static IObservable<Unit> DirtyLayoutCallbackAsObservable(this Graphic graphic) { return Observable.Create<Unit>(observer => { UnityAction registerHandler = () => observer.OnNext(Unit.Default); graphic.RegisterDirtyLayoutCallback(registerHandler); return Disposable.Create(() => graphic.UnregisterDirtyLayoutCallback(registerHandler)); }); } public static IObservable<Unit> DirtyMaterialCallbackAsObservable(this Graphic graphic) { return Observable.Create<Unit>(observer => { UnityAction registerHandler = () => observer.OnNext(Unit.Default); graphic.RegisterDirtyMaterialCallback(registerHandler); return Disposable.Create(() => graphic.UnregisterDirtyMaterialCallback(registerHandler)); }); } public static IObservable<Unit> DirtyVerticesCallbackAsObservable(this Graphic graphic) { return Observable.Create<Unit>(observer => { UnityAction registerHandler = () => observer.OnNext(Unit.Default); graphic.RegisterDirtyVerticesCallback(registerHandler); return Disposable.Create(() => graphic.UnregisterDirtyVerticesCallback(registerHandler)); }); } } } #endif
411
0.531838
1
0.531838
game-dev
MEDIA
0.54075
game-dev
0.894361
1
0.894361
lizhi5753186/OnlineStore
4,317
OnlineStore.Infrastructure/PagedResult.cs
using System.Collections; using System.Collections.Generic; namespace OnlineStore.Infrastructure { /// <summary> /// 分页结果 /// </summary> public class PagedResult<T> : IEnumerable<T>, ICollection<T> { public static readonly PagedResult<T> EmptyPagedResult = new PagedResult<T>(0, 0, 0, 0, null); #region Public Properties // 总记录数 public int TotalRecords { get; set; } // 总页数 public int TotalPages { get; set; } // 每页的记录数 public int PageSize { get; set; } // 页码 public int PageNumber { get; set; } /// <summary> /// 获取或设置当前页码的记录 /// </summary> public List<T> PageData { get; set; } #endregion #region Ctor public PagedResult() { this.PageData =new List<T>(); } public PagedResult(int totalRecords, int totalPages, int pageSize, int pageNumber, List<T> data) { this.TotalPages = totalPages; this.TotalRecords = totalRecords; this.PageSize = pageSize; this.PageNumber = pageNumber; this.PageData = data; } #endregion #region Override Object Members /// <summary> /// 确定指定的Object是否等于当前的Object。 /// </summary> /// <param name="obj">要与当前对象进行比较的对象。</param> /// <returns>如果指定的Object与当前Object相等,则返回true,否则返回false。</returns> public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) return true; if (obj == (object)null) return false; var other = obj as PagedResult<T>; if (ReferenceEquals(other, (object)null)) return false; return this.TotalPages == other.TotalPages && this.TotalRecords == other.TotalRecords && this.PageNumber == other.PageNumber && this.PageSize == other.PageSize && this.PageData == other.PageData; } /// <summary> /// 用作特定类型的哈希函数。 /// </summary> /// <returns>当前Object的哈希代码。</returns> public override int GetHashCode() { return this.TotalPages.GetHashCode() ^ this.TotalRecords.GetHashCode() ^ this.PageNumber.GetHashCode() ^ this.PageSize.GetHashCode(); } /// <summary> /// 确定两个对象是否相等。 /// </summary> /// <param name="a">待确定的第一个对象。</param> /// <param name="b">待确定的另一个对象。</param> /// <returns>如果两者相等,则返回true,否则返回false。</returns> public static bool operator ==(PagedResult<T> a, PagedResult<T> b) { if (ReferenceEquals(a, b)) return true; if ((object)a == null || (object)b == null) return false; return a.Equals(b); } /// <summary> /// 确定两个对象是否不相等。 /// </summary> /// <param name="a">待确定的第一个对象。</param> /// <param name="b">待确定的另一个对象。</param> /// <returns>如果两者不相等,则返回true,否则返回false。</returns> public static bool operator !=(PagedResult<T> a, PagedResult<T> b) { return !(a == b); } #endregion #region IEnumberable Members public IEnumerator<T> GetEnumerator() { return PageData.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return PageData.GetEnumerator(); } #endregion #region ICollection Members public void Add(T item) { PageData.Add(item); } public void Clear() { PageData.Clear(); } public bool Contains(T item) { return PageData.Contains(item); } public void CopyTo(T[] array, int arrayIndex) { PageData.CopyTo(array, arrayIndex); } public int Count { get { return PageData.Count; } } public bool IsReadOnly { get { return false; } } public bool Remove(T item) { return PageData.Remove(item); } #endregion } }
411
0.914788
1
0.914788
game-dev
MEDIA
0.247224
game-dev
0.975095
1
0.975095
P3pp3rF1y/AncientWarfare2
2,234
src/main/java/net/shadowmage/ancientwarfare/automation/container/ContainerWorksiteQuarryBounds.java
package net.shadowmage.ancientwarfare.automation.container; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.math.BlockPos; import net.shadowmage.ancientwarfare.automation.tile.worksite.WorkSiteQuarry; import net.shadowmage.ancientwarfare.core.container.ContainerTileBase; import net.shadowmage.ancientwarfare.core.interfaces.IBoundedSite; import net.shadowmage.ancientwarfare.core.util.BlockTools; public class ContainerWorksiteQuarryBounds extends ContainerTileBase<WorkSiteQuarry> { public int maxHeight; public ContainerWorksiteQuarryBounds(EntityPlayer player, int x, int y, int z) { super(player, x, y, z); maxHeight = tileEntity.height; } @Override public void sendInitData() { NBTTagCompound tag = new NBTTagCompound(); tag.setInteger("height", maxHeight); sendDataToClient(tag); } @Override public void handlePacketData(NBTTagCompound tag) { maxHeight = tag.getInteger("height"); if (tag.hasKey("guiClosed")) { getWorksite().onBoundsAdjusted(); getWorksite().onPostBoundsAdjusted(); BlockTools.notifyBlockUpdate(player.world, getPos()); } if (!player.world.isRemote) { tileEntity.height = maxHeight; tileEntity.markDirty();//mark dirty so it get saved to nbt } refreshGui(); } public void sendSettingsToServer() { NBTTagCompound tag = new NBTTagCompound(); tag.setInteger("height", maxHeight); sendDataToServer(tag); } @Override public void detectAndSendChanges() { super.detectAndSendChanges(); boolean send = false; if (maxHeight != tileEntity.height) { maxHeight = tileEntity.height; send = true; } if (send) { sendInitData(); } } public void onClose(boolean boundsAdjusted) { NBTTagCompound tag = new NBTTagCompound(); tag.setBoolean("guiClosed", true); if (boundsAdjusted) { tag.setInteger("height", maxHeight); } sendDataToServer(tag); } public BlockPos getPos() { return tileEntity.getPos(); } public int getX() { return tileEntity.getPos().getX(); } public int getY() { return tileEntity.getPos().getY(); } public int getZ() { return tileEntity.getPos().getZ(); } public IBoundedSite getWorksite() { return tileEntity; } }
411
0.835667
1
0.835667
game-dev
MEDIA
0.963731
game-dev
0.959812
1
0.959812
DragonBones/DragonBonesCPP
17,576
DragonBones/src/dragonBones/animation/Animation.cpp
#include "Animation.h" #include "../model/DisplayData.h" #include "../model/AnimationConfig.h" #include "../model/AnimationData.h" #include "../armature/Armature.h" #include "../armature/Bone.h" #include "../armature/Slot.h" #include "AnimationState.h" DRAGONBONES_NAMESPACE_BEGIN void Animation::_onClear() { for (const auto animationState : _animationStates) { animationState->returnToPool(); } if (_animationConfig != nullptr) { _animationConfig->returnToPool(); } timeScale = 1.0f; _animationDirty = false; _inheritTimeScale = 1.0f; _animations.clear(); _animationNames.clear(); _animationStates.clear(); _armature = nullptr; _animationConfig = nullptr; _lastAnimationState = nullptr; } void Animation::_fadeOut(AnimationConfig* animationConfig) { switch (animationConfig->fadeOutMode) { case AnimationFadeOutMode::SameLayer: for (const auto animationState : _animationStates) { if (animationState->layer == (unsigned)animationConfig->layer) { animationState->fadeOut(animationConfig->fadeOutTime, animationConfig->pauseFadeOut); } } break; case AnimationFadeOutMode::SameGroup: for (const auto animationState : _animationStates) { if (animationState->group == animationConfig->group) { animationState->fadeOut(animationConfig->fadeOutTime, animationConfig->pauseFadeOut); } } break; case AnimationFadeOutMode::SameLayerAndGroup: for (const auto animationState : _animationStates) { if (animationState->layer == (unsigned)animationConfig->layer && animationState->group == animationConfig->group) { animationState->fadeOut(animationConfig->fadeOutTime, animationConfig->pauseFadeOut); } } break; case AnimationFadeOutMode::All: for (const auto animationState : _animationStates) { animationState->fadeOut(animationConfig->fadeOutTime, animationConfig->pauseFadeOut); } break; case AnimationFadeOutMode::None: case AnimationFadeOutMode::Single: default: break; } } void Animation::init(Armature* armature) { if (_armature != nullptr) { return; } _armature = armature; _animationConfig = BaseObject::borrowObject<AnimationConfig>(); } void Animation::advanceTime(float passedTime) { if (passedTime < 0.0f) { passedTime = -passedTime; } if (_armature->inheritAnimation && _armature->_parent != nullptr) // Inherit parent animation timeScale. { _inheritTimeScale = _armature->_parent->_armature->getAnimation()->_inheritTimeScale * timeScale; } else { _inheritTimeScale = timeScale; } if (_inheritTimeScale != 1.0f) { passedTime *= _inheritTimeScale; } const auto animationStateCount = _animationStates.size(); if (animationStateCount == 1) { const auto animationState = _animationStates[0]; if (animationState->_fadeState > 0 && animationState->_subFadeState > 0) { _armature->_dragonBones->bufferObject(animationState); _animationStates.clear(); _lastAnimationState = nullptr; } else { const auto animationData = animationState->_animationData; const auto cacheFrameRate = animationData->cacheFrameRate; if (_animationDirty && cacheFrameRate > 0.0f) // Update cachedFrameIndices. { _animationDirty = false; for (const auto bone : _armature->getBones()) { bone->_cachedFrameIndices = animationData->getBoneCachedFrameIndices(bone->getName()); } for (const auto slot : _armature->getSlots()) { const auto rawDisplayDatas = slot->getRawDisplayDatas(); if (rawDisplayDatas != nullptr && !(*rawDisplayDatas).empty()) { const auto rawDsplayData = (*rawDisplayDatas)[0]; if (rawDsplayData != nullptr) { if (rawDsplayData->parent == _armature->getArmatureData()->defaultSkin) { slot->_cachedFrameIndices = animationData->getSlotCachedFrameIndices(slot->getName()); continue; } } } slot->_cachedFrameIndices = nullptr; } } animationState->advanceTime(passedTime, cacheFrameRate); } } else if (animationStateCount > 1) { for (std::size_t i = 0, r = 0; i < animationStateCount; ++i) { const auto animationState = _animationStates[i]; if (animationState->_fadeState > 0 && animationState->_subFadeState > 0) { r++; _armature->_dragonBones->bufferObject(animationState); _animationDirty = true; if (_lastAnimationState == animationState) { _lastAnimationState = nullptr; } } else { if (r > 0) { _animationStates[i - r] = animationState; } animationState->advanceTime(passedTime, 0.0f); } if (i == animationStateCount - 1 && r > 0) { _animationStates.resize(animationStateCount - r); if (_lastAnimationState == nullptr && !_animationStates.empty()) { _lastAnimationState = _animationStates[_animationStates.size() - 1]; } } } _armature->_cacheFrameIndex = -1; } else { _armature->_cacheFrameIndex = -1; } } void Animation::reset() { for (const auto animationState : _animationStates) { animationState->returnToPool(); } _animationDirty = false; _animationConfig->clear(); _animationStates.clear(); _lastAnimationState = nullptr; } void Animation::stop(const std::string& animationName) { if (!animationName.empty()) { const auto animationState = getState(animationName); if (animationState != nullptr) { animationState->stop(); } } else { for (const auto animationState : _animationStates) { animationState->stop(); } } } AnimationState* Animation::playConfig(AnimationConfig* animationConfig) { const auto& animationName = animationConfig->animation; if (_animations.find(animationName) == _animations.end()) { DRAGONBONES_ASSERT( false, "Non-existent animation.\n" + " DragonBones name: " + this->_armature->getArmatureData().parent->name + " Armature name: " + this->_armature->name + " Animation name: " + animationName ); return nullptr; } const auto animationData = _animations[animationName]; if (animationConfig->fadeOutMode == AnimationFadeOutMode::Single) { for (const auto animationState : _animationStates) { if (animationState->_animationData == animationData) { return animationState; } } } if (animationConfig->fadeInTime < 0.0f) { if (_animationStates.empty()) { animationConfig->fadeInTime = 0.0f; } else { animationConfig->fadeInTime = animationData->fadeInTime; } } if (animationConfig->fadeOutTime < 0.0f) { animationConfig->fadeOutTime = animationConfig->fadeInTime; } if (animationConfig->timeScale <= -100.0f) { animationConfig->timeScale = 1.0f / animationData->scale; } if (animationData->frameCount > 1) { if (animationConfig->position < 0.0f) { animationConfig->position = fmod(animationConfig->position, animationData->duration); animationConfig->position = animationData->duration - animationConfig->position; } else if (animationConfig->position == animationData->duration) { animationConfig->position -= 0.000001f; // Play a little time before end. } else if (animationConfig->position > animationData->duration) { animationConfig->position = fmod(animationConfig->position, animationData->duration); } if (animationConfig->duration > 0.0f && animationConfig->position + animationConfig->duration > animationData->duration) { animationConfig->duration = animationData->duration - animationConfig->position; } if (animationConfig->playTimes < 0) { animationConfig->playTimes = animationData->playTimes; } } else { animationConfig->playTimes = 1; animationConfig->position = 0.0f; if (animationConfig->duration > 0.0f) { animationConfig->duration = 0.0f; } } if (animationConfig->duration == 0.0f) { animationConfig->duration = -1.0f; } _fadeOut(animationConfig); const auto animationState = BaseObject::borrowObject<AnimationState>(); animationState->init(_armature, animationData, animationConfig); _animationDirty = true; _armature->_cacheFrameIndex = -1; if (!_animationStates.empty()) { auto added = false; for (std::size_t i = 0, l = _animationStates.size(); i < l; ++i) { if (animationState->layer > _animationStates[i]->layer) { added = true; auto parentInerator = std::find(_animationStates.begin(), _animationStates.end(), _animationStates[i]); _animationStates.insert(parentInerator, animationState); break; } else if (i != l - 1 && animationState->layer > _animationStates[i + 1]->layer) { added = true; auto parentInerator = std::find(_animationStates.begin(), _animationStates.end(), _animationStates[i]); _animationStates.insert(parentInerator + 1, animationState); break; } } if (!added) { _animationStates.push_back(animationState); } } else { _animationStates.push_back(animationState); } // Child armature play same name animation. for (const auto slot : _armature->getSlots()) { const auto childArmature = slot->getChildArmature(); if ( childArmature != nullptr && childArmature->inheritAnimation && childArmature->getAnimation()->hasAnimation(animationName) && childArmature->getAnimation()->getState(animationName) == nullptr ) { childArmature->getAnimation()->fadeIn(animationName); // } } if (animationConfig->fadeInTime <= 0.0f) // Blend animation state, update armature. { _armature->advanceTime(0.0f); } _lastAnimationState = animationState; return animationState; } AnimationState* Animation::play(const std::string& animationName, int playTimes) { _animationConfig->clear(); _animationConfig->resetToPose = true; _animationConfig->playTimes = playTimes; _animationConfig->fadeInTime = 0.0f; _animationConfig->animation = animationName; if (!animationName.empty()) { playConfig(_animationConfig); } else if (_lastAnimationState == nullptr) { const auto defaultAnimation = _armature->_armatureData->defaultAnimation; if (defaultAnimation != nullptr) { _animationConfig->animation = defaultAnimation->name; playConfig(_animationConfig); } } else if (!_lastAnimationState->isPlaying() && !_lastAnimationState->isCompleted()) { _lastAnimationState->play(); } else { _animationConfig->animation = _lastAnimationState->name; playConfig(_animationConfig); } return _lastAnimationState; } #ifdef EGRET_WASM AnimationState* Animation::fadeIn( const std::string& animationName, float fadeInTime, int playTimes, int layer, const std::string& group, int fadeOutMode /*AnimationFadeOutMode*/ #else AnimationState* Animation::fadeIn( const std::string& animationName, float fadeInTime, int playTimes, int layer, const std::string& group, AnimationFadeOutMode fadeOutMode #endif // EGRET_WASM ) { _animationConfig->clear(); _animationConfig->fadeOutMode = (AnimationFadeOutMode)fadeOutMode; _animationConfig->playTimes = playTimes; _animationConfig->layer = layer; _animationConfig->fadeInTime = fadeInTime; _animationConfig->animation = animationName; _animationConfig->group = group; return playConfig(_animationConfig); } AnimationState* Animation::gotoAndPlayByTime(const std::string& animationName, float time, int playTimes) { _animationConfig->clear(); _animationConfig->resetToPose = true; _animationConfig->playTimes = playTimes; _animationConfig->position = time; _animationConfig->fadeInTime = 0.0f; _animationConfig->animation = animationName; return playConfig(_animationConfig); } AnimationState* Animation::gotoAndPlayByFrame(const std::string& animationName, unsigned frame, int playTimes) { _animationConfig->clear(); _animationConfig->resetToPose = true; _animationConfig->playTimes = playTimes; _animationConfig->fadeInTime = 0.0f; _animationConfig->animation = animationName; const auto animationData = mapFind(_animations, animationName); if (animationData != nullptr) { _animationConfig->position = animationData->duration * frame / animationData->frameCount; } return playConfig(_animationConfig); } AnimationState* Animation::gotoAndPlayByProgress(const std::string& animationName, float progress, int playTimes) { _animationConfig->clear(); _animationConfig->resetToPose = true; _animationConfig->playTimes = playTimes; _animationConfig->fadeInTime = 0.0f; _animationConfig->animation = animationName; const auto animationData = mapFind(_animations, animationName); if (animationData != nullptr) { _animationConfig->position = animationData->duration * (progress > 0.0f ? progress : 0.0f); } return playConfig(_animationConfig); } AnimationState* Animation::gotoAndStopByTime(const std::string& animationName, float time) { const auto animationState = gotoAndPlayByTime(animationName, time, 1); if (animationState != nullptr) { animationState->stop(); } return animationState; } AnimationState* Animation::gotoAndStopByFrame(const std::string& animationName, unsigned frame) { const auto animationState = gotoAndPlayByFrame(animationName, frame, 1); if (animationState != nullptr) { animationState->stop(); } return animationState; } AnimationState* Animation::gotoAndStopByProgress(const std::string& animationName, float progress) { const auto animationState = gotoAndPlayByProgress(animationName, progress, 1); if (animationState != nullptr) { animationState->stop(); } return animationState; } AnimationState* Animation::getState(const std::string& animationName) const { int i = _animationStates.size(); while (i--) { const auto animationState = _animationStates[i]; if (animationState->name == animationName) { return animationState; } } return nullptr; } bool Animation::hasAnimation(const std::string& animationName) const { return _animations.find(animationName) != _animations.end(); } bool Animation::isPlaying() const { for (const auto animationState : _animationStates) { if (animationState->isPlaying()) { return true; } } return false; } bool Animation::isCompleted() const { for (const auto animationState : _animationStates) { if (!animationState->isCompleted()) { return false; } } return !_animationStates.empty(); } const std::string& Animation::getLastAnimationName() const { if (_lastAnimationState != nullptr) { return _lastAnimationState->name; } static const std::string DEFAULT_NAME = ""; return DEFAULT_NAME; } void Animation::setAnimations(const std::map<std::string, AnimationData*>& value) { if (_animations == value) { return; } _animationNames.clear(); _animations.clear(); for (const auto& pair : value) { _animationNames.push_back(pair.first); _animations[pair.first] = pair.second; } } AnimationConfig* Animation::getAnimationConfig() const { _animationConfig->clear(); return _animationConfig; } DRAGONBONES_NAMESPACE_END
411
0.888157
1
0.888157
game-dev
MEDIA
0.877498
game-dev
0.919192
1
0.919192
SkelletonX/DDTank4.1
4,256
Source Server/SourceQuest4.5/Microsoft.QualityTools.Testing.Fakes/Microsoft.QualityTools.Testing.Fakes.Stubs/StubBehaviors.cs
using Microsoft.QualityTools.Testing.Fakes.Shims; using System; using System.Diagnostics; namespace Microsoft.QualityTools.Testing.Fakes.Stubs { [DebuggerNonUserCode] public static class StubBehaviors { [Serializable] [DebuggerNonUserCode] [__Instrument] private class DefaultValueStub : IStubBehavior { public TResult Result<TBehaved, TResult>(TBehaved me, string name) where TBehaved : IStub { return default(TResult); } public void VoidResult<TBehaved>(TBehaved me, string name) where TBehaved : IStub { } public void ValueAtReturn<TBehaved, TResult>(TBehaved me, string name, out TResult value) where TBehaved : IStub { value = default(TResult); } public void ValueAtEnterAndReturn<TBehaved, TResult>(TBehaved stub, string name, ref TResult value) where TBehaved : IStub { value = default(TResult); } public bool TryGetValue<TValue>(object name, out TValue value) { value = default(TValue); return true; } } [Serializable] [DebuggerNonUserCode] [__Instrument] private class NotImplementedStub : IStubBehavior { public TResult Result<TBehaved, TResult>(TBehaved me, string name) where TBehaved : IStub { throw new NotImplementedException(); } public void VoidResult<TBehaved>(TBehaved me, string name) where TBehaved : IStub { throw new NotImplementedException(); } public void ValueAtReturn<TBehaved, TResult>(TBehaved me, string name, out TResult value) where TBehaved : IStub { throw new NotImplementedException(); } public void ValueAtEnterAndReturn<TBehaved, TResult>(TBehaved stub, string name, ref TResult value) where TBehaved : IStub { throw new NotImplementedException(); } public bool TryGetValue<TValue>(object name, out TValue value) { value = default(TValue); return false; } } private sealed class CurrentProxyBehavior : IStubBehavior { public static readonly CurrentProxyBehavior Instance = new CurrentProxyBehavior(); private CurrentProxyBehavior() { } public bool TryGetValue<TValue>(object name, out TValue value) { return Current.TryGetValue(name, out value); } public TResult Result<TBehaved, TResult>(TBehaved target, string name) where TBehaved : IStub { return Current.Result<TBehaved, TResult>(target, name); } public void ValueAtReturn<TBehaved, TValue>(TBehaved target, string name, out TValue value) where TBehaved : IStub { Current.ValueAtReturn(target, name, out value); } public void ValueAtEnterAndReturn<TBehaved, TValue>(TBehaved target, string name, ref TValue value) where TBehaved : IStub { Current.ValueAtEnterAndReturn(target, name, ref value); } public void VoidResult<TBehaved>(TBehaved target, string name) where TBehaved : IStub { Current.VoidResult(target, name); } } private static IStubBehavior @default; private static IStubBehavior notImplementedStub; private static IStubBehavior current = DefaultValue; public static IStubBehavior DefaultValue { get { if (@default == null) { using (ShimRuntime.AcquireProtectingThreadContext()) { @default = new DefaultValueStub(); } } return @default; } } public static IStubBehavior NotImplemented { get { if (notImplementedStub == null) { using (ShimRuntime.AcquireProtectingThreadContext()) { notImplementedStub = new NotImplementedStub(); } } return notImplementedStub; } } public static IStubBehavior Current { get { using (ShimRuntime.AcquireProtectingThreadContext()) { return current; } } set { using (ShimRuntime.AcquireProtectingThreadContext()) { if (value == null) { throw new ArgumentNullException("value"); } current = value; } } } public static IStubBehavior CurrentProxy => CurrentProxyBehavior.Instance; public static void BehaveAsNotImplemented() { Current = NotImplemented; } public static IStubBehavior GetValueOrCurrent(IStubBehavior behavior) { using (ShimRuntime.AcquireProtectingThreadContext()) { return (behavior != null) ? behavior : Current; } } } }
411
0.801457
1
0.801457
game-dev
MEDIA
0.413528
game-dev
0.638743
1
0.638743
nature-of-code/Nature-of-Code-Website-Archive
2,912
natureofcode2.0/book/processingjs/chapter03/_3_10_PendulumExample/Pendulum.pde
// Pendulum // Daniel Shiffman <http://www.shiffman.net> // A Simple Pendulum Class // Includes functionality for user can click and drag the pendulum class Pendulum { PVector location; // Location of pendulum ball PVector origin; // Location of arm origin float r; // Length of arm float angle; // Pendulum arm angle float aVelocity; // Angle velocity float aAcceleration; // Angle acceleration float ballr; // Ball radius float damping; // Arbitary damping amount boolean dragging = false; // This constructor could be improved to allow a greater variety of pendulums Pendulum(PVector origin_, float r_) { // Fill all variables origin = origin_.get(); location = new PVector(); r = r_; angle = PI/4; aVelocity = 0.0; aAcceleration = 0.0; damping = 0.995; // Arbitrary damping ballr = 48.0; // Arbitrary ball radius } void go() { update(); drag(); //for user interaction display(); } // Function to update location void update() { // As long as we aren't dragging the pendulum, let it swing! if (!dragging) { float gravity = 0.4; // Arbitrary constant aAcceleration = (-1 * gravity / r) * sin(angle); // Calculate acceleration (see: http://www.myphysicslab.com/pendulum1.html) aVelocity += aAcceleration; // Increment velocity aVelocity *= damping; // Arbitrary damping angle += aVelocity; // Increment angle } } void display() { location.set(r*sin(angle), r*cos(angle), 0); // Polar to cartesian conversion location.add(origin); // Make sure the location is relative to the pendulum's origin stroke(0); strokeWeight(2); // Draw the arm line(origin.x, origin.y, location.x, location.y); ellipseMode(CENTER); fill(175); if (dragging) fill(0); // Draw the ball ellipse(location.x, location.y, ballr, ballr); } // The methods below are for mouse interaction // This checks to see if we clicked on the pendulum ball void clicked(int mx, int my) { float d = dist(mx, my, location.x, location.y); if (d < ballr) { dragging = true; } } // This tells us we are not longer clicking on the ball void stopDragging() { aVelocity = 0; // No velocity once you let go dragging = false; } void drag() { // If we are draging the ball, we calculate the angle between the // pendulum origin and mouse location // we assign that angle to the pendulum if (dragging) { PVector diff = PVector.sub(origin, new PVector(mouseX, mouseY)); // Difference between 2 points angle = atan2(-1*diff.y, diff.x) - radians(90); // Angle relative to vertical axis } } }
411
0.78423
1
0.78423
game-dev
MEDIA
0.819121
game-dev
0.620715
1
0.620715
Picorims/open-street-kart
4,227
prefabs/player_spawner.gd
# Open Street Kart is an arcade kart game where you race in real life areas reconstructed from Open Street Map # Copyright (c) 2025 Charly Schmidt aka Picorims<picorims.contact@gmail.com> and Open Street Kart contributors # 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/. class_name PlayerSpawner extends Node3D @export var race_path: RacePath enum CountdownState { THREE = 3, TWO = 2, ONE = 1, GO = 0, IDLE = -1, } const CAR_SCENE: PackedScene = preload("res://prefabs/car_custom_physics_2.tscn") const COUNTDOWN_DURATION: CountdownState = CountdownState.THREE const CARS_COUNT = 16 var _in_countdown: bool = false var _countdown_state = 0 var _countdown_elapsed: float = 0 var cars: Array[RigidBody3D] = [] var car_root_nodes: Array[CarCustomPhysics2] = [] var _car_root_node_map: Dictionary[String, CarCustomPhysics2] = {} signal go var TrackSpeedDict: Dictionary[TrackState.SpeedMode, float] = { TrackState.SpeedMode.CHILL: 15, TrackState.SpeedMode.CASUAL: 20, TrackState.SpeedMode.CHALLENGING: 25, TrackState.SpeedMode.CRAZY: 32, } var OutOfBoundsSpeedDict: Dictionary[TrackState.SpeedMode, float] = { TrackState.SpeedMode.CHILL: 4, TrackState.SpeedMode.CASUAL: 6, TrackState.SpeedMode.CHALLENGING: 8, TrackState.SpeedMode.CRAZY: 10, } func _ready() -> void: assert(race_path != null, "ERROR: race_path not configured on player spawner.") func init(mode: TrackState.GameMode, speed: TrackState.SpeedMode): print("Initializing player spawner...") var count: int = 0 if (mode == TrackState.GameMode.AGAINST_CLOCK): count = 1 elif (mode == TrackState.GameMode.VERSUS): count = CARS_COUNT for i in range(count): var car: CarCustomPhysics2 = CAR_SCENE.instantiate() self.add_child(car) car.display_name = "p{0}".format([i + 1]) car.material = StandardMaterial3D.new() car.material.albedo_color = Color(randf(), randf(), randf()) if (i == count - 1): car.mode = CarCustomPhysics2.CarMode.USER car.display_name = "you" var cam: Camera3D = car.get_node("CarRigidBody/Camera3D") if (cam != null): cam.current = true car.show_debug_arrows = true else: push_error("ERROR: Could not set user as main camera focus.") else: car.mode = CarCustomPhysics2.CarMode.BOT car.path = race_path car.speed_multiplier = 1.0 car.max_speed_meters_per_second = TrackSpeedDict.get(speed) car.max_speed_out_of_bounds_meters_per_second = OutOfBoundsSpeedDict.get(speed) car.basis = self.basis car.global_transform = self.global_transform car.global_position += self.basis.x * -i + self.basis.z * (i % 4) + self.basis.y * 5 var rigid_body: RigidBody3D = car.get_node("CarRigidBody") rigid_body.freeze = true var snap_ray_cast = SnapToGroundRayCast3D.new() self.add_child(snap_ray_cast) snap_ray_cast.align_to_normal = true snap_ray_cast.offset = -0.5 snap_ray_cast.target_position = Vector3(0, -1000, 0) snap_ray_cast.target = car snap_ray_cast.force_raycast_update() cars.append(rigid_body) car_root_nodes.append(car) _car_root_node_map.set(car.name, car) print("Initializing player spawner done.") func _process(delta: float) -> void: if (_in_countdown): _countdown_elapsed += delta if (_countdown_state == CountdownState.IDLE): # initialize print("3...") _countdown_state = CountdownState.THREE elif (_countdown_state == CountdownState.THREE and _countdown_elapsed > 1): print("2...") _countdown_state = CountdownState.TWO elif (_countdown_state == CountdownState.TWO and _countdown_elapsed > 2): print("1...") _countdown_state = CountdownState.ONE elif (_countdown_state == CountdownState.ONE and _countdown_elapsed > 3): print("GO!") _countdown_state = CountdownState.GO go.emit() if (_countdown_elapsed > COUNTDOWN_DURATION): for c in cars: c.freeze = false _in_countdown = false _countdown_state = CountdownState.IDLE func countdown(): _countdown_elapsed = 0 _countdown_state = CountdownState.IDLE _in_countdown = true func get_car_by_id(id: String) -> CarCustomPhysics2: return _car_root_node_map.get(id)
411
0.629191
1
0.629191
game-dev
MEDIA
0.476506
game-dev,desktop-app
0.933615
1
0.933615
CraftTweaker/CraftTweaker-Documentation
1,348
docs_exported/1.19.4/crafttweaker/docs/forge/api/event/tick/PlayerTickEvent.md
# PlayerTickEvent The event is not cancelable. The event does not have a result. ## Importing the class It might be required for you to import the package if you encounter any issues (like casting an Array), so better be safe than sorry and add the import at the very top of the file. ```zenscript import crafttweaker.forge.api.event.tick.PlayerTickEvent; ``` ## Extending TickEvent PlayerTickEvent extends [TickEvent](/forge/api/event/tick/TickEvent). That means all methods available in [TickEvent](/forge/api/event/tick/TickEvent) are also available in PlayerTickEvent ## Methods :::group{name=every} ```zenscript PlayerTickEvent.every(ticks as int, event as Consumer<PlayerTickEvent>) ``` | Parameter | Type | |-----------|--------------------------------------------------------------------------| | ticks | int | | event | Consumer&lt;[PlayerTickEvent](/forge/api/event/tick/PlayerTickEvent)&gt; | ::: ## Properties | Name | Type | Has Getter | Has Setter | |--------|--------------------------------------------------|------------|------------| | player | [Player](/vanilla/api/entity/type/player/Player) | true | false |
411
0.606958
1
0.606958
game-dev
MEDIA
0.72858
game-dev
0.566161
1
0.566161
electronicarts/CnC_Generals_Zero_Hour
54,986
GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/parameter.cpp
/* ** Command & Conquer Generals Zero Hour(tm) ** Copyright 2025 Electronic Arts Inc. ** ** This program is free software: you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation, either version 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/>. */ /*********************************************************************************************** *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** *********************************************************************************************** * * * Project Name : WWSaveLoad * * * * $Archive:: /Commando/Code/wwsaveload/parameter.cpp $* * * * Org Author:: Patrick Smith * * * * Author:: Kenny Mitchell * * * * $Modtime:: 5/29/02 11:00a $* * * * $Revision:: 33 $* * * *---------------------------------------------------------------------------------------------* * Functions: * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ #include "parameter.h" #include "parametertypes.h" #include "simpleparameter.h" #include "wwstring.h" #include "definitionclassids.h" ///////////////////////////////////////////////////////////////////// // // Construct // // This is a virtual constructor that is capable of creating a new // instance of any type of parameter used in the Editable system. // ///////////////////////////////////////////////////////////////////// ParameterClass * ParameterClass::Construct (Type type, void *data, const char *name) { ParameterClass *new_param = NULL; switch (type) { case TYPE_INT: new_param = W3DNEW IntParameterClass (data, name); break; case TYPE_FLOAT: new_param = W3DNEW FloatParameterClass (data, name); break; case TYPE_VECTOR2: new_param = W3DNEW Vector2ParameterClass (data, name); break; case TYPE_VECTOR3: new_param = W3DNEW Vector3ParameterClass (data, name); break; case TYPE_RECT: new_param = W3DNEW RectParameterClass (data, name); break; case TYPE_COLOR: new_param = W3DNEW ColorParameterClass (data, name); break; case TYPE_MATRIX3D: new_param = W3DNEW Matrix3DParameterClass (data, name); break; case TYPE_BOOL: new_param = W3DNEW BoolParameterClass (data, name); break; case TYPE_STRINGSDB_ID: new_param = W3DNEW StringsDBEntryParameterClass (data, name); break; case TYPE_ANGLE: new_param = W3DNEW AngleParameterClass (data, name); break; case TYPE_STRING: new_param = W3DNEW StringParameterClass ((StringClass *)data); new_param->Set_Name (name); break; case TYPE_FILENAME: new_param = W3DNEW FilenameParameterClass ((StringClass *)data); new_param->Set_Name (name); break; case TYPE_TEXTURE_FILENAME: new_param = new TextureFilenameParameterClass ((StringClass *)data); new_param->Set_Name (name); break; case TYPE_SOUND_FILENAME: new_param = W3DNEW SoundFilenameParameterClass ((StringClass *)data); new_param->Set_Name (name); break; case TYPE_ENUM: new_param = W3DNEW EnumParameterClass ((int *)data); new_param->Set_Name (name); break; case TYPE_GENERICDEFINITIONID: new_param = W3DNEW GenericDefParameterClass ((int *)data); new_param->Set_Name (name); break; case TYPE_GAMEOBJDEFINITIONID: new_param = W3DNEW GameObjDefParameterClass ((int *)data); new_param->Set_Name (name); break; case TYPE_WEAPONOBJDEFINITIONID: new_param = W3DNEW WeaponObjDefParameterClass ((int *)data); new_param->Set_Name (name); break; case TYPE_AMMOOBJDEFINITIONID: new_param = W3DNEW AmmoObjDefParameterClass ((int *)data); new_param->Set_Name (name); break; case TYPE_EXPLOSIONDEFINITIONID: new_param = W3DNEW ExplosionObjDefParameterClass ((int *)data); new_param->Set_Name (name); break; case TYPE_SOUNDDEFINITIONID: new_param = W3DNEW SoundDefParameterClass ((int *)data); new_param->Set_Name (name); break; case TYPE_MODELDEFINITIONID: new_param = W3DNEW ModelDefParameterClass ((int *)data); new_param->Set_Name (name); break; case TYPE_PHYSDEFINITIONID: new_param = W3DNEW PhysDefParameterClass ((int *)data); new_param->Set_Name (name); break; case TYPE_DEFINITIONIDLIST: new_param = W3DNEW DefIDListParameterClass ((DynamicVectorClass<int> *)data); new_param->Set_Name (name); ((DefIDListParameterClass *)new_param)->Set_Class_ID (CLASSID_GAME_OBJECTS); break; case TYPE_ZONE: new_param = W3DNEW ZoneParameterClass ((OBBoxClass *)data); new_param->Set_Name (name); break; case TYPE_FILENAMELIST: new_param = W3DNEW FilenameListParameterClass ((DynamicVectorClass<StringClass> *)data); new_param->Set_Name (name); break; case TYPE_SEPARATOR: new_param = W3DNEW SeparatorParameterClass; new_param->Set_Name (name); break; } return new_param; } //*******************************************************************************************// // // Start of StringParameterClass // //*******************************************************************************************// ///////////////////////////////////////////////////////////////////// // // StringParameterClass // ///////////////////////////////////////////////////////////////////// StringParameterClass::StringParameterClass (StringClass *string) : m_String (string) { return ; } ///////////////////////////////////////////////////////////////////// // // StringParameterClass // ///////////////////////////////////////////////////////////////////// StringParameterClass::StringParameterClass (const StringParameterClass &src) : m_String (NULL) { (*this) = src; return ; } ///////////////////////////////////////////////////////////////////// // // operator= // ///////////////////////////////////////////////////////////////////// const StringParameterClass & StringParameterClass::operator= (const StringParameterClass &src) { m_String = src.m_String; ParameterClass::operator= (src); return *this; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool StringParameterClass::operator== (const StringParameterClass &src) { bool retval = false; if (m_String != NULL && src.m_String != NULL && (m_String->Compare (*(src.m_String)) == 0)) { retval = true; } return retval; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool StringParameterClass::operator== (const ParameterClass &src) { bool retval = false; if (src.Get_Type () == Get_Type ()) { retval = StringParameterClass::operator== ((const StringParameterClass &)src); } return retval; } ///////////////////////////////////////////////////////////////////// // // Copy_Value // ///////////////////////////////////////////////////////////////////// void StringParameterClass::Copy_Value (const ParameterClass &src) { if (src.Is_Type (ParameterClass::TYPE_STRING)) { (*m_String) = ((StringParameterClass &)src).Get_String (); } ParameterClass::Copy_Value (src); return ; } ///////////////////////////////////////////////////////////////////// // // Get_String // ///////////////////////////////////////////////////////////////////// const char * StringParameterClass::Get_String (void) const { const char * string = NULL; if (m_String != NULL) { string = (*m_String); } return string; } ///////////////////////////////////////////////////////////////////// // // Set_String // ///////////////////////////////////////////////////////////////////// void StringParameterClass::Set_String (const char * string) { if (m_String != NULL) { Set_Modified (); (*m_String) = string; } return ; } //*******************************************************************************************// // // Start of FilenameParameterClass // //*******************************************************************************************// ///////////////////////////////////////////////////////////////////// // // FilenameParameterClass // ///////////////////////////////////////////////////////////////////// FilenameParameterClass::FilenameParameterClass (StringClass *string) : StringParameterClass (string) { return ; } ///////////////////////////////////////////////////////////////////// // // FilenameParameterClass // ///////////////////////////////////////////////////////////////////// FilenameParameterClass::FilenameParameterClass (const FilenameParameterClass &src) : StringParameterClass (src) { (*this) = src; return ; } ///////////////////////////////////////////////////////////////////// // // operator= // ///////////////////////////////////////////////////////////////////// const FilenameParameterClass & FilenameParameterClass::operator= (const FilenameParameterClass &src) { StringParameterClass::operator= (src); return *this; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool FilenameParameterClass::operator== (const FilenameParameterClass &src) { return StringParameterClass::operator== (src); } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool FilenameParameterClass::operator== (const ParameterClass &src) { return StringParameterClass::operator== (src); } ///////////////////////////////////////////////////////////////////// // // Copy_Value // ///////////////////////////////////////////////////////////////////// void FilenameParameterClass::Copy_Value (const ParameterClass &src) { if (src.Is_Type (ParameterClass::TYPE_FILENAME)) { Set_String (((FilenameParameterClass &)src).Get_String ()); } StringParameterClass::Copy_Value (src); return ; } //*******************************************************************************************// // // Start of TextureFilenameParameterClass // //*******************************************************************************************// ///////////////////////////////////////////////////////////////////// // // TextureFilenameParameterClass // ///////////////////////////////////////////////////////////////////// TextureFilenameParameterClass::TextureFilenameParameterClass (StringClass *string) : FilenameParameterClass (string), Show_Alpha(false), Show_Texture(false) { } ///////////////////////////////////////////////////////////////////// // // TextureFilenameParameterClass // ///////////////////////////////////////////////////////////////////// TextureFilenameParameterClass::TextureFilenameParameterClass (const TextureFilenameParameterClass &src) : FilenameParameterClass (src), Show_Alpha(false), Show_Texture(false) { } ///////////////////////////////////////////////////////////////////// // // Copy_Value // ///////////////////////////////////////////////////////////////////// void TextureFilenameParameterClass::Copy_Value (const ParameterClass &src) { if (src.Is_Type (ParameterClass::TYPE_TEXTURE_FILENAME)) { Set_String (((FilenameParameterClass &)src).Get_String ()); } StringParameterClass::Copy_Value (src); return ; } //*******************************************************************************************// // // Start of SoundFilenameParameterClass // //*******************************************************************************************// ///////////////////////////////////////////////////////////////////// // // SoundFilenameParameterClass // ///////////////////////////////////////////////////////////////////// SoundFilenameParameterClass::SoundFilenameParameterClass (StringClass *string) : FilenameParameterClass (string) { return ; } ///////////////////////////////////////////////////////////////////// // // SoundFilenameParameterClass // ///////////////////////////////////////////////////////////////////// SoundFilenameParameterClass::SoundFilenameParameterClass (const SoundFilenameParameterClass &src) : FilenameParameterClass (src) { (*this) = src; return ; } ///////////////////////////////////////////////////////////////////// // // operator= // ///////////////////////////////////////////////////////////////////// const SoundFilenameParameterClass & SoundFilenameParameterClass::operator= (const SoundFilenameParameterClass &src) { FilenameParameterClass::operator= (src); return *this; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool SoundFilenameParameterClass::operator== (const SoundFilenameParameterClass &src) { return FilenameParameterClass::operator== (src); } //*******************************************************************************************// // // Start of EnumParameterClass // //*******************************************************************************************// ///////////////////////////////////////////////////////////////////// // // EnumParameterClass // ///////////////////////////////////////////////////////////////////// EnumParameterClass::EnumParameterClass (int *value) : m_Value (value) { return ; } ///////////////////////////////////////////////////////////////////// // // EnumParameterClass // ///////////////////////////////////////////////////////////////////// EnumParameterClass::EnumParameterClass (const EnumParameterClass &src) : m_Value (NULL) { (*this) = src; return ; } ///////////////////////////////////////////////////////////////////// // // operator= // ///////////////////////////////////////////////////////////////////// const EnumParameterClass & EnumParameterClass::operator= (const EnumParameterClass &src) { m_List.Delete_All (); m_Value = src.m_Value; m_List = src.m_List; ParameterClass::operator= (src); return *this; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool EnumParameterClass::operator== (const EnumParameterClass &src) { bool retval = false; if (m_Value != NULL && src.m_Value != NULL && (*m_Value) == (*src.m_Value)) { retval = true; } return retval; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool EnumParameterClass::operator== (const ParameterClass &src) { bool retval = false; if (src.Get_Type () == Get_Type ()) { retval = EnumParameterClass::operator== ((const EnumParameterClass &)src); } return retval; } ///////////////////////////////////////////////////////////////////// // // Copy_Value // ///////////////////////////////////////////////////////////////////// void EnumParameterClass::Copy_Value (const ParameterClass &src) { if (src.Is_Type (ParameterClass::TYPE_ENUM)) { (*m_Value) = ((EnumParameterClass &)src).Get_Selected_Value (); } ParameterClass::Copy_Value (src); return ; } ///////////////////////////////////////////////////////////////////// // // Add_Value // ///////////////////////////////////////////////////////////////////// void EnumParameterClass::Add_Value (const char *display_name, int value) { m_List.Add (ENUM_VALUE(display_name, value)); return ; } ///////////////////////////////////////////////////////////////////// // // Add_Value // ///////////////////////////////////////////////////////////////////// void __cdecl EnumParameterClass::Add_Values (const char *first_name, int first_value, ...) { m_List.Add (ENUM_VALUE(first_name, first_value)); va_list arg_list; va_start (arg_list, first_value); // // Add all the params on the stack (until we found // the terminator) // bool more_params = true; while (more_params) { // // Get the string param // const char *name = va_arg (arg_list, const char *); if (name == NULL) { more_params = false; } else { // // Add the string/id pair to the enum list // int value = va_arg (arg_list, int); m_List.Add (ENUM_VALUE(name, value)); } } va_end (arg_list); return ; } //*******************************************************************************************// // // Start of PhysDefParameterClass // //*******************************************************************************************// ///////////////////////////////////////////////////////////////////// // // PhysDefParameterClass // ///////////////////////////////////////////////////////////////////// PhysDefParameterClass::PhysDefParameterClass (int *id) : m_Value (id) { return ; } ///////////////////////////////////////////////////////////////////// // // PhysDefParameterClass // ///////////////////////////////////////////////////////////////////// PhysDefParameterClass::PhysDefParameterClass (const PhysDefParameterClass &src) : m_Value (NULL) { (*this) = src; return ; } ///////////////////////////////////////////////////////////////////// // // operator= // ///////////////////////////////////////////////////////////////////// const PhysDefParameterClass & PhysDefParameterClass::operator= (const PhysDefParameterClass &src) { m_Value = src.m_Value; ParameterClass::operator= (src); return *this; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool PhysDefParameterClass::operator== (const PhysDefParameterClass &src) { bool retval = false; if (m_Value != NULL && src.m_Value != NULL && (*m_Value) == (*src.m_Value)) { retval = true; } return retval; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool PhysDefParameterClass::operator== (const ParameterClass &src) { bool retval = false; if (src.Get_Type () == Get_Type ()) { retval = PhysDefParameterClass::operator== ((const PhysDefParameterClass &)src); } return retval; } ///////////////////////////////////////////////////////////////////// // // Copy_Value // ///////////////////////////////////////////////////////////////////// void PhysDefParameterClass::Copy_Value (const ParameterClass &/*src*/) { // // We don't allow the value to be copied // return ; } //*******************************************************************************************// // // Start of ModelDefParameterClass // //*******************************************************************************************// ///////////////////////////////////////////////////////////////////// // // ModelDefParameterClass // ///////////////////////////////////////////////////////////////////// ModelDefParameterClass::ModelDefParameterClass (int *id) : m_Value (id) { return ; } ///////////////////////////////////////////////////////////////////// // // ModelDefParameterClass // ///////////////////////////////////////////////////////////////////// ModelDefParameterClass::ModelDefParameterClass (const ModelDefParameterClass &src) : m_Value (NULL) { (*this) = src; return ; } ///////////////////////////////////////////////////////////////////// // // operator= // ///////////////////////////////////////////////////////////////////// const ModelDefParameterClass & ModelDefParameterClass::operator= (const ModelDefParameterClass &src) { m_Value = src.m_Value; ParameterClass::operator= (src); return *this; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool ModelDefParameterClass::operator== (const ModelDefParameterClass &src) { bool retval = false; if (m_Value != NULL && src.m_Value != NULL && (*m_Value) == (*src.m_Value)) { retval = true; } return retval; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool ModelDefParameterClass::operator== (const ParameterClass &src) { bool retval = false; if (src.Get_Type () == Get_Type ()) { retval = ModelDefParameterClass::operator== ((const ModelDefParameterClass &)src); } return retval; } ///////////////////////////////////////////////////////////////////// // // Copy_Value // ///////////////////////////////////////////////////////////////////// void ModelDefParameterClass::Copy_Value (const ParameterClass &/*src*/) { // // We don't allow the value to be copied // return ; } //*******************************************************************************************// // // Start of DefParameterClass // //*******************************************************************************************// ///////////////////////////////////////////////////////////////////// // // DefParameterClass // ///////////////////////////////////////////////////////////////////// DefParameterClass::DefParameterClass (int *id) : m_Value (id) { return ; } ///////////////////////////////////////////////////////////////////// // // DefParameterClass // ///////////////////////////////////////////////////////////////////// DefParameterClass::DefParameterClass (const DefParameterClass &src) : m_Value (NULL) { (*this) = src; return ; } ///////////////////////////////////////////////////////////////////// // // operator= // ///////////////////////////////////////////////////////////////////// const DefParameterClass & DefParameterClass::operator= (const DefParameterClass &src) { m_Value = src.m_Value; ParameterClass::operator= (src); return *this; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool DefParameterClass::operator== (const DefParameterClass &src) { bool retval = false; if (m_Value != NULL && src.m_Value != NULL && (*m_Value) == (*src.m_Value)) { retval = true; } return retval; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool DefParameterClass::operator== (const ParameterClass &src) { bool retval = false; if (src.Get_Type () == Get_Type ()) { retval = DefParameterClass::operator== ((const DefParameterClass &)src); } return retval; } ///////////////////////////////////////////////////////////////////// // // Copy_Value // ///////////////////////////////////////////////////////////////////// void DefParameterClass::Copy_Value (const ParameterClass &src) { if (src.Get_Type () == Get_Type ()) { (*m_Value) = ((DefParameterClass &)src).Get_Value (); } ParameterClass::Copy_Value (src); return ; } //*******************************************************************************************// // // Start of GenericDefParameterClass // //*******************************************************************************************// ///////////////////////////////////////////////////////////////////// // // GenericDefParameterClass // ///////////////////////////////////////////////////////////////////// GenericDefParameterClass::GenericDefParameterClass (int *id) : m_ClassID (0), DefParameterClass (id) { return ; } ///////////////////////////////////////////////////////////////////// // // GenericDefParameterClass // ///////////////////////////////////////////////////////////////////// GenericDefParameterClass::GenericDefParameterClass (const GenericDefParameterClass &src) : m_ClassID (0), DefParameterClass (src) { (*this) = src; return ; } ///////////////////////////////////////////////////////////////////// // // operator= // ///////////////////////////////////////////////////////////////////// const GenericDefParameterClass & GenericDefParameterClass::operator= (const GenericDefParameterClass &src) { DefParameterClass::operator= (src); return *this; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool GenericDefParameterClass::operator== (const GenericDefParameterClass &src) { bool retval = false; if (m_Value != NULL && src.m_Value != NULL && (*m_Value) == (*src.m_Value)) { retval = true; } return retval; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool GenericDefParameterClass::operator== (const ParameterClass &src) { bool retval = false; if (src.Get_Type () == Get_Type ()) { retval = GenericDefParameterClass::operator== ((const GenericDefParameterClass &)src); } return retval; } ///////////////////////////////////////////////////////////////////// // // Copy_Value // ///////////////////////////////////////////////////////////////////// void GenericDefParameterClass::Copy_Value (const ParameterClass &src) { if (src.Is_Type (ParameterClass::TYPE_GENERICDEFINITIONID)) { (*m_Value) = ((GenericDefParameterClass &)src).Get_Value (); } ParameterClass::Copy_Value (src); return ; } //*******************************************************************************************// // // Start of GameObjDefParameterClass // //*******************************************************************************************// ///////////////////////////////////////////////////////////////////// // // GameObjDefParameterClass // ///////////////////////////////////////////////////////////////////// GameObjDefParameterClass::GameObjDefParameterClass (int *id) : DefParameterClass (id) { return ; } ///////////////////////////////////////////////////////////////////// // // GameObjDefParameterClass // ///////////////////////////////////////////////////////////////////// GameObjDefParameterClass::GameObjDefParameterClass (const GameObjDefParameterClass &src) : DefParameterClass (src) { (*this) = src; return ; } ///////////////////////////////////////////////////////////////////// // // operator= // ///////////////////////////////////////////////////////////////////// const GameObjDefParameterClass & GameObjDefParameterClass::operator= (const GameObjDefParameterClass &src) { DefParameterClass::operator= (src); return *this; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool GameObjDefParameterClass::operator== (const GameObjDefParameterClass &src) { bool retval = false; if (m_Value != NULL && src.m_Value != NULL && (*m_Value) == (*src.m_Value)) { retval = true; } return retval; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool GameObjDefParameterClass::operator== (const ParameterClass &src) { bool retval = false; if (src.Get_Type () == Get_Type ()) { retval = GameObjDefParameterClass::operator== ((const GameObjDefParameterClass &)src); } return retval; } ///////////////////////////////////////////////////////////////////// // // Copy_Value // ///////////////////////////////////////////////////////////////////// void GameObjDefParameterClass::Copy_Value (const ParameterClass &src) { if (src.Is_Type (ParameterClass::TYPE_GAMEOBJDEFINITIONID)) { (*m_Value) = ((GameObjDefParameterClass &)src).Get_Value (); } ParameterClass::Copy_Value (src); return ; } //*******************************************************************************************// // // Start of WeaponObjDefParameterClass // //*******************************************************************************************// ///////////////////////////////////////////////////////////////////// // // WeaponObjDefParameterClass // ///////////////////////////////////////////////////////////////////// WeaponObjDefParameterClass::WeaponObjDefParameterClass (int *id) : GameObjDefParameterClass (id) { return ; } ///////////////////////////////////////////////////////////////////// // // WeaponObjDefParameterClass // ///////////////////////////////////////////////////////////////////// WeaponObjDefParameterClass::WeaponObjDefParameterClass (const WeaponObjDefParameterClass &src) : GameObjDefParameterClass (NULL) { (*this) = src; return ; } ///////////////////////////////////////////////////////////////////// // // operator= // ///////////////////////////////////////////////////////////////////// const WeaponObjDefParameterClass & WeaponObjDefParameterClass::operator= (const WeaponObjDefParameterClass &src) { m_Value = src.m_Value; ParameterClass::operator= (src); return *this; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool WeaponObjDefParameterClass::operator== (const WeaponObjDefParameterClass &src) { bool retval = false; if (m_Value != NULL && src.m_Value != NULL && (*m_Value) == (*src.m_Value)) { retval = true; } return retval; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool WeaponObjDefParameterClass::operator== (const ParameterClass &src) { bool retval = false; if (src.Get_Type () == Get_Type ()) { retval = WeaponObjDefParameterClass::operator== ((const WeaponObjDefParameterClass &)src); } return retval; } ///////////////////////////////////////////////////////////////////// // // Copy_Value // ///////////////////////////////////////////////////////////////////// void WeaponObjDefParameterClass::Copy_Value (const ParameterClass &src) { if (src.Is_Type (ParameterClass::TYPE_WEAPONOBJDEFINITIONID)) { (*m_Value) = ((WeaponObjDefParameterClass &)src).Get_Value (); } GameObjDefParameterClass::Copy_Value (src); return ; } //*******************************************************************************************// // // Start of AmmoObjDefParameterClass // //*******************************************************************************************// ///////////////////////////////////////////////////////////////////// // // AmmoObjDefParameterClass // ///////////////////////////////////////////////////////////////////// AmmoObjDefParameterClass::AmmoObjDefParameterClass (int *id) : GameObjDefParameterClass (id) { return ; } ///////////////////////////////////////////////////////////////////// // // AmmoObjDefParameterClass // ///////////////////////////////////////////////////////////////////// AmmoObjDefParameterClass::AmmoObjDefParameterClass (const AmmoObjDefParameterClass &src) : GameObjDefParameterClass (NULL) { (*this) = src; return ; } ///////////////////////////////////////////////////////////////////// // // operator= // ///////////////////////////////////////////////////////////////////// const AmmoObjDefParameterClass & AmmoObjDefParameterClass::operator= (const AmmoObjDefParameterClass &src) { m_Value = src.m_Value; ParameterClass::operator= (src); return *this; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool AmmoObjDefParameterClass::operator== (const AmmoObjDefParameterClass &src) { bool retval = false; if (m_Value != NULL && src.m_Value != NULL && (*m_Value) == (*src.m_Value)) { retval = true; } return retval; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool AmmoObjDefParameterClass::operator== (const ParameterClass &src) { bool retval = false; if (src.Get_Type () == Get_Type ()) { retval = AmmoObjDefParameterClass::operator== ((const AmmoObjDefParameterClass &)src); } return retval; } ///////////////////////////////////////////////////////////////////// // // Copy_Value // ///////////////////////////////////////////////////////////////////// void AmmoObjDefParameterClass::Copy_Value (const ParameterClass &src) { if (src.Is_Type (ParameterClass::TYPE_AMMOOBJDEFINITIONID)) { (*m_Value) = ((AmmoObjDefParameterClass &)src).Get_Value (); } GameObjDefParameterClass::Copy_Value (src); return ; } //*******************************************************************************************// // // Start of ExplosionObjDefParameterClass // //*******************************************************************************************// ///////////////////////////////////////////////////////////////////// // // ExplosionObjDefParameterClass // ///////////////////////////////////////////////////////////////////// ExplosionObjDefParameterClass::ExplosionObjDefParameterClass (int *id) : GameObjDefParameterClass (id) { return ; } ///////////////////////////////////////////////////////////////////// // // ExplosionObjDefParameterClass // ///////////////////////////////////////////////////////////////////// ExplosionObjDefParameterClass::ExplosionObjDefParameterClass (const ExplosionObjDefParameterClass &src) : GameObjDefParameterClass (NULL) { (*this) = src; return ; } ///////////////////////////////////////////////////////////////////// // // operator= // ///////////////////////////////////////////////////////////////////// const ExplosionObjDefParameterClass & ExplosionObjDefParameterClass::operator= (const ExplosionObjDefParameterClass &src) { m_Value = src.m_Value; ParameterClass::operator= (src); return *this; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool ExplosionObjDefParameterClass::operator== (const ExplosionObjDefParameterClass &src) { bool retval = false; if (m_Value != NULL && src.m_Value != NULL && (*m_Value) == (*src.m_Value)) { retval = true; } return retval; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool ExplosionObjDefParameterClass::operator== (const ParameterClass &src) { bool retval = false; if (src.Get_Type () == Get_Type ()) { retval = ExplosionObjDefParameterClass::operator== ((const ExplosionObjDefParameterClass &)src); } return retval; } ///////////////////////////////////////////////////////////////////// // // Copy_Value // ///////////////////////////////////////////////////////////////////// void ExplosionObjDefParameterClass::Copy_Value (const ParameterClass &src) { if (src.Is_Type (ParameterClass::TYPE_AMMOOBJDEFINITIONID)) { (*m_Value) = ((ExplosionObjDefParameterClass &)src).Get_Value (); } GameObjDefParameterClass::Copy_Value (src); return ; } //*******************************************************************************************// // // Start of SoundDefParameterClass // //*******************************************************************************************// ///////////////////////////////////////////////////////////////////// // // SoundDefParameterClass // ///////////////////////////////////////////////////////////////////// SoundDefParameterClass::SoundDefParameterClass (int *id) : DefParameterClass (id) { return ; } ///////////////////////////////////////////////////////////////////// // // SoundDefParameterClass // ///////////////////////////////////////////////////////////////////// SoundDefParameterClass::SoundDefParameterClass (const SoundDefParameterClass &src) : DefParameterClass (src) { (*this) = src; return ; } ///////////////////////////////////////////////////////////////////// // // operator= // ///////////////////////////////////////////////////////////////////// const SoundDefParameterClass & SoundDefParameterClass::operator= (const SoundDefParameterClass &src) { DefParameterClass::operator= (src); return *this; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool SoundDefParameterClass::operator== (const SoundDefParameterClass &src) { bool retval = false; if (m_Value != NULL && src.m_Value != NULL && (*m_Value) == (*src.m_Value)) { retval = true; } return retval; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool SoundDefParameterClass::operator== (const ParameterClass &src) { bool retval = false; if (src.Get_Type () == Get_Type ()) { retval = SoundDefParameterClass::operator== ((const SoundDefParameterClass &)src); } return retval; } //*******************************************************************************************// // // Start of ScriptParameterClass // //*******************************************************************************************// ///////////////////////////////////////////////////////////////////// // // ScriptParameterClass // ///////////////////////////////////////////////////////////////////// ScriptParameterClass::ScriptParameterClass (StringClass *name, StringClass *params) : m_ScriptName (name), m_ScriptParams (params) { return ; } ///////////////////////////////////////////////////////////////////// // // ScriptParameterClass // ///////////////////////////////////////////////////////////////////// ScriptParameterClass::ScriptParameterClass (const ScriptParameterClass &src) : m_ScriptName (NULL), m_ScriptParams (NULL) { (*this) = src; return ; } ///////////////////////////////////////////////////////////////////// // // operator= // ///////////////////////////////////////////////////////////////////// const ScriptParameterClass & ScriptParameterClass::operator= (const ScriptParameterClass &src) { m_ScriptName = src.m_ScriptName; m_ScriptParams = src.m_ScriptParams; ParameterClass::operator= (src); return *this; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool ScriptParameterClass::operator== (const ScriptParameterClass &src) { bool retval = false; // // Data valid? // if ( (m_ScriptName != NULL) && (src.m_ScriptName != NULL) && (m_ScriptParams != NULL) && (src.m_ScriptParams != NULL)) { // // Simple string compares should workd // if ( (m_ScriptName->Compare (*(src.m_ScriptName)) == 0) && (m_ScriptParams->Compare (*(src.m_ScriptParams)) == 0)) { retval = true; } } return retval; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool ScriptParameterClass::operator== (const ParameterClass &src) { bool retval = false; if (src.Get_Type () == Get_Type ()) { retval = ScriptParameterClass::operator== ((const ScriptParameterClass &)src); } return retval; } ///////////////////////////////////////////////////////////////////// // // Copy_Value // ///////////////////////////////////////////////////////////////////// void ScriptParameterClass::Copy_Value (const ParameterClass &src) { if (src.Is_Type (ParameterClass::TYPE_SCRIPT)) { (*m_ScriptName) = ((ScriptParameterClass &)src).Get_Script_Name (); (*m_ScriptParams) = ((ScriptParameterClass &)src).Get_Params (); } ParameterClass::Copy_Value (src); return ; } //*******************************************************************************************// // // Start of DefIDListParameterClass // //*******************************************************************************************// ///////////////////////////////////////////////////////////////////// // // DefIDListParameterClass // ///////////////////////////////////////////////////////////////////// DefIDListParameterClass::DefIDListParameterClass (DynamicVectorClass<int> *list) : m_IDList (list), m_ClassID (0), m_SelectedClassID (NULL) { return ; } ///////////////////////////////////////////////////////////////////// // // DefIDListParameterClass // ///////////////////////////////////////////////////////////////////// DefIDListParameterClass::DefIDListParameterClass (const DefIDListParameterClass &src) : m_IDList (NULL), m_ClassID (0), m_SelectedClassID (NULL) { (*this) = src; return ; } ///////////////////////////////////////////////////////////////////// // // operator= // ///////////////////////////////////////////////////////////////////// const DefIDListParameterClass & DefIDListParameterClass::operator= (const DefIDListParameterClass &src) { m_IDList = src.m_IDList; m_ClassID = src.m_ClassID; m_SelectedClassID = src.m_SelectedClassID; ParameterClass::operator= (src); return *this; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool DefIDListParameterClass::operator== (const DefIDListParameterClass &src) { bool retval = false; // // Data valid? // if ((m_IDList != NULL) && (src.m_IDList != NULL)) { // // Class IDs the same? // if (m_ClassID == src.m_ClassID) { int count1 = m_IDList->Count (); int count2 = src.m_IDList->Count (); // // Are the lists the same? // retval = (count1 == count2); for (int index = 0; (index < count1) && retval; index ++) { int value1 = (*m_IDList)[index]; int value2 = (*src.m_IDList)[index]; retval &= (value1 == value2); } } } return retval; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool DefIDListParameterClass::operator== (const ParameterClass &src) { bool retval = false; if (src.Get_Type () == Get_Type ()) { retval = DefIDListParameterClass::operator== ((const DefIDListParameterClass &)src); } return retval; } ///////////////////////////////////////////////////////////////////// // // Copy_Value // ///////////////////////////////////////////////////////////////////// void DefIDListParameterClass::Copy_Value (const ParameterClass &src) { if (src.Is_Type (ParameterClass::TYPE_DEFINITIONIDLIST)) { DefIDListParameterClass real_src = (DefIDListParameterClass &)src; m_ClassID = real_src.m_ClassID; (*m_IDList) = (*real_src.m_IDList); if (m_SelectedClassID != NULL && real_src.m_SelectedClassID != NULL) { (*m_SelectedClassID) = (*real_src.m_SelectedClassID); } } ParameterClass::Copy_Value (src); return ; } //*******************************************************************************************// // // Start of ZoneParameterClass // //*******************************************************************************************// ///////////////////////////////////////////////////////////////////// // // ZoneParameterClass // ///////////////////////////////////////////////////////////////////// ZoneParameterClass::ZoneParameterClass (OBBoxClass *box) : m_OBBox (box) { return ; } ///////////////////////////////////////////////////////////////////// // // ZoneParameterClass // ///////////////////////////////////////////////////////////////////// ZoneParameterClass::ZoneParameterClass (const ZoneParameterClass &src) : m_OBBox (NULL) { (*this) = src; return ; } ///////////////////////////////////////////////////////////////////// // // operator= // ///////////////////////////////////////////////////////////////////// const ZoneParameterClass & ZoneParameterClass::operator= (const ZoneParameterClass &src) { m_OBBox = src.m_OBBox; ParameterClass::operator= (src); return *this; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool ZoneParameterClass::operator== (const ZoneParameterClass &src) { bool retval = false; // // Are the OBBoxes the same? // if ((m_OBBox != NULL) && (src.m_OBBox != NULL)) { retval = (*m_OBBox) == (*src.m_OBBox); } return retval; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool ZoneParameterClass::operator== (const ParameterClass &src) { bool retval = false; if (src.Get_Type () == Get_Type ()) { retval = ZoneParameterClass::operator== ((const ZoneParameterClass &)src); } return retval; } ///////////////////////////////////////////////////////////////////// // // Copy_Value // ///////////////////////////////////////////////////////////////////// void ZoneParameterClass::Copy_Value (const ParameterClass &src) { if (src.Is_Type (ParameterClass::TYPE_ZONE)) { ZoneParameterClass real_src = (ZoneParameterClass &)src; (*m_OBBox) = (*real_src.m_OBBox); } ParameterClass::Copy_Value (src); return ; } //*******************************************************************************************// // // Start of FilenameListParameterClass // //*******************************************************************************************// ///////////////////////////////////////////////////////////////////// // // FilenameListParameterClass // ///////////////////////////////////////////////////////////////////// FilenameListParameterClass::FilenameListParameterClass (DynamicVectorClass<StringClass> *list) : m_FilenameList (list) { return ; } ///////////////////////////////////////////////////////////////////// // // FilenameListParameterClass // ///////////////////////////////////////////////////////////////////// FilenameListParameterClass::FilenameListParameterClass (const FilenameListParameterClass &src) : m_FilenameList (NULL) { (*this) = src; return ; } ///////////////////////////////////////////////////////////////////// // // operator= // ///////////////////////////////////////////////////////////////////// const FilenameListParameterClass & FilenameListParameterClass::operator= (const FilenameListParameterClass &src) { m_FilenameList = src.m_FilenameList; ParameterClass::operator= (src); return *this; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool FilenameListParameterClass::operator== (const FilenameListParameterClass &src) { bool retval = false; // // Data valid? // if ((m_FilenameList != NULL) && (src.m_FilenameList != NULL)) { int count1 = m_FilenameList->Count (); int count2 = src.m_FilenameList->Count (); // // Are the lists the same? // retval = (count1 == count2); for (int index = 0; (index < count1) && retval; index ++) { StringClass &filename1 = (*m_FilenameList)[index]; StringClass &filename2 = (*src.m_FilenameList)[index]; retval &= (::stricmp (filename1, filename2) == 0); } } return retval; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool FilenameListParameterClass::operator== (const ParameterClass &src) { bool retval = false; if (src.Get_Type () == Get_Type ()) { retval = FilenameListParameterClass::operator== ((const FilenameListParameterClass &)src); } return retval; } ///////////////////////////////////////////////////////////////////// // // Copy_Value // ///////////////////////////////////////////////////////////////////// void FilenameListParameterClass::Copy_Value (const ParameterClass &src) { if (src.Is_Type (ParameterClass::TYPE_FILENAMELIST)) { FilenameListParameterClass real_src = (FilenameListParameterClass &)src; (*m_FilenameList) = (*real_src.m_FilenameList); } ParameterClass::Copy_Value (src); return ; } //*******************************************************************************************// // // Start of ScriptListParameterClass // //*******************************************************************************************// ///////////////////////////////////////////////////////////////////// // // ScriptListParameterClass // ///////////////////////////////////////////////////////////////////// ScriptListParameterClass::ScriptListParameterClass ( DynamicVectorClass<StringClass> *name_list, DynamicVectorClass<StringClass> *param_list ) : m_NameList (name_list), m_ParamList (param_list) { return ; } ///////////////////////////////////////////////////////////////////// // // ScriptListParameterClass // ///////////////////////////////////////////////////////////////////// ScriptListParameterClass::ScriptListParameterClass (const ScriptListParameterClass &src) : m_NameList (NULL), m_ParamList (NULL) { (*this) = src; return ; } ///////////////////////////////////////////////////////////////////// // // operator= // ///////////////////////////////////////////////////////////////////// const ScriptListParameterClass & ScriptListParameterClass::operator= (const ScriptListParameterClass &src) { m_NameList = src.m_NameList; m_ParamList = src.m_ParamList; ParameterClass::operator= (src); return *this; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool ScriptListParameterClass::operator== (const ScriptListParameterClass &src) { bool retval = false; // // Data valid? // if ( (m_NameList != NULL) && (src.m_NameList != NULL) && (m_ParamList != NULL) && (src.m_ParamList != NULL)) { retval = Are_Lists_Identical (*m_NameList, *(src.m_NameList)); retval &= Are_Lists_Identical (*m_ParamList, *(src.m_ParamList)); } return retval; } ///////////////////////////////////////////////////////////////////// // // Are_Lists_Identical // ///////////////////////////////////////////////////////////////////// bool ScriptListParameterClass::Are_Lists_Identical ( DynamicVectorClass<StringClass> &list1, DynamicVectorClass<StringClass> &list2 ) { int count1 = list1.Count (); int count2 = list2.Count (); // // Do a string compare on every entry // bool retval = (count1 == count2); for (int index = 0; (index < count1) && retval; index ++) { StringClass &string1 = list1[index]; StringClass &string2 = list2[index]; retval &= (::stricmp (string1, string2) == 0); } return retval; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool ScriptListParameterClass::operator== (const ParameterClass &src) { bool retval = false; if (src.Get_Type () == Get_Type ()) { retval = ScriptListParameterClass::operator== ((const ScriptListParameterClass &)src); } return retval; } ///////////////////////////////////////////////////////////////////// // // Copy_Value // ///////////////////////////////////////////////////////////////////// void ScriptListParameterClass::Copy_Value (const ParameterClass &src) { if (src.Is_Type (ParameterClass::TYPE_SCRIPTLIST)) { ScriptListParameterClass &real_src = (ScriptListParameterClass &)src; (*m_NameList) = (*real_src.m_NameList); (*m_ParamList) = (*real_src.m_ParamList); } ParameterClass::Copy_Value (src); return ; } //*******************************************************************************************// // // Start of SeparatorParameterClass // //*******************************************************************************************// ///////////////////////////////////////////////////////////////////// // // SeparatorParameterClass // ///////////////////////////////////////////////////////////////////// SeparatorParameterClass::SeparatorParameterClass (const SeparatorParameterClass &src) { (*this) = src; return ; } ///////////////////////////////////////////////////////////////////// // // operator= // ///////////////////////////////////////////////////////////////////// const SeparatorParameterClass & SeparatorParameterClass::operator= (const SeparatorParameterClass &src) { ParameterClass::operator= (src); return *this; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool SeparatorParameterClass::operator== (const SeparatorParameterClass &src) { return true; } ///////////////////////////////////////////////////////////////////// // // operator== // ///////////////////////////////////////////////////////////////////// bool SeparatorParameterClass::operator== (const ParameterClass &src) { bool retval = false; if (src.Get_Type () == Get_Type ()) { retval = SeparatorParameterClass::operator== ((const SeparatorParameterClass &)src); } return retval; } ///////////////////////////////////////////////////////////////////// // // Copy_Value // ///////////////////////////////////////////////////////////////////// void SeparatorParameterClass::Copy_Value (const ParameterClass &src) { ParameterClass::Copy_Value (src); return ; }
411
0.696014
1
0.696014
game-dev
MEDIA
0.516857
game-dev
0.76208
1
0.76208
chrislo/sourceclassifier
24,802
sources/java/meteor.java-2.java
/* The Computer Language Benchmarks Game http://shootout.alioth.debian.org/ transliterated from C++ (Ben St. John) and D (Michael Deardeuff) by Amir K aka Razii */ import java.util.*; public final class meteor { static final int X = 0; static final int Y = 1; static final int N_DIM = 2; static final int EVEN = 0; static final int ODD = 1; static final int N_PARITY = 2; static final int GOOD = 0; static final int BAD = 1; static final int ALWAYS_BAD = 2; static final int OPEN = 0; static final int CLOSED = 1; static final int N_FIXED = 2; static final int MAX_ISLAND_OFFSET = 1024; static final int N_COL = 5; static final int N_ROW = 10; static final int N_CELL = N_COL * N_ROW; static final int N_PIECE_TYPE = 10; static final int N_ORIENT = 12; //-- Globals ------------------------- static IslandInfo[] g_islandInfo = new IslandInfo [MAX_ISLAND_OFFSET]; static int g_nIslandInfo = 0; static OkPieces[][] g_okPieces = new OkPieces [N_ROW][N_COL]; static final int g_firstRegion[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x01, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x0c, 0x01, 0x0e, 0x0f, 0x10, 0x01, 0x02, 0x03, 0x04, 0x01, 0x06, 0x07, 0x18, 0x01, 0x02, 0x03, 0x1c, 0x01, 0x1e, 0x1f }; static final int g_flip[] = { 0x00, 0x10, 0x08, 0x18, 0x04, 0x14, 0x0c, 0x1c, 0x02, 0x12, 0x0a, 0x1a, 0x06, 0x16, 0x0e, 0x1e, 0x01, 0x11, 0x09, 0x19, 0x05, 0x15, 0x0d, 0x1d, 0x03, 0x13, 0x0b, 0x1b, 0x07, 0x17, 0x0f, 0x1f, }; static final int[] s_firstOne = { 0, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, }; static int getMask(int iPos) { return (1 << (iPos)); } static int floor(int top, int bot) { int toZero = top / bot; // negative numbers should be rounded down, not towards zero; if ((toZero * bot != top) && ((top < 0) != (bot <= 0))) toZero--; return toZero; } static int getFirstOne(int v) { int startPos = 0; if (v == 0) return 0; int iPos = startPos; int mask = 0xff << startPos; while ((mask & v) == 0) { mask <<= 8; iPos += 8; } int result = (mask & v) >> iPos; int resultLow = result & 0x0f; if (resultLow != 0) iPos += s_firstOne[resultLow]; else iPos += 4 + s_firstOne[result >> 4]; return iPos; } static int countOnes(int v) { int n = 0; while (v != 0) { n++; v = v & (v - 1); } return n; } static int flipTwoRows(int bits) { int flipped = g_flip[bits >> N_COL] << N_COL; return (flipped | g_flip[bits & Board.TOP_ROW]); } static void markBad(IslandInfo info, int mask, int eo, boolean always) { info.hasBad[eo][OPEN] |= mask; info.hasBad[eo][CLOSED] |= mask; if (always) info.alwaysBad[eo] |= mask; } static void initGlobals() { for (int i = 0; i < MAX_ISLAND_OFFSET; i++) { g_islandInfo[i] = new IslandInfo(); } for (int i = 0; i < N_ROW; i++) { for (int j = 0; j < N_COL; j++) g_okPieces[i][j] = new OkPieces(); } } //-- Classes -------------------------; static class OkPieces { byte[] nPieces = new byte[N_PIECE_TYPE]; int[][] pieceVec = new int[N_PIECE_TYPE][N_ORIENT]; } static class IslandInfo { int[][] hasBad = new int[N_FIXED][N_PARITY]; int[][] isKnown = new int[N_FIXED][N_PARITY]; int[] alwaysBad = new int[N_PARITY]; } static class Soln { static final int NO_PIECE = -1; boolean isEmpty() { return (m_nPiece == 0); } void popPiece() { m_nPiece--; m_synched = false; } void pushPiece(int vec, int iPiece, int row) { SPiece p = m_pieces[m_nPiece++]; p.vec = vec; p.iPiece = (short) iPiece; p.row = (short) row; } Soln() { m_synched = false; m_nPiece = 0; init(); } class SPiece { int vec; short iPiece; short row; SPiece() {} SPiece(int avec, int apiece, int arow) { vec = avec; iPiece = (short)apiece; row = (short)arow; } SPiece(SPiece other) { vec = other.vec; iPiece = other.iPiece; row = other.row; } } SPiece[] m_pieces = new SPiece [N_PIECE_TYPE]; int m_nPiece; byte[][] m_cells = new byte [N_ROW][N_COL]; boolean m_synched; void init() { for (int i = 0; i < N_PIECE_TYPE; i++) m_pieces[i] = new SPiece(); } Soln (int fillVal) { init(); m_nPiece = 0; fill(fillVal); } public Soln clone2() { Soln s = new Soln(); for (int i = 0; i < m_pieces.length; i++) s.m_pieces[i] = new SPiece(m_pieces[i]); s.m_nPiece = m_nPiece; //System.arraycopy(m_cells, 0, s.m_cells, 0, N_CELL); for (int i = 0; i < N_ROW; i++) { for (int j = 0; j < N_COL; j ++) { s.m_cells[i][j] = m_cells[i][j]; } } s.m_synched = m_synched; return s; } void fill(int val) { m_synched = false; for (int i = 0; i < N_ROW; i++) { for (int j = 0; j < N_COL; j++) m_cells[i][j] = (byte) val; } } public String toString() { StringBuffer result = new StringBuffer(N_CELL * 2); for (int y = 0; y < N_ROW; y++) { for (int x = 0; x < N_COL; x++) { int val = m_cells[y][x]; //if (val == NO_PIECE) result.append('.'); { result.append(val); } result.append(' '); } result.append('\n'); // indent every second line if (y % 2 == 0) result.append(" "); } return result.toString(); } void setCells() { if (m_synched) return; for (int iPiece = 0; iPiece < m_nPiece; iPiece++) { SPiece p = m_pieces[iPiece]; int vec = p.vec; byte pID = (byte) p.iPiece; int rowOffset = p.row; int nNewCells = 0; for (int y = rowOffset; y < N_ROW; y++) { for (int x = 0; x < N_COL; x++) { if ((vec & 1) != 0) { m_cells[y][x] = pID; nNewCells++; } vec >>= 1; } if (nNewCells == Piece.N_ELEM) break; } } m_synched = true; } boolean lessThan(Soln r) { if (m_pieces[0].iPiece != r.m_pieces[0].iPiece) { return m_pieces[0].iPiece < r.m_pieces[0].iPiece; } setCells(); r.setCells(); for (int y = 0; y < N_ROW; y++) { for (int x = 0; x < N_COL; x++) { int lval = m_cells[y][x]; int rval = r.m_cells[y][x]; if (lval != rval) return (lval < rval); } } return false; } void spin(Soln spun) { setCells(); for (int y = 0; y < N_ROW; y++) { for (int x = 0; x < N_COL; x++) { byte flipped = m_cells[N_ROW - y - 1][N_COL - x - 1]; spun.m_cells[y][x] = flipped; } } spun.m_pieces[0].iPiece = m_pieces[N_PIECE_TYPE - 1].iPiece; spun.m_synched = true; } } //----------------------- static class Board { static final int L_EDGE_MASK = ((1 << 0) | (1 << 5) | (1 << 10) | (1 << 15) | (1 << 20) | (1 << 25) | (1 << 30)); static final int R_EDGE_MASK = L_EDGE_MASK << 4; static final int TOP_ROW = (1 << N_COL) - 1; static final int ROW_0_MASK = TOP_ROW | (TOP_ROW << 10) | (TOP_ROW << 20) | (TOP_ROW << 30); static final int ROW_1_MASK = ROW_0_MASK << 5; static final int BOARD_MASK = (1 << 30) - 1; static int getIndex(int x, int y) { return y * N_COL + x; } Soln m_curSoln; Soln m_minSoln; Soln m_maxSoln; int m_nSoln; Board () { m_curSoln = new Soln(Soln.NO_PIECE); m_minSoln = new Soln(N_PIECE_TYPE); m_maxSoln = new Soln(Soln.NO_PIECE); m_nSoln = (0); } static boolean badRegion(int[] toFill, int rNew) { // grow empty region, until it doesn't change any more; int region; do { region = rNew; // simple grow up/down rNew |= (region >> N_COL); rNew |= (region << N_COL); // grow right/left rNew |= (region & ~L_EDGE_MASK) >> 1; rNew |= (region & ~R_EDGE_MASK) << 1; // tricky growth int evenRegion = region & (ROW_0_MASK & ~L_EDGE_MASK); rNew |= evenRegion >> (N_COL + 1); rNew |= evenRegion << (N_COL - 1); int oddRegion = region & (ROW_1_MASK & ~R_EDGE_MASK); rNew |= oddRegion >> (N_COL - 1); rNew |= oddRegion << (N_COL + 1); // clamp against existing pieces rNew &= toFill[0]; } while ((rNew != toFill[0]) && (rNew != region)); // subtract empty region from board toFill[0] ^= rNew; int nCells = countOnes(toFill[0]); return (nCells % Piece.N_ELEM != 0); } static int hasBadIslands(int boardVec, int row) { // skip over any filled rows while ((boardVec & TOP_ROW) == TOP_ROW) { boardVec >>= N_COL; row++; } int iInfo = boardVec & ((1 << 2 * N_COL) - 1); IslandInfo info = g_islandInfo[iInfo]; int lastRow = (boardVec >> (2 * N_COL)) & TOP_ROW; int mask = getMask(lastRow); int isOdd = row & 1; if ((info.alwaysBad[isOdd] & mask) != 0) return BAD; if ((boardVec & (TOP_ROW << N_COL * 3)) != 0) return calcBadIslands(boardVec, row); int isClosed = (row > 6) ? 1 : 0; if ((info.isKnown[isOdd][isClosed] & mask) != 0) return (info.hasBad[isOdd][isClosed] & mask); if (boardVec == 0) return GOOD; int hasBad = calcBadIslands(boardVec, row); info.isKnown[isOdd][isClosed] |= mask; if (hasBad != 0) info.hasBad[isOdd][isClosed] |= mask; return hasBad; } static int calcBadIslands(int boardVec, int row) { int[] toFill = {~boardVec}; if ((row & 1) != 0) { row--; toFill[0] <<= N_COL; } int boardMask = BOARD_MASK; if (row > 4) { int boardMaskShift = (row - 4) * N_COL; boardMask >>= boardMaskShift; } toFill[0] &= boardMask; // a little pre-work to speed things up int bottom = (TOP_ROW << (5 * N_COL)); boolean filled = ((bottom & toFill[0]) == bottom); while ((bottom & toFill[0]) == bottom) { toFill[0] ^= bottom; bottom >>= N_COL; } int startRegion; if (filled || (row < 4)) startRegion = bottom & toFill[0]; else { startRegion = g_firstRegion[toFill[0] & TOP_ROW]; if (startRegion == 0) { startRegion = (toFill[0] >> N_COL) & TOP_ROW; startRegion = g_firstRegion[startRegion]; startRegion <<= N_COL; } startRegion |= (startRegion << N_COL) & toFill[0]; } while (toFill[0] != 0) { if (badRegion(toFill, startRegion)) return ((toFill[0]!=0) ? ALWAYS_BAD : BAD); int iPos = getFirstOne(toFill[0]); startRegion = getMask(iPos); } return GOOD; } static void calcAlwaysBad() { for (int iWord = 1; iWord < MAX_ISLAND_OFFSET; iWord++) { IslandInfo isleInfo = g_islandInfo[iWord]; IslandInfo flipped = g_islandInfo[flipTwoRows(iWord)]; for (int i = 0, mask = 1; i < 32; i++, mask <<= 1) { int boardVec = (i << (2 * N_COL)) | iWord; if ((isleInfo.isKnown[0][OPEN] & mask) != 0) continue; int hasBad = calcBadIslands(boardVec, 0); if (hasBad != GOOD) { boolean always = (hasBad==ALWAYS_BAD); markBad(isleInfo, mask, EVEN, always); int flipMask = getMask(g_flip[i]); markBad(flipped, flipMask, ODD, always); } } flipped.isKnown[1][OPEN] = -1; isleInfo.isKnown[0][OPEN] = -1; } } static boolean hasBadIslandsSingle(int boardVec, int row) { int[] toFill = {~boardVec}; boolean isOdd = ((row & 1) != 0); if (isOdd) { row--; toFill[0] <<= N_COL; // shift to even aligned toFill[0] |= TOP_ROW; } int startRegion = TOP_ROW; int lastRow = TOP_ROW << (5 * N_COL); int boardMask = BOARD_MASK; // all but the first two bits if (row >= 4) boardMask >>= ((row - 4) * N_COL); else if (isOdd || (row == 0)) startRegion = lastRow; toFill[0] &= boardMask; startRegion &= toFill[0]; while (toFill[0] != 0) { if (badRegion(toFill, startRegion)) return true; int iPos = getFirstOne(toFill[0]); startRegion = getMask(iPos); } return false; } void genAllSolutions(int boardVec, int placedPieces, int row) { while ((boardVec & TOP_ROW) == TOP_ROW) { boardVec >>= N_COL; row++; } int iNextFill = s_firstOne[~boardVec & TOP_ROW]; OkPieces allowed = g_okPieces[row][iNextFill]; int iPiece = getFirstOne(~placedPieces); int pieceMask = getMask(iPiece); for (; iPiece < N_PIECE_TYPE; iPiece++, pieceMask <<= 1) { if ((pieceMask & placedPieces) != 0) continue; placedPieces |= pieceMask; for (int iOrient = 0; iOrient < allowed.nPieces[iPiece]; iOrient++) { int pieceVec = allowed.pieceVec[iPiece][iOrient]; if ((pieceVec & boardVec) != 0) continue; boardVec |= pieceVec; if ((hasBadIslands(boardVec, row)) != 0) { boardVec ^= pieceVec; continue; } m_curSoln.pushPiece(pieceVec, iPiece, row); // recur or record solution if (placedPieces != Piece.ALL_PIECE_MASK) genAllSolutions(boardVec, placedPieces, row); else recordSolution(m_curSoln); boardVec ^= pieceVec; m_curSoln.popPiece(); } placedPieces ^= pieceMask; } } void recordSolution(Soln s) { m_nSoln += 2; if (m_minSoln.isEmpty()) { m_minSoln = m_maxSoln = s.clone2(); return; } if (s.lessThan(m_minSoln)) m_minSoln = s.clone2(); else if (m_maxSoln.lessThan(s)) m_maxSoln = s.clone2(); Soln spun = new Soln(); s.spin(spun); if (spun.lessThan(m_minSoln)) m_minSoln = spun; else if (m_maxSoln.lessThan(spun)) m_maxSoln = spun; } } //---------------------- static class Piece { class Instance { long m_allowed; int m_vec; int m_offset; } static final int N_ELEM = 5; static final int ALL_PIECE_MASK = (1 << N_PIECE_TYPE) - 1; static final int SKIP_PIECE = 5; static final int BaseVecs[] = { 0x10f, 0x0cb, 0x1087, 0x427, 0x465, 0x0c7, 0x8423, 0x0a7, 0x187, 0x08f }; static Piece[][] s_basePiece = new Piece [N_PIECE_TYPE][N_ORIENT]; Instance[] m_instance = new Instance [N_PARITY]; void init() { for (int i = 0; i < N_PARITY; i++) m_instance[i] = new Instance(); } Piece() { init(); } static { for (int i = 0; i < N_PIECE_TYPE; i++) { for (int j = 0; j < N_ORIENT; j++) s_basePiece[i][j] = new Piece(); } } static void setCoordList(int vec, int[][] pts) { int iPt = 0; int mask = 1; for (int y = 0; y < N_ROW; y++) { for (int x = 0; x < N_COL; x++) { if ((mask & vec) != 0) { pts[iPt][X] = x; pts[iPt][Y] = y; iPt++; } mask <<= 1; } } } static int toBitVector(int[][] pts) { int y, x; int result = 0; for (int iPt = 0; iPt < N_ELEM; iPt++) { x = pts[iPt][X]; y = pts[iPt][Y]; int pos = Board.getIndex(x, y); result |= (1 << pos); } return result; } static void shiftUpLines(int[][] pts, int shift) { for (int iPt = 0; iPt < N_ELEM; iPt++) { if ((pts[iPt][Y] & shift & 0x1) != 0) (pts[iPt][X])++; pts[iPt][Y] -= shift; } } static int shiftToX0(int[][] pts, Instance instance, int offsetRow) { int x, y, iPt; int xMin = pts[0][X]; int xMax = xMin; for (iPt = 1; iPt < N_ELEM; iPt++) { x = pts[iPt][X]; y = pts[iPt][Y]; if (x < xMin) xMin = x; else if (x > xMax) xMax = x; } int offset = N_ELEM; for (iPt = 0; iPt < N_ELEM; iPt++) { pts[iPt][X] -= xMin; if ((pts[iPt][Y] == offsetRow) && (pts[iPt][X] < offset)) offset = pts[iPt][X]; } instance.m_offset = offset; instance.m_vec = toBitVector(pts); return xMax - xMin; } void setOkPos(int isOdd, int w, int h) { Instance p = m_instance[isOdd]; p.m_allowed = 0; long posMask = 1L << (isOdd * N_COL); for (int y = isOdd; y < N_ROW - h; y+=2, posMask <<= N_COL) { if ((p.m_offset) != 0) posMask <<= p.m_offset; for (int xPos = 0; xPos < N_COL - p.m_offset; xPos++, posMask <<= 1) { if (xPos >= N_COL - w) continue; int pieceVec = p.m_vec << xPos; if (Board.hasBadIslandsSingle(pieceVec, y)) continue; p.m_allowed |= posMask; } } } static void genOrientation(int vec, int iOrient, Piece target) { int[][] pts = new int[N_ELEM][N_DIM]; setCoordList(vec, pts); int y, x, iPt; int rot = iOrient % 6; int flip = iOrient >= 6 ? 1 : 0; if (flip != 0) { for (iPt = 0; iPt < N_ELEM; iPt++) pts[iPt][Y] = -pts[iPt][Y]; } while ((rot--) != 0) { for (iPt = 0; iPt < N_ELEM; iPt++) { x = pts[iPt][X]; y = pts[iPt][Y]; int xNew = floor((2 * x - 3 * y + 1), 4); int yNew = floor((2 * x + y + 1), 2); pts[iPt][X] = xNew; pts[iPt][Y] = yNew; } } int yMin = pts[0][Y]; int yMax = yMin; for (iPt = 1; iPt < N_ELEM; iPt++) { y = pts[iPt][Y]; if (y < yMin) yMin = y; else if (y > yMax) yMax = y; } int h = yMax - yMin; Instance even = target.m_instance[EVEN]; Instance odd = target.m_instance[ODD]; shiftUpLines(pts, yMin); int w = shiftToX0(pts, even, 0); target.setOkPos(EVEN, w, h); even.m_vec >>= even.m_offset; shiftUpLines(pts, -1); w = shiftToX0(pts, odd, 1); odd.m_vec >>= N_COL; target.setOkPos(ODD, w, h); odd.m_vec >>= odd.m_offset; } static void genAllOrientations() { for (int iPiece = 0; iPiece < N_PIECE_TYPE; iPiece++) { int refPiece = BaseVecs[iPiece]; for (int iOrient = 0; iOrient < N_ORIENT; iOrient++) { Piece p = s_basePiece[iPiece][iOrient]; genOrientation(refPiece, iOrient, p); if ((iPiece == SKIP_PIECE) && (((iOrient / 3) & 1) != 0)) p.m_instance[0].m_allowed = p.m_instance[1].m_allowed = 0; } } for (int iPiece = 0; iPiece < N_PIECE_TYPE; iPiece++) { for (int iOrient = 0; iOrient < N_ORIENT; iOrient++) { long mask = 1; for (int iRow = 0; iRow < N_ROW; iRow++) { Instance p = getPiece(iPiece, iOrient, (iRow & 1)); for (int iCol = 0; iCol < N_COL; iCol++) { OkPieces allowed = g_okPieces[iRow][iCol]; if ((p.m_allowed & mask) != 0) { allowed.pieceVec[iPiece][allowed.nPieces[iPiece]] = p.m_vec << iCol; (allowed.nPieces[iPiece])++; } mask <<= 1; } } } } } static Instance getPiece(int iPiece, int iOrient, int iParity) { return s_basePiece[iPiece][iOrient].m_instance[iParity]; } } //-- Main --------------------------- public static void main(String[] args) { if (args.length > 2) System.exit(-1); // spec says this is an error; initGlobals(); Board b = new Board(); Piece.genAllOrientations(); Board.calcAlwaysBad(); b.genAllSolutions(0, 0, 0); System.out.println(b.m_nSoln + " solutions found\n"); System.out.println(b.m_minSoln); System.out.println(b.m_maxSoln); } }
411
0.963511
1
0.963511
game-dev
MEDIA
0.420786
game-dev
0.97883
1
0.97883
MCreator-Examples/Tale-of-Biomes
3,661
src/main/java/net/nwtg/taleofbiomes/block/entity/HangingLanternBlockEntity.java
package net.nwtg.taleofbiomes.block.entity; import net.nwtg.taleofbiomes.init.TaleOfBiomesModBlockEntities; import net.neoforged.neoforge.items.wrapper.SidedInvWrapper; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.entity.RandomizableContainerBlockEntity; import net.minecraft.world.item.ItemStack; import net.minecraft.world.inventory.ChestMenu; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.WorldlyContainer; import net.minecraft.world.ContainerHelper; import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; import net.minecraft.network.chat.Component; import net.minecraft.nbt.CompoundTag; import net.minecraft.core.NonNullList; import net.minecraft.core.HolderLookup; import net.minecraft.core.Direction; import net.minecraft.core.BlockPos; import javax.annotation.Nullable; import java.util.stream.IntStream; public class HangingLanternBlockEntity extends RandomizableContainerBlockEntity implements WorldlyContainer { private NonNullList<ItemStack> stacks = NonNullList.<ItemStack>withSize(0, ItemStack.EMPTY); private final SidedInvWrapper handler = new SidedInvWrapper(this, null); public HangingLanternBlockEntity(BlockPos position, BlockState state) { super(TaleOfBiomesModBlockEntities.HANGING_LANTERN.get(), position, state); } @Override public void loadAdditional(CompoundTag compound, HolderLookup.Provider lookupProvider) { super.loadAdditional(compound, lookupProvider); if (!this.tryLoadLootTable(compound)) this.stacks = NonNullList.withSize(this.getContainerSize(), ItemStack.EMPTY); ContainerHelper.loadAllItems(compound, this.stacks, lookupProvider); } @Override public void saveAdditional(CompoundTag compound, HolderLookup.Provider lookupProvider) { super.saveAdditional(compound, lookupProvider); if (!this.trySaveLootTable(compound)) { ContainerHelper.saveAllItems(compound, this.stacks, lookupProvider); } } @Override public ClientboundBlockEntityDataPacket getUpdatePacket() { return ClientboundBlockEntityDataPacket.create(this); } @Override public CompoundTag getUpdateTag(HolderLookup.Provider lookupProvider) { return this.saveWithFullMetadata(lookupProvider); } @Override public int getContainerSize() { return stacks.size(); } @Override public boolean isEmpty() { for (ItemStack itemstack : this.stacks) if (!itemstack.isEmpty()) return false; return true; } @Override public Component getDefaultName() { return Component.literal("hanging_lantern"); } @Override public int getMaxStackSize() { return 64; } @Override public AbstractContainerMenu createMenu(int id, Inventory inventory) { return ChestMenu.threeRows(id, inventory); } @Override public Component getDisplayName() { return Component.literal("Hanging Lantern"); } @Override protected NonNullList<ItemStack> getItems() { return this.stacks; } @Override protected void setItems(NonNullList<ItemStack> stacks) { this.stacks = stacks; } @Override public boolean canPlaceItem(int index, ItemStack stack) { return true; } @Override public int[] getSlotsForFace(Direction side) { return IntStream.range(0, this.getContainerSize()).toArray(); } @Override public boolean canPlaceItemThroughFace(int index, ItemStack stack, @Nullable Direction direction) { return this.canPlaceItem(index, stack); } @Override public boolean canTakeItemThroughFace(int index, ItemStack stack, Direction direction) { return true; } public SidedInvWrapper getItemHandler() { return handler; } }
411
0.936128
1
0.936128
game-dev
MEDIA
0.999117
game-dev
0.948278
1
0.948278
IAFEnvoy/IceAndFire-Fabric
3,494
src/main/java/com/iafenvoy/iceandfire/world/structure/LightningDragonCaveStructure.java
package com.iafenvoy.iceandfire.world.structure; import com.iafenvoy.iceandfire.IceAndFire; import com.iafenvoy.iceandfire.entity.EntityDragonBase; import com.iafenvoy.iceandfire.registry.IafBlocks; import com.iafenvoy.iceandfire.registry.IafEntities; import com.iafenvoy.iceandfire.registry.IafStructurePieces; import com.iafenvoy.iceandfire.registry.IafStructureTypes; import com.iafenvoy.iceandfire.registry.tag.IafBlockTags; import com.mojang.serialization.Codec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.entity.EntityType; import net.minecraft.nbt.NbtCompound; import net.minecraft.registry.tag.TagKey; import net.minecraft.structure.StructureContext; import net.minecraft.util.Identifier; import net.minecraft.util.math.BlockBox; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.random.Random; import net.minecraft.world.gen.structure.StructureType; public class LightningDragonCaveStructure extends DragonCaveStructure { public static final Codec<LightningDragonCaveStructure> CODEC = RecordCodecBuilder.<LightningDragonCaveStructure>mapCodec(instance -> instance.group(configCodecBuilder(instance)).apply(instance, LightningDragonCaveStructure::new)).codec(); protected LightningDragonCaveStructure(Config config) { super(config); } @Override protected DragonCavePiece createPiece(BlockBox boundingBox, boolean male, BlockPos offset, int y, long seed) { return new LightningDragonCavePiece(0, boundingBox, male, offset, y, seed); } @Override public StructureType<?> getType() { return IafStructureTypes.LIGHTNING_DRAGON_CAVE; } public static class LightningDragonCavePiece extends DragonCavePiece { public static final Identifier LIGHTNING_DRAGON_CHEST = new Identifier(IceAndFire.MOD_ID, "chest/lightning_dragon_female_cave"); public static final Identifier LIGHTNING_DRAGON_CHEST_MALE = new Identifier(IceAndFire.MOD_ID, "chest/lightning_dragon_male_cave"); protected LightningDragonCavePiece(int length, BlockBox boundingBox, boolean male, BlockPos offset, int y, long seed) { super(IafStructurePieces.LIGHTNING_DRAGON_CAVE, length, boundingBox, male, offset, y, seed); } public LightningDragonCavePiece(StructureContext context, NbtCompound nbt) { super(IafStructurePieces.LIGHTNING_DRAGON_CAVE, nbt); } @Override protected TagKey<Block> getOreTag() { return IafBlockTags.LIGHTNING_DRAGON_CAVE_ORES; } @Override protected WorldGenCaveStalactites getCeilingDecoration() { return new WorldGenCaveStalactites(IafBlocks.CRACKLED_STONE, 6); } @Override protected BlockState getTreasurePile() { return IafBlocks.COPPER_PILE.getDefaultState(); } @Override protected BlockState getPaletteBlock(Random random) { return (random.nextBoolean() ? IafBlocks.CRACKLED_STONE : IafBlocks.CRACKLED_COBBLESTONE).getDefaultState(); } @Override protected Identifier getChestTable(boolean male) { return male ? LIGHTNING_DRAGON_CHEST_MALE : LIGHTNING_DRAGON_CHEST; } @Override protected EntityType<? extends EntityDragonBase> getDragonType() { return IafEntities.LIGHTNING_DRAGON; } } }
411
0.770522
1
0.770522
game-dev
MEDIA
0.962735
game-dev
0.562271
1
0.562271