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
cocos2d/cocos2d-x-samples
3,685
samples/LiquidFun-Testbed/Classes/Tests/VerticalStack.h
/* * Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef VERTICAL_STACK_H #define VERTICAL_STACK_H class VerticalStack : public Test { public: enum { e_columnCount = 5, e_rowCount = 16 //e_columnCount = 1, //e_rowCount = 1 }; VerticalStack() { { b2BodyDef bd; b2Body* ground = m_world->CreateBody(&bd); b2EdgeShape shape; shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); ground->CreateFixture(&shape, 0.0f); shape.Set(b2Vec2(20.0f, 0.0f), b2Vec2(20.0f, 20.0f)); ground->CreateFixture(&shape, 0.0f); } float32 xs[5] = {0.0f, -10.0f, -5.0f, 5.0f, 10.0f}; for (int32 j = 0; j < e_columnCount; ++j) { b2PolygonShape shape; shape.SetAsBox(0.5f, 0.5f); b2FixtureDef fd; fd.shape = &shape; fd.density = 1.0f; fd.friction = 0.3f; for (int i = 0; i < e_rowCount; ++i) { b2BodyDef bd; bd.type = b2_dynamicBody; int32 n = j * e_rowCount + i; b2Assert(n < e_rowCount * e_columnCount); m_indices[n] = n; bd.userData = m_indices + n; float32 x = 0.0f; //float32 x = RandomFloat(-0.02f, 0.02f); //float32 x = i % 2 == 0 ? -0.025f : 0.025f; bd.position.Set(xs[j] + x, 0.752f + 1.54f * i); b2Body* body = m_world->CreateBody(&bd); m_bodies[n] = body; body->CreateFixture(&fd); } } m_bullet = NULL; } void Keyboard(unsigned char key) { switch (key) { case ',': if (m_bullet != NULL) { m_world->DestroyBody(m_bullet); m_bullet = NULL; } { b2CircleShape shape; shape.m_radius = 0.25f; b2FixtureDef fd; fd.shape = &shape; fd.density = 20.0f; fd.restitution = 0.05f; b2BodyDef bd; bd.type = b2_dynamicBody; bd.bullet = true; bd.position.Set(-31.0f, 5.0f); m_bullet = m_world->CreateBody(&bd); m_bullet->CreateFixture(&fd); m_bullet->SetLinearVelocity(b2Vec2(400.0f, 0.0f)); } break; } } void Step(Settings* settings) { Test::Step(settings); m_debugDraw.DrawString(5, m_textLine, "Press: (,) to launch a bullet."); m_textLine += DRAW_STRING_NEW_LINE; //if (m_stepCount == 300) //{ // if (m_bullet != NULL) // { // m_world->DestroyBody(m_bullet); // m_bullet = NULL; // } // { // b2CircleShape shape; // shape.m_radius = 0.25f; // b2FixtureDef fd; // fd.shape = &shape; // fd.density = 20.0f; // fd.restitution = 0.05f; // b2BodyDef bd; // bd.type = b2_dynamicBody; // bd.bullet = true; // bd.position.Set(-31.0f, 5.0f); // m_bullet = m_world->CreateBody(&bd); // m_bullet->CreateFixture(&fd); // m_bullet->SetLinearVelocity(b2Vec2(400.0f, 0.0f)); // } //} } static Test* Create() { return new VerticalStack; } b2Body* m_bullet; b2Body* m_bodies[e_rowCount * e_columnCount]; int32 m_indices[e_rowCount * e_columnCount]; }; #endif
412
0.909226
1
0.909226
game-dev
MEDIA
0.861859
game-dev,testing-qa
0.706608
1
0.706608
jewer3330/plato
10,849
plato/Assets/Editor/SkillExtension/Table/Gen/spawnmonster.cs
/* !!auto gen do not change */ using UnityEngine; using System; using System.Collections; using System.Collections.Generic; namespace Table { public partial class spawnmonster { public int id; public int mapid; public int stage; public int arrindex; public int baseid; public float spawnx; public float spawny; public float spawnz; public string RelativePosition; static int memberCount = 9 ; public spawnmonster() { } public spawnmonster( int id, int mapid, int stage, int arrindex, int baseid, float spawnx, float spawny, float spawnz, string RelativePosition) { this.id = id; this.mapid = mapid; this.stage = stage; this.arrindex = arrindex; this.baseid = baseid; this.spawnx = spawnx; this.spawny = spawny; this.spawnz = spawnz; this.RelativePosition = RelativePosition; } public static Dictionary<int, spawnmonster> _datas = new Dictionary<int, spawnmonster>(); public static bool loaded = false; public static Dictionary<int, spawnmonster> datas { get { if(!loaded) { LoadBinFromResources(); } return _datas; } set { _datas = value; } } public static void LoadFromBinanry(byte[] bytes) { System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes); System.IO.BinaryReader br = new System.IO.BinaryReader(ms); int length = br.ReadInt32(); for (int i = 0; i < length; i++) { br.ReadByte(); } int looplength = br.ReadInt32(); for (int i = 0; i < looplength; i++) { spawnmonster dataspawnmonster = new spawnmonster(); dataspawnmonster.id = br.ReadInt32(); dataspawnmonster.mapid = br.ReadInt32(); dataspawnmonster.stage = br.ReadInt32(); dataspawnmonster.arrindex = br.ReadInt32(); dataspawnmonster.baseid = br.ReadInt32(); dataspawnmonster.spawnx = br.ReadSingle(); dataspawnmonster.spawny = br.ReadSingle(); dataspawnmonster.spawnz = br.ReadSingle(); dataspawnmonster.RelativePosition = br.ReadString(); if (_datas.ContainsKey(dataspawnmonster.id)) { #if UNITY_EDITOR UnityEditor.EditorApplication.isPaused = true; #endif throw new ArgumentException("数据有误,主键重复:" + dataspawnmonster.id); } _datas.Add(dataspawnmonster.id,dataspawnmonster); } br.Close(); ms.Close(); } public static void LoadFromString(string data) { string content = data; string[] lines = content.Split('\n'); for (int i = 3; i < lines.Length; i++) { string line = lines[i]; line = line.Replace("\r", ""); if(string.IsNullOrEmpty(line)) continue; string[] values = line.Split('\t'); if(values.Length != memberCount) { Debug.LogError("spawnmonster严重错误,表头和表数据长度不一样"); #if UNITY_EDITOR UnityEditor.EditorApplication.isPaused = true; #endif throw new ArgumentException("spawnmonster严重错误,表头和表数据长度不一样"); } spawnmonster dataspawnmonster = new spawnmonster(); if(!int.TryParse(values[0],out dataspawnmonster.id)) { #if UNITY_EDITOR Debug.LogError("数据有误:" + values[0] + " to int"); UnityEditor.EditorApplication.isPaused = true; #endif throw new ArgumentException("数据有误:" + values[0] + " to int" + " 第"+ i + "行,第0列"); } if(!int.TryParse(values[1],out dataspawnmonster.mapid)) { #if UNITY_EDITOR Debug.LogError("数据有误:" + values[1] + " to int"); UnityEditor.EditorApplication.isPaused = true; #endif throw new ArgumentException("数据有误:" + values[1] + " to int" + " 第"+ i + "行,第1列"); } if(!int.TryParse(values[2],out dataspawnmonster.stage)) { #if UNITY_EDITOR Debug.LogError("数据有误:" + values[2] + " to int"); UnityEditor.EditorApplication.isPaused = true; #endif throw new ArgumentException("数据有误:" + values[2] + " to int" + " 第"+ i + "行,第2列"); } if(!int.TryParse(values[3],out dataspawnmonster.arrindex)) { #if UNITY_EDITOR Debug.LogError("数据有误:" + values[3] + " to int"); UnityEditor.EditorApplication.isPaused = true; #endif throw new ArgumentException("数据有误:" + values[3] + " to int" + " 第"+ i + "行,第3列"); } if(!int.TryParse(values[4],out dataspawnmonster.baseid)) { #if UNITY_EDITOR Debug.LogError("数据有误:" + values[4] + " to int"); UnityEditor.EditorApplication.isPaused = true; #endif throw new ArgumentException("数据有误:" + values[4] + " to int" + " 第"+ i + "行,第4列"); } if(!float.TryParse(values[5],out dataspawnmonster.spawnx)) { #if UNITY_EDITOR Debug.LogError("数据有误:" + values[5] + " to float"); UnityEditor.EditorApplication.isPaused = true; #endif throw new ArgumentException("数据有误:" + values[5] + " to float" + " 第"+ i + "行,第5列"); } if(!float.TryParse(values[6],out dataspawnmonster.spawny)) { #if UNITY_EDITOR Debug.LogError("数据有误:" + values[6] + " to float"); UnityEditor.EditorApplication.isPaused = true; #endif throw new ArgumentException("数据有误:" + values[6] + " to float" + " 第"+ i + "行,第6列"); } if(!float.TryParse(values[7],out dataspawnmonster.spawnz)) { #if UNITY_EDITOR Debug.LogError("数据有误:" + values[7] + " to float"); UnityEditor.EditorApplication.isPaused = true; #endif throw new ArgumentException("数据有误:" + values[7] + " to float" + " 第"+ i + "行,第7列"); } dataspawnmonster.RelativePosition = values[8]; if (datas.ContainsKey(dataspawnmonster.id)) { #if UNITY_EDITOR UnityEditor.EditorApplication.isPaused = true; #endif throw new ArgumentException("数据有误,主键重复:" + dataspawnmonster.id); } datas.Add(dataspawnmonster.id,dataspawnmonster); } } public static void LoadFromResources() { Clear(); string path = ""; TextAsset data = null; path = "Table/spawnmonster"; data = Resources.Load(path) as TextAsset; if(data == null) { Debug.LogError(path + " 不存在!!!!"); #if UNITY_EDITOR UnityEditor.EditorApplication.isPaused = true; #endif return; } string text = data.text; if(string.IsNullOrEmpty(text)) { Debug.LogError(path + " 没有内容"); #if UNITY_EDITOR UnityEditor.EditorApplication.isPaused = true; #endif return; } spawnmonster.LoadFromString(text); } public static void LoadBinFromResources() { Clear(); loaded = true; string path = ""; TextAsset data = null; path = "TableBin/spawnmonster"; data = Resources.Load(path) as TextAsset; if(data == null) { Debug.LogError(path + " 不存在!!!!"); #if UNITY_EDITOR UnityEditor.EditorApplication.isPaused = true; #endif return; } byte [] text = data.bytes; if(text == null || text.Length == 0) { Debug.LogError(path + " 没有内容"); #if UNITY_EDITOR UnityEditor.EditorApplication.isPaused = true; #endif return; } spawnmonster.LoadFromBinanry(text); } /* public static void LoadFromStreaming() { try { string url = "Table/spawnmonster"; string content = FileUtils.ReadStringFromStreaming(url); LoadFromString(content); } catch (Exception ex) { Debug.LogError(string.Format("表spawnmonster数据有误! ({0})",ex.Message)); } } */ public static void UnLoad() { Clear(); } public static void Clear() { if(_datas != null && _datas.Count != 0) _datas.Clear(); } public static bool Contains(int id) { return datas.ContainsKey(id); } public static spawnmonster Get(int id) { #if UNITY_EDITOR if (!Contains(id)) { Debug.LogError("表spawnmonster没有元素" + id + ",检测一下Excel表"); #if UNITY_EDITOR UnityEditor.EditorApplication.isPaused = true; #endif return null; } #endif return datas[id]; } public static int Getmapid(int id) { return Get(id).mapid; } public static int Getstage(int id) { return Get(id).stage; } public static int Getarrindex(int id) { return Get(id).arrindex; } public static int Getbaseid(int id) { return Get(id).baseid; } public static float Getspawnx(int id) { return Get(id).spawnx; } public static float Getspawny(int id) { return Get(id).spawny; } public static float Getspawnz(int id) { return Get(id).spawnz; } public static string GetRelativePosition(int id) { return Get(id).RelativePosition; } } }
412
0.806762
1
0.806762
game-dev
MEDIA
0.949153
game-dev
0.948757
1
0.948757
nccgroup/ncccodenavi
6,493
Win.CodeNavi/3rd-Party/ObjectListView/ObjectListViewFull-2.6.0/ObjectListViewDemo/SparkleLibrary/Effects/Effects.cs
/* * Effects - A Factory that creates commonly useful effects * * Author: Phillip Piper * Date: 18/01/2010 5:29 PM * * Change log: * 2010-01-18 JPP - Initial version * * To do: * * Copyright (C) 2010 Phillip Piper * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * If you wish to use this code in a closed source application, please contact phillip_piper@bigfoot.com. */ using System; using System.Collections.Generic; using System.Drawing; using System.Text; namespace BrightIdeasSoftware { /// <summary> /// Factory methods that create commonly useful effects /// </summary> public static class Effects { public static MoveEffect Move(int x, int y) { return new MoveEffect(new FixedPointLocator(new Point(x, y))); } public static MoveEffect Move(Point from, Point to) { return new MoveEffect(new FixedPointLocator(from), new FixedPointLocator(to)); } public static MoveEffect Move(Corner toCorner) { return new MoveEffect(Locators.SpriteAligned(toCorner)); } public static MoveEffect Move(Corner toCorner, Point toOffset) { return new MoveEffect(Locators.SpriteAligned(toCorner, toOffset)); } public static MoveEffect Move(Corner fromCorner, Corner toCorner) { return new MoveEffect( Locators.SpriteAligned(fromCorner), Locators.SpriteAligned(toCorner)); } public static MoveEffect Move(Corner fromCorner, Corner toCorner, Point toOffset) { return new MoveEffect( Locators.SpriteAligned(fromCorner), Locators.SpriteAligned(toCorner, toOffset)); } public static MoveEffect Move(Corner fromCorner, Point fromOffset, Corner toCorner, Point toOffset) { return new MoveEffect( Locators.SpriteAligned(fromCorner, fromOffset), Locators.SpriteAligned(toCorner, toOffset)); } /// <summary> /// Create a Mover that will move a sprite so that the middle of the sprite moves from the given /// proportional location of the animation bounds to the other given proportional location. /// </summary> public static MoveEffect Move(float fromProportionX, float fromProportionY, float toProportionX, float toProportionY) { return Effects.Move(Corner.MiddleCenter, fromProportionX, fromProportionY, toProportionX, toProportionY); } /// <summary> /// Create a Mover that will move a sprite so that the given corner moves from the given /// proportional location of the animation bounds to the other given proportional location. /// </summary> public static MoveEffect Move(Corner spriteCorner, float fromProportionX, float fromProportionY, float toProportionX, float toProportionY) { return new MoveEffect( Locators.SpriteAligned(spriteCorner, fromProportionX, fromProportionY), Locators.SpriteAligned(spriteCorner, toProportionX, toProportionY)); } public static GotoEffect Goto(int x, int y) { return new GotoEffect(Locators.At(x, y)); } public static GotoEffect Goto(Corner toCorner) { return new GotoEffect(Locators.SpriteAligned(toCorner)); } public static GotoEffect Goto(Corner toCorner, Point toOffset) { return new GotoEffect(Locators.SpriteAligned(toCorner, toOffset)); } /// <summary> /// Creates an animation that keeps the given corner in the centre of the animation /// </summary> /// <param name="cornerToCenter"></param> /// <returns></returns> public static MoveEffect Centre(Corner cornerToCenter) { return new GotoEffect(Locators.SpriteAligned(Corner.MiddleCenter, cornerToCenter)); } public static RotationEffect Rotate(float from, float to) { return new RotationEffect(from, to); } public static FadeEffect Fade(float from, float to) { return new FadeEffect(from, to); } public static ScaleEffect Scale(float from, float to) { return new ScaleEffect(from, to); } public static BoundsEffect Bounds(IRectangleLocator to) { return new BoundsEffect(to); } public static BoundsEffect Bounds(IRectangleLocator from, IRectangleLocator to) { return new BoundsEffect(from, to); } public static RectangleWalkEffect Walk(IRectangleLocator rl) { return new RectangleWalkEffect(rl); } public static RectangleWalkEffect Walk(IRectangleLocator rl, WalkDirection direction) { return new RectangleWalkEffect(rl, null, direction); } public static RectangleWalkEffect Walk(IRectangleLocator rl, Corner start, WalkDirection direction) { return new RectangleWalkEffect(rl, null, direction, new PointOnRectangleLocator(rl, start)); } public static TickerBoardEffect TickerBoard(string endString) { return new TickerBoardEffect(endString); } public static Repeater Repeat(int repetitions, IEffect effect) { return new Repeater(repetitions, effect); } public static BlinkEffect OneBlink(int fadeIn, int visible, int fadeOut, int invisible) { return new BlinkEffect(fadeIn, visible, fadeOut, invisible); } public static Repeater Blink(int repetitions, int fading, int visible) { return Effects.Repeat(repetitions, Effects.OneBlink(fading, visible, fading, 0)); } public static Repeater Blink(int repetitions) { return Effects.Repeat(repetitions, Effects.OneBlink(2, 4, 2, 1)); } } }
412
0.827927
1
0.827927
game-dev
MEDIA
0.615335
game-dev,desktop-app
0.946559
1
0.946559
Swinject/SwinjectMVVMExample
10,844
Carthage/Checkouts/SwinjectStoryboard/Carthage/Checkouts/Swinject/Sample-iOS.playground/Contents.swift
/*: # Swinject Sample for iOS */ import Swinject /*: ## Basic Use */ protocol AnimalType { var name: String? { get set } func sound() -> String } class Cat: AnimalType { var name: String? init(name: String?) { self.name = name } func sound() -> String { return "Meow!" } } protocol PersonType { func play() -> String } class PetOwner: PersonType { let pet: AnimalType init(pet: AnimalType) { self.pet = pet } func play() -> String { let name = pet.name ?? "someone" return "I'm playing with \(name). \(pet.sound())" } } // Create a container and register service and component pairs. let container = Container() container.register(AnimalType.self) { _ in Cat(name: "Mimi") } container.register(PersonType.self) { r in PetOwner(pet: r.resolve(AnimalType.self)!) } // The person is resolved to a PetOwner with a Cat. let person = container.resolve(PersonType.self)! print(person.play()) /*: ## Named Registration */ class Dog: AnimalType { var name: String? init(name: String?) { self.name = name } func sound() -> String { return "Bow wow!" } } // Add more registrations to the container already containing the PetOwner with the Cat. container.register(AnimalType.self, name: "dog") { _ in Dog(name: "Hachi") } container.register(PersonType.self, name: "doggy") { r in PetOwner(pet: r.resolve(AnimalType.self, name: "dog")!) } // Resolve the service with the registration name to differentiate from the cat owner. let doggyPerson = container.resolve(PersonType.self, name:"doggy")! print(doggyPerson.play()) /*: ## Initialization Callback */ // A closure can be registered as an initCompleted callback. var called = false container.register(AnimalType.self, name: "cb") { _ in Cat(name: "Mew") } .initCompleted { _, _ in called = true } print(called) // The closure is executed when the instance is created. let catWithCallback = container.resolve(AnimalType.self, name: "cb") print(called) /*: ## Injection Patterns */ class InjectablePerson: PersonType { var pet: AnimalType? { didSet { log = "Injected by property." } } var log = "" init() { } init(pet: AnimalType) { self.pet = pet log = "Injected by initializer." } func setPet(pet: AnimalType) { self.pet = pet log = "Injected by method." } func play() -> String { return log } } // Initializer injection container.register(PersonType.self, name: "initializer") { r in InjectablePerson(pet: r.resolve(AnimalType.self)!) } let initializerInjection = container.resolve(PersonType.self, name:"initializer")! print(initializerInjection.play()) // Property injection 1 (in the component factory) container.register(PersonType.self, name: "property1") { r in let person = InjectablePerson() person.pet = r.resolve(AnimalType.self) return person } let propertyInjection1 = container.resolve(PersonType.self, name:"property1")! print(propertyInjection1.play()) // Property injection 2 (in the initCompleted callback) container.register(PersonType.self, name: "property2") { _ in InjectablePerson() } .initCompleted { r, p in let injectablePerson = p as! InjectablePerson injectablePerson.pet = r.resolve(AnimalType.self) } let propertyInjection2 = container.resolve(PersonType.self, name:"property2")! print(propertyInjection2.play()) // Method injection 1 (in the component factory) container.register(PersonType.self, name: "method1") { r in let person = InjectablePerson() person.setPet(r.resolve(AnimalType.self)!) return person } let methodInjection1 = container.resolve(PersonType.self, name:"method1")! print(methodInjection1.play()) // Method injection 2 (in the initCompleted callback) container.register(PersonType.self, name: "method2") { _ in InjectablePerson() } .initCompleted { r, p in let injectablePerson = p as! InjectablePerson injectablePerson.setPet(r.resolve(AnimalType.self)!) } let methodInjection2 = container.resolve(PersonType.self, name:"method2")! print(methodInjection2.play()) /*: ## Circular Dependency */ internal protocol ParentType: AnyObject { } internal protocol ChildType: AnyObject { } internal class Parent: ParentType { let child: ChildType? init(child: ChildType?) { self.child = child } } internal class Child: ChildType { weak var parent: ParentType? } // Use initCompleted callback to set the circular dependency to avoid infinite recursion. container.register(ParentType.self) { r in Parent(child: r.resolve(ChildType.self)!) } container.register(ChildType.self) { _ in Child() } .initCompleted { r, c in let child = c as! Child child.parent = r.resolve(ParentType.self) } let parent = container.resolve(ParentType.self) as! Parent let child = parent.child as! Child // The parent and child are referencing each other. print(parent === child.parent) /*: ## Injection with Arguments */ class Horse: AnimalType { var name: String? var running: Bool convenience init(name: String) { self.init(name: name, running: false) } init(name: String, running: Bool) { self.name = name self.running = running } func sound() -> String { return "Whinny!" } } // The factory closure can take arguments after the `Resolvable` parameter (in this example, unused as `_`). // Note that the container already has an AnimalType without a registration name, // but the factory with the arguments is recognized as a different registration to resolve. container.register(AnimalType.self) { _, name in Horse(name: name) } container.register(AnimalType.self) { _, name, running in Horse(name: name, running: running) } // The arguments to the factory are specified on the resolution. // If you pass an argument, pass it to `argument` parameter. // If you pass more arguments, pass them as a tuple to `arguments` parameter. let horse1 = container.resolve(AnimalType.self, argument: "Spirit") as! Horse print(horse1.name) print(horse1.running) let horse2 = container.resolve(AnimalType.self, arguments: "Lucky", true) as! Horse print(horse2.name) print(horse2.running) /*: ## Self-binding */ protocol MyDataType { var data: String { get } } class MyImportantData: MyDataType { let data = "Important data" } class MyController { var myData: MyDataType? func showData() -> String { return myData.map { $0.data } ?? "" } } // Register MyController as both service and component types to inject dependency to its property. container.register(MyController.self) { r in MyController() } .initCompleted { r, c in c.myData = r.resolve(MyDataType.self)! } container.register(MyDataType.self) { _ in MyImportantData() } let myController = container.resolve(MyController.self)! print(myController.showData()) /*: ## Container Hierarchy */ let parentContainer = Container() parentContainer.register(AnimalType.self, name: "cat") { _ in Cat(name: "Mimi") } let childContainer = Container(parent: parentContainer) childContainer.register(AnimalType.self, name: "dog") { _ in Dog(name: "Hachi") } // The registration on the parent container is resolved on the child container. let cat = childContainer.resolve(AnimalType.self, name: "cat") print(cat != nil) // The registration on the child container is not resolved on the parent container. let dog = parentContainer.resolve(AnimalType.self, name: "dog") print(dog == nil) /*: ## Object Scopes */ class A { let b: B let c: C init(b: B, c: C) { self.b = b self.c = c } } class B { let c: C init(c: C) { self.c = c } } class C { } //: ### ObjectScope.None (aka Transient) // New instatnces are created every time. let container1 = Container() container1.register(C.self) { _ in C() } .inObjectScope(.None) let c1 = container1.resolve(C.self) let c2 = container1.resolve(C.self) print(c1 !== c2) // New instances are created in a object graph. container1.register(A.self) { r in A(b: r.resolve(B.self)!, c: r.resolve(C.self)!) } container1.register(B.self) { r in B(c: r.resolve(C.self)!) } let a1 = container1.resolve(A.self)! print(a1.b.c !== a1.c) //: ### ObjectScope.Graph // New instances are created like ObjectScope.None. let container2 = Container() container2.register(C.self) { _ in C() } .inObjectScope(.Graph) // This is the default scope. let c3 = container2.resolve(C.self) let c4 = container2.resolve(C.self) print(c3 !== c4) // But unlike ObjectScope.None, the same instance is resolved in the object graph. container2.register(A.self) { r in A(b: r.resolve(B.self)!, c: r.resolve(C.self)!) } container2.register(B.self) { r in B(c: r.resolve(C.self)!) } let a2 = container2.resolve(A.self)! print(a2.b.c === a2.c) //: ### ObjectScope.Container (aka Singleton) // The same instance is shared in the container. let container3 = Container() container3.register(C.self) { _ in C() } .inObjectScope(.Container) let c5 = container3.resolve(C.self) let c6 = container3.resolve(C.self) print(c5 === c6) // The instance in the parent container is not shared to its child container. let childOfContainer3 = Container(parent: container3) let c7 = childOfContainer3.resolve(C.self) print(c5 !== c7) //: ### ObjectScope.Hierarchy (aka Singleton in the Hierarchy) // The same instance is shared in the container like ObjectScope.Container. let container4 = Container() container4.register(C.self) { _ in C() } .inObjectScope(.Hierarchy) let c8 = container4.resolve(C.self) let c9 = container4.resolve(C.self) print(c8 === c9) // Unlike ObjectScope.Container, the instance in the parent container is shared to its child container. let childOfContainer4 = Container(parent: container4) let c10 = childOfContainer4.resolve(C.self) print(c8 === c10) /*: ## Injection of Value Types */ struct Turtle: AnimalType { var name: String? init(name: String?) { self.name = name } func sound() -> String { return "Ninja!" } } // A value type can be registered as a component. // The object scope is ignored because a value type always creates a new instance. let container5 = Container() container5.register(AnimalType.self) { _ in Turtle(name: "Reo") } .inObjectScope(.Container) var turtle1 = container5.resolve(AnimalType.self)! var turtle2 = container5.resolve(AnimalType.self)! // Still the type of turtle1 and turtle2 is AnimalType protocol, they work as value types. // (Try editing 'var turtle1' to 'let turtle1', then you see a compilation error!) turtle1.name = "Laph" print(turtle1.name!) print(turtle2.name!)
412
0.754772
1
0.754772
game-dev
MEDIA
0.349072
game-dev
0.798739
1
0.798739
SpongePowered/Sponge
2,663
src/mixins/java/org/spongepowered/common/mixin/core/world/item/crafting/RecipeManagerMixin.java
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.mixin.core.world.item.crafting; import com.mojang.serialization.Codec; import com.mojang.serialization.DataResult; import com.mojang.serialization.DynamicOps; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.crafting.Recipe; import net.minecraft.world.item.crafting.RecipeManager; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.common.SpongeCommon; @Mixin(RecipeManager.class) public abstract class RecipeManagerMixin { @Redirect(method = "fromJson", at = @At(value = "INVOKE", target = "Lcom/mojang/serialization/Codec;parse(Lcom/mojang/serialization/DynamicOps;Ljava/lang/Object;)Lcom/mojang/serialization/DataResult;")) private static <T> DataResult<Recipe<?>> impl$onParseRecipe(final Codec<Recipe<?>> instance, final DynamicOps<T> dynamicOps, final T element, final ResourceLocation $$0) { final DataResult<Recipe<?>> parsed; try { parsed = instance.parse(dynamicOps, element); } catch (Exception e) { SpongeCommon.logger().error("Could not parse recipe {}", $$0, e); throw new RuntimeException(e); } if (parsed.error().isPresent()) { SpongeCommon.logger().error("Could not parse recipe {} {}", $$0, parsed.error().get().message()); } return parsed; } }
412
0.74941
1
0.74941
game-dev
MEDIA
0.964916
game-dev
0.903408
1
0.903408
ethereumdegen/spirit_editor
1,374
assets/editor_config.editorconfig.ron
( //this gets copied to artifacts //if just getting started, set to None external_game_assets_folder: Some("../healing-spirit-game-assets/game-assets"), // initial_level_to_load: Some( "editor_showcase.level" ), // initial_level_to_load: Some( "player_shop_basic.level" ), //initial_level_to_load: Some( "player_shop_cellar.level" ), initial_level_to_load: Some( "crypt_1.level" ), // initial_level_to_load: Some( "crypt_bossroom.level" ), // initial_level_to_load: Some( "world.level" ), // initial_level_to_load: Some( "dungeon_viridian_temple.level" ), // initial_level_to_load: Some( "dungeon_broken_elves.level" ), // initial_level_to_load: Some( "house_interior_kieran.level" ), // initial_level_to_load: Some( "dungeon_banesera_aruun.level" ), // initial_level_to_load: Some( "fae_world.level" ), // initial_level_to_load: Some( "vessara_enchanting_shop.level" ), // initial_level_to_load: Some( "dungeon_grove_cave.level" ), // initial_level_to_load: Some( "fetid_hole.level" ), // initial_level_to_load: Some( "city_vessara.level" ), // initial_level_to_load: Some( "academy_1.level" ), //initial_level_to_load: Some( "default_level.level" ), default_placement_settings: Some(( translation_grid_lock_step: Some( (1.0,1.0,1.0) ) , )), )
412
0.636595
1
0.636595
game-dev
MEDIA
0.821647
game-dev,testing-qa
0.57734
1
0.57734
showlab/BYOC
4,115
BlendshapeToolkit/Library/PackageCache/com.unity.visualscripting@1.8.0/Documentation~/vs-input-nodes.md
# Input Event nodes Input nodes are an Event node type that can read input from Unity's [Input Manager](https://docs.unity3d.com/Manual/class-InputManager.html) or [Input System package](https://docs.unity3d.com/Packages/com.unity.inputsystem@latest) for use in a Script Graph. For more information about how to read and capture input in Visual Scripting, see [Capture user input in an application](vs-capture-player-input.md). ## Input System package nodes The following nodes read and interact with Events from the Input System package: | **Node** | **Description** | | :------ | :--------------- | | [**On Input System Event Button**](vs-nodes-events-input-system-button.md) | The On Input System Event Button node listens for a specific Input Action from a Player Input component. It doesn't send or read any other data. | | [**On Input System Event Float**](vs-nodes-events-input-system-float.md) | The On Input System Event Float node listens for a specific Input Action from a Player Input component. The node can output a **single float value**. | | [**On Input System Event Vector 2**](vs-nodes-events-input-system-vector2.md) | The On Input System Event Vector 2 node listens for a specific Input Action from a Player Input component. The node can output **two values as a Vector 2**. | ## Input Manager nodes The following nodes read and interact with Events from Unity's Input Manager: | **Node** | **Description** | | :------ | :--------------- | | [**On Button Input**](vs-nodes-events-on-button-input.md) | The On Button Input node listens for a specified action on a virtual button from your Input Manager configuration. | | [**On Keyboard Input**](vs-nodes-events-on-keyboard-input.md) | The On Keyboard Input node listens for a specified action on a keyboard key. | | [**On Mouse Down**](vs-nodes-events-on-mouse-down.md) | The On Mouse Down node listens for a mouse click action on a specific GameObject in your application. | | [**On Mouse Drag**](vs-nodes-events-on-mouse-drag.md) | The On Mouse Drag node listens for a mouse click and hold on a specific GameObject in your application. It triggers the next node connected to it as long as the mouse button is held down on that GameObject. | | [**On Mouse Enter**](vs-nodes-events-on-mouse-enter.md) | The On Mouse Enter node listens for the user's mouse pointer location to enter the Collider of a specified GameObject. When the mouse enters the Collider or GUI element, the node triggers the next node connected to it. | | [**On Mouse Exit**](vs-nodes-events-on-mouse-exit.md) | The On Mouse Exit node listens for the user's mouse pointer location to exit the Collider of a specified GameObject. When the mouse exits the Collider or GUI element, the node triggers the next node connected to it. | | [**On Mouse Input**](vs-nodes-events-on-mouse-input.md)| The On Mouse Input node listens for a specific action on a user's mouse. The action doesn't need to happen on a specific GameObject's Collider. | | [**On Mouse Over**](vs-nodes-events-on-mouse-over.md) | The On Mouse Over node listens for a user's mouse to land over a specified GameObject's Collider. While the user's mouse is over the Collider, it triggers the next node connected to it once every frame. | | [**On Mouse Up As Button**](vs-nodes-events-on-mouse-up-button.md) | The On Mouse Up As Button node listens for a user to release their mouse button after they click a Collider in your application. To trigger the On Mouse Up As Button node, the user must release their mouse button over the same Collider they clicked. | | [**On Mouse Up**](vs-nodes-events-on-mouse-up.md) | The On Mouse Up node listens for a user to release their mouse button after they click a Collider in your application. The user can release their mouse button anywhere in your application to trigger the On Mouse Up node. | ## Additional resources - [Capturing input in your application](vs-capture-player-input.md) - [Capture input using the Input System package](vs-capturing-player-inputs-new.md) - [Capture input using the Input Manager](vs-capturing-player-inputs-old.md)
412
0.78217
1
0.78217
game-dev
MEDIA
0.713458
game-dev
0.531493
1
0.531493
SkyFireArchives/SkyFireEMU_420
9,822
src/server/scripts/Outland/TempestKeep/arcatraz/instance_arcatraz.cpp
/* * Copyright (C) 2010-2012 Project SkyFire <http://www.projectskyfire.org/> * Copyright (C) 2005-2012 MaNGOS <http://www.getmangos.com/> * Copyright (C) 2008-2012 Trinity <http://www.trinitycore.org/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: Instance_Arcatraz SD%Complete: 80 SDComment: Mainly Harbringer Skyriss event SDCategory: Tempest Keep, The Arcatraz EndScriptData */ #include "ScriptPCH.h" #include "arcatraz.h" #define MAX_ENCOUNTER 9 enum eUnits { CONTAINMENT_CORE_SECURITY_FIELD_ALPHA = 184318, //door opened when Wrath-Scryer Soccothrates dies CONTAINMENT_CORE_SECURITY_FIELD_BETA = 184319, //door opened when Dalliah the Doomsayer dies POD_ALPHA = 183961, //pod first boss wave POD_BETA = 183963, //pod second boss wave POD_DELTA = 183964, //pod third boss wave POD_GAMMA = 183962, //pod fourth boss wave POD_OMEGA = 183965, //pod fifth boss wave WARDENS_SHIELD = 184802, // warden shield SEAL_SPHERE = 184802, //shield 'protecting' mellichar MELLICHAR = 20904, //skyriss will kill this unit }; /* Arcatraz encounters: 1 - Zereketh the Unbound event 2 - Dalliah the Doomsayer event 3 - Wrath-Scryer Soccothrates event 4 - Harbinger Skyriss event, 5 sub-events */ class instance_arcatraz : public InstanceMapScript { public: instance_arcatraz() : InstanceMapScript("instance_arcatraz", 552) { } struct instance_arcatraz_InstanceMapScript : public InstanceScript { instance_arcatraz_InstanceMapScript(Map* pMap) : InstanceScript(pMap) { Initialize(); }; uint32 m_auiEncounter[MAX_ENCOUNTER]; uint64 Containment_Core_Security_Field_AlphaGUID; uint64 Containment_Core_Security_Field_BetaGUID; uint64 Pod_AlphaGUID; uint64 Pod_GammaGUID; uint64 Pod_BetaGUID; uint64 Pod_DeltaGUID; uint64 Pod_OmegaGUID; uint64 Wardens_ShieldGUID; uint64 GoSphereGUID; uint64 MellicharGUID; void Initialize() { memset(&m_auiEncounter, 0, sizeof(m_auiEncounter)); Containment_Core_Security_Field_AlphaGUID = 0; Containment_Core_Security_Field_BetaGUID = 0; Pod_AlphaGUID = 0; Pod_GammaGUID = 0; Pod_BetaGUID = 0; Pod_DeltaGUID = 0; Pod_OmegaGUID = 0; Wardens_ShieldGUID = 0; GoSphereGUID = 0; MellicharGUID = 0; } bool IsEncounterInProgress() const { for (uint8 i = 0; i < MAX_ENCOUNTER; ++i) if (m_auiEncounter[i] == IN_PROGRESS) return true; return false; } void OnGameObjectCreate(GameObject* pGo, bool /*add*/) { switch(pGo->GetEntry()) { case CONTAINMENT_CORE_SECURITY_FIELD_ALPHA: Containment_Core_Security_Field_AlphaGUID = pGo->GetGUID(); break; case CONTAINMENT_CORE_SECURITY_FIELD_BETA: Containment_Core_Security_Field_BetaGUID = pGo->GetGUID(); break; case POD_ALPHA: Pod_AlphaGUID = pGo->GetGUID(); break; case POD_GAMMA: Pod_GammaGUID = pGo->GetGUID(); break; case POD_BETA: Pod_BetaGUID = pGo->GetGUID(); break; case POD_DELTA: Pod_DeltaGUID = pGo->GetGUID(); break; case POD_OMEGA: Pod_OmegaGUID = pGo->GetGUID(); break; case SEAL_SPHERE: GoSphereGUID = pGo->GetGUID(); break; //case WARDENS_SHIELD: Wardens_ShieldGUID = pGo->GetGUID(); break; } } void OnCreatureCreate(Creature* pCreature, bool /*add*/) { if (pCreature->GetEntry() == MELLICHAR) MellicharGUID = pCreature->GetGUID(); } void SetData(uint32 type, uint32 data) { switch(type) { case TYPE_ZEREKETH: m_auiEncounter[0] = data; break; case TYPE_DALLIAH: if (data == DONE) { if (GameObject *pGo = instance->GetGameObject(Containment_Core_Security_Field_BetaGUID)) pGo->UseDoorOrButton(); } m_auiEncounter[1] = data; break; case TYPE_SOCCOTHRATES: if (data == DONE) { if (GameObject *pGo = instance->GetGameObject(Containment_Core_Security_Field_AlphaGUID)) pGo->UseDoorOrButton(); } m_auiEncounter[2] = data; break; case TYPE_HARBINGERSKYRISS: if (data == NOT_STARTED || data == FAIL) { m_auiEncounter[4] = NOT_STARTED; m_auiEncounter[5] = NOT_STARTED; m_auiEncounter[6] = NOT_STARTED; m_auiEncounter[7] = NOT_STARTED; m_auiEncounter[8] = NOT_STARTED; } m_auiEncounter[3] = data; break; case TYPE_WARDEN_1: if (data == IN_PROGRESS) if (GameObject *pGo = instance->GetGameObject(Pod_AlphaGUID)) pGo->UseDoorOrButton(); m_auiEncounter[4] = data; break; case TYPE_WARDEN_2: if (data == IN_PROGRESS) { if (GameObject *pGo = instance->GetGameObject(Pod_BetaGUID)) pGo->UseDoorOrButton(); } m_auiEncounter[5] = data; break; case TYPE_WARDEN_3: if (data == IN_PROGRESS) { if (GameObject *pGo = instance->GetGameObject(Pod_DeltaGUID)) pGo->UseDoorOrButton(); } m_auiEncounter[6] = data; break; case TYPE_WARDEN_4: if (data == IN_PROGRESS) { if (GameObject *pGo = instance->GetGameObject(Pod_GammaGUID)) pGo->UseDoorOrButton(); } m_auiEncounter[7] = data; break; case TYPE_WARDEN_5: if (data == IN_PROGRESS) { if (GameObject *pGo = instance->GetGameObject(Pod_OmegaGUID)) pGo->UseDoorOrButton(); } m_auiEncounter[8] = data; break; case TYPE_SHIELD_OPEN: if (data == IN_PROGRESS) { if (GameObject *pGo = instance->GetGameObject(Wardens_ShieldGUID)) pGo->UseDoorOrButton(); } break; } } uint32 GetData(uint32 type) { switch(type) { case TYPE_HARBINGERSKYRISS: return m_auiEncounter[3]; case TYPE_WARDEN_1: return m_auiEncounter[4]; case TYPE_WARDEN_2: return m_auiEncounter[5]; case TYPE_WARDEN_3: return m_auiEncounter[6]; case TYPE_WARDEN_4: return m_auiEncounter[7]; case TYPE_WARDEN_5: return m_auiEncounter[8]; } return 0; } uint64 GetData64(uint32 data) { switch(data) { case DATA_MELLICHAR: return MellicharGUID; case DATA_SPHERE_SHIELD: return GoSphereGUID; } return 0; } }; InstanceScript* GetInstanceScript(InstanceMap* pMap) const { return new instance_arcatraz_InstanceMapScript(pMap); } }; void AddSC_instance_arcatraz() { new instance_arcatraz; }
412
0.936767
1
0.936767
game-dev
MEDIA
0.971006
game-dev
0.990725
1
0.990725
DeltaV-Station/Delta-v
2,446
Resources/Prototypes/Maps/byoin.yml
- type: gameMap id: Byoin mapName: 'Byōin' mapPath: /Maps/byoin.yml minPlayers: 0 maxPlayers: 35 stations: Byoin: stationProto: StandardNanotrasenStation components: - type: StationEmergencyShuttle emergencyShuttlePath: /Maps/_DV/Shuttles/NTES_Basu.yml - type: StationNameSetup mapNameTemplate: '{0} Byōin Station {1}' nameGenerator: !type:NanotrasenNameGenerator prefixCreator: 'DV' - type: StationJobs availableJobs: #Command Captain: [ 1, 1 ] HeadOfSecurity: [ 1, 1 ] HeadOfPersonnel: [ 1, 1 ] ChiefJustice: [ 1, 1 ] ChiefMedicalOfficer: [ 1, 1 ] ChiefEngineer: [ 1, 1 ] Quartermaster: [ 1, 1 ] ResearchDirector: [ 1, 1 ] StationAi: [ 1, 1 ] #service Reporter: [ 1, 1 ] Janitor: [ 1, 1 ] Bartender: [ 1, 1 ] Botanist: [ 1, 1 ] Chef: [ 1 , 1 ] Musician: [ 1, 1 ] Clown: [ 1, 1 ] Mime: [ 1, 1 ] Librarian: [ 1, 1 ] ServiceWorker: [ 1, 1 ] Boxer: [ 2, 2 ] #engineering AtmosphericTechnician: [ 2, 2 ] StationEngineer: [ 2, 2 ] TechnicalAssistant: [ 1, 1 ] #medical Chemist: [ 1, 1 ] Psychologist: [ 1, 1 ] Paramedic: [ 1, 1 ] Surgeon: [ 1, 1 ] MedicalDoctor: [ 2, 3 ] MedicalIntern: [ 1, 1 ] #science Roboticist: [ 1, 1 ] Scientist: [ 2, 2 ] ResearchAssistant: [ 1, 1 ] ForensicMantis: [ 1, 1 ] Chaplain: [ 1, 1 ] #Silicon MedicalBorg: [ 1, 1 ] Borg: [ 1, 1 ] #security Warden: [ 1, 1 ] Detective: [ 1, 1 ] SecurityOfficer: [ 2, 3 ] SecurityCadet: [ 1, 1 ] Brigmedic: [ 1, 1 ] Prisoner: [ 2, 2 ] PrisonGuard: [ 1, 1 ] #justice Clerk: [ 1, 1 ] Prosecutor: [ 1, 1 ] Lawyer: [ 1, 1 ] #supply SalvageSpecialist: [ 2, 2 ] CargoTechnician: [ 2, 2 ] Courier: [ 1, 1 ] CargoAssistant: [ 1, 1 ] #civilian Passenger: [ -1, -1 ]
412
0.782879
1
0.782879
game-dev
MEDIA
0.243206
game-dev
0.773125
1
0.773125
ChiselsAndBits/Chisels-and-Bits
2,215
api/src/main/java/mod/chiselsandbits/api/item/wireframe/IWireframeProvidingItem.java
package mod.chiselsandbits.api.item.wireframe; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.VoxelShape; import org.joml.Vector4f; /** * Represents an item which can provide a wireframe for different purposes, * including rendering a preview. */ public interface IWireframeProvidingItem { /** * Provides access to the wire frame of the item. * * @param stack The stack to get the wire frame from. * @param player The player to get the wire frame for. * @param rayTraceResult The ray trace result of the current context. * @return The VoxelShape for the wire frame. */ VoxelShape getWireFrame( final ItemStack stack, final Player player, final BlockHitResult rayTraceResult ); /** * The color to render the wireframe in. * * @param heldStack The stack to get the wire frame color for. * @param playerEntity The entity that is rendering the wire frame color. * @param blockRayTraceResult The block ray trace result for the current context. * @return An RGB (XYZ) Vector with the color. */ Vector4f getWireFrameColor( ItemStack heldStack, Player playerEntity, BlockHitResult blockRayTraceResult ); /** * Returns the position the wire frame should be rendered at. * * @param heldStack The stack to get the position for. * @param playerEntity The entity that is rendering the wire frame. * @param blockRayTraceResult The block ray trace result for the current context. * @return The position to render the wire frame. */ Vec3 getTargetedPosition( ItemStack heldStack, Player playerEntity, BlockHitResult blockRayTraceResult ); /** * Returns whether to effectively ignore the depth buffer and render in front of everything * * @param heldStack The stack to get depth logic for. * @return Whether depth is effectively ignored. */ default boolean ignoreDepth(ItemStack heldStack) { return true; } }
412
0.904311
1
0.904311
game-dev
MEDIA
0.878034
game-dev,graphics-rendering
0.635084
1
0.635084
limbonaut/limboai
1,568
doc/source/classes/class_btinvert.rst
:github_url: hide .. DO NOT EDIT THIS FILE!!! .. Generated automatically from Godot engine sources. .. Generator: https://github.com/godotengine/godot/tree/4.3/doc/tools/make_rst.py. .. XML source: https://github.com/godotengine/godot/tree/4.3/modules/limboai/doc_classes/BTInvert.xml. .. _class_BTInvert: BTInvert ======== **Inherits:** :ref:`BTDecorator<class_BTDecorator>` **<** :ref:`BTTask<class_BTTask>` **<** :ref:`BT<class_BT>` BT decorator that transforms ``FAILURE`` into ``SUCCESS`` and ``SUCCESS`` into ``FAILURE``. .. rst-class:: classref-introduction-group Description ----------- BTInvert transforms ``FAILURE`` into ``SUCCESS`` and ``SUCCESS`` into ``FAILURE``. .. |virtual| replace:: :abbr:`virtual (This method should typically be overridden by the user to have any effect.)` .. |const| replace:: :abbr:`const (This method has no side effects. It doesn't modify any of the instance's member variables.)` .. |vararg| replace:: :abbr:`vararg (This method accepts any number of arguments after the ones described here.)` .. |constructor| replace:: :abbr:`constructor (This method is used to construct a type.)` .. |static| replace:: :abbr:`static (This method doesn't need an instance to be called, so it can be called directly using the class name.)` .. |operator| replace:: :abbr:`operator (This method describes a valid operator to use with this type as left-hand operand.)` .. |bitfield| replace:: :abbr:`BitField (This value is an integer composed as a bitmask of the following flags.)` .. |void| replace:: :abbr:`void (No return value.)`
412
0.722176
1
0.722176
game-dev
MEDIA
0.256967
game-dev
0.732896
1
0.732896
Kirby64Ret/kirby64
7,968
asm/non_matchings/ovl1/ovl1_3/func_800A8724.s
glabel func_800A8724 /* 050974 800A8724 27BDFFC8 */ addiu $sp, $sp, -0x38 /* 050978 800A8728 AFBF0034 */ sw $ra, 0x34($sp) /* 05097C 800A872C AFB6002C */ sw $s6, 0x2c($sp) /* 050980 800A8730 AFB50028 */ sw $s5, 0x28($sp) /* 050984 800A8734 0080A825 */ move $s5, $a0 /* 050988 800A8738 AFB70030 */ sw $s7, 0x30($sp) /* 05098C 800A873C AFB40024 */ sw $s4, 0x24($sp) /* 050990 800A8740 AFB30020 */ sw $s3, 0x20($sp) /* 050994 800A8744 AFB2001C */ sw $s2, 0x1c($sp) /* 050998 800A8748 AFB10018 */ sw $s1, 0x18($sp) /* 05099C 800A874C AFB00014 */ sw $s0, 0x14($sp) /* 0509A0 800A8750 0C02A0B0 */ jal func_800A82C0 /* 0509A4 800A8754 0000B025 */ move $s6, $zero /* 0509A8 800A8758 3C06800D */ lui $a2, %hi(D_800D00E4) # $a2, 0x800d /* 0509AC 800A875C 3C05800D */ lui $a1, %hi(D_800D0124) # $a1, 0x800d /* 0509B0 800A8760 3C08800D */ lui $t0, %hi(D_800D0144) # $t0, 0x800d /* 0509B4 800A8764 25080144 */ addiu $t0, %lo(D_800D0144) # addiu $t0, $t0, 0x144 /* 0509B8 800A8768 24A50124 */ addiu $a1, %lo(D_800D0124) # addiu $a1, $a1, 0x124 /* 0509BC 800A876C 24C600E4 */ addiu $a2, %lo(D_800D00E4) # addiu $a2, $a2, 0xe4 /* 0509C0 800A8770 00003825 */ move $a3, $zero .L800A8774_ovl1: /* 0509C4 800A8774 8CCE0000 */ lw $t6, ($a2) /* 0509C8 800A8778 3C0F800D */ lui $t7, %hi(D_800D00C4) # $t7, 0x800d /* 0509CC 800A877C 25EF00C4 */ addiu $t7, %lo(D_800D00C4) # addiu $t7, $t7, 0xc4 /* 0509D0 800A8780 11C0000D */ beqz $t6, .L800A87B8_ovl1 /* 0509D4 800A8784 00001825 */ move $v1, $zero /* 0509D8 800A8788 00EF2021 */ addu $a0, $a3, $t7 /* 0509DC 800A878C 00001025 */ move $v0, $zero /* 0509E0 800A8790 8C980000 */ lw $t8, ($a0) .L800A8794_ovl1: /* 0509E4 800A8794 24630001 */ addiu $v1, $v1, 1 /* 0509E8 800A8798 0302C821 */ addu $t9, $t8, $v0 /* 0509EC 800A879C AF200000 */ sw $zero, ($t9) /* 0509F0 800A87A0 8CC90000 */ lw $t1, ($a2) /* 0509F4 800A87A4 24420004 */ addiu $v0, $v0, 4 /* 0509F8 800A87A8 0069082B */ sltu $at, $v1, $t1 /* 0509FC 800A87AC 5420FFF9 */ bnezl $at, .L800A8794_ovl1 /* 050A00 800A87B0 8C980000 */ lw $t8, ($a0) /* 050A04 800A87B4 00001825 */ move $v1, $zero .L800A87B8_ovl1: /* 050A08 800A87B8 8CAA0000 */ lw $t2, ($a1) /* 050A0C 800A87BC 24C60004 */ addiu $a2, $a2, 4 /* 050A10 800A87C0 00001025 */ move $v0, $zero /* 050A14 800A87C4 1140000C */ beqz $t2, .L800A87F8_ovl1 /* 050A18 800A87C8 3C0B800D */ lui $t3, %hi(D_800D0104) # $t3, 0x800d /* 050A1C 800A87CC 256B0104 */ addiu $t3, %lo(D_800D0104) # addiu $t3, $t3, 0x104 /* 050A20 800A87D0 00EB2021 */ addu $a0, $a3, $t3 /* 050A24 800A87D4 8C8C0000 */ lw $t4, ($a0) .L800A87D8_ovl1: /* 050A28 800A87D8 24630001 */ addiu $v1, $v1, 1 /* 050A2C 800A87DC 01826821 */ addu $t5, $t4, $v0 /* 050A30 800A87E0 ADA00000 */ sw $zero, ($t5) /* 050A34 800A87E4 8CAE0000 */ lw $t6, ($a1) /* 050A38 800A87E8 24420004 */ addiu $v0, $v0, 4 /* 050A3C 800A87EC 006E082B */ sltu $at, $v1, $t6 /* 050A40 800A87F0 5420FFF9 */ bnezl $at, .L800A87D8_ovl1 /* 050A44 800A87F4 8C8C0000 */ lw $t4, ($a0) .L800A87F8_ovl1: /* 050A48 800A87F8 24A50004 */ addiu $a1, $a1, 4 /* 050A4C 800A87FC 00A8082B */ sltu $at, $a1, $t0 /* 050A50 800A8800 1420FFDC */ bnez $at, .L800A8774_ovl1 /* 050A54 800A8804 24E70004 */ addiu $a3, $a3, 4 /* 050A58 800A8808 3C18800C */ lui $t8, %hi(D_800C4654) # $t8, 0x800c /* 050A5C 800A880C 27184654 */ addiu $t8, %lo(D_800C4654) # addiu $t8, $t8, 0x4654 /* 050A60 800A8810 3C10800D */ lui $s0, %hi(D_800D7BD0) # $s0, 0x800d /* 050A64 800A8814 3C04800D */ lui $a0, %hi(D_800D7BB8) # $a0, 0x800d /* 050A68 800A8818 00157900 */ sll $t7, $s5, 4 /* 050A6C 800A881C 3C13800D */ lui $s3, %hi(D_800D7BC0) # $s3, 0x800d /* 050A70 800A8820 3C14800D */ lui $s4, %hi(D_800D7BE0) # $s4, 0x800d /* 050A74 800A8824 26947BE0 */ addiu $s4, %lo(D_800D7BE0) # addiu $s4, $s4, 0x7be0 /* 050A78 800A8828 26737BC0 */ addiu $s3, %lo(D_800D7BC0) # addiu $s3, $s3, 0x7bc0 /* 050A7C 800A882C 01F89021 */ addu $s2, $t7, $t8 /* 050A80 800A8830 8C847BB8 */ lw $a0, %lo(D_800D7BB8)($a0) /* 050A84 800A8834 26107BD0 */ addiu $s0, %lo(D_800D7BD0) # addiu $s0, $s0, 0x7bd0 /* 050A88 800A8838 00008825 */ move $s1, $zero /* 050A8C 800A883C 2417FFFF */ li $s7, -1 .L800A8840_ovl1: /* 050A90 800A8840 8E460000 */ lw $a2, ($s2) /* 050A94 800A8844 AE000000 */ sw $zero, ($s0) /* 050A98 800A8848 0080A825 */ move $s5, $a0 /* 050A9C 800A884C 50C00013 */ beql $a2, $zero, .L800A889C_ovl1 /* 050AA0 800A8850 8E190000 */ lw $t9, ($s0) /* 050AA4 800A8854 14D70009 */ bne $a2, $s7, .L800A887C_ovl1 /* 050AA8 800A8858 02202825 */ move $a1, $s1 /* 050AAC 800A885C 0C02A103 */ jal func_800A840C /* 050AB0 800A8860 02202825 */ move $a1, $s1 /* 050AB4 800A8864 14400002 */ bnez $v0, .L800A8870_ovl1 /* 050AB8 800A8868 AE020000 */ sw $v0, ($s0) /* 050ABC 800A886C 26D60001 */ addiu $s6, $s6, 1 .L800A8870_ovl1: /* 050AC0 800A8870 3C04800D */ lui $a0, %hi(D_800D7BB8) # $a0, 0x800d /* 050AC4 800A8874 10000008 */ b .L800A8898_ovl1 /* 050AC8 800A8878 8C847BB8 */ lw $a0, %lo(D_800D7BB8)($a0) .L800A887C_ovl1: /* 050ACC 800A887C 0C02A103 */ jal func_800A840C /* 050AD0 800A8880 00C02025 */ move $a0, $a2 /* 050AD4 800A8884 14400002 */ bnez $v0, .L800A8890_ovl1 /* 050AD8 800A8888 AE020000 */ sw $v0, ($s0) /* 050ADC 800A888C 26D60001 */ addiu $s6, $s6, 1 .L800A8890_ovl1: /* 050AE0 800A8890 3C04800D */ lui $a0, %hi(D_800D7BB8) # $a0, 0x800d /* 050AE4 800A8894 8C847BB8 */ lw $a0, %lo(D_800D7BB8)($a0) .L800A8898_ovl1: /* 050AE8 800A8898 8E190000 */ lw $t9, ($s0) .L800A889C_ovl1: /* 050AEC 800A889C 26310001 */ addiu $s1, $s1, 1 /* 050AF0 800A88A0 2E210004 */ sltiu $at, $s1, 4 /* 050AF4 800A88A4 02A44823 */ subu $t1, $s5, $a0 /* 050AF8 800A88A8 26100004 */ addiu $s0, $s0, 4 /* 050AFC 800A88AC 26520004 */ addiu $s2, $s2, 4 /* 050B00 800A88B0 26730004 */ addiu $s3, $s3, 4 /* 050B04 800A88B4 26940004 */ addiu $s4, $s4, 4 /* 050B08 800A88B8 AE89FFFC */ sw $t1, -4($s4) /* 050B0C 800A88BC 1420FFE0 */ bnez $at, .L800A8840_ovl1 /* 050B10 800A88C0 AE79FFFC */ sw $t9, -4($s3) /* 050B14 800A88C4 3C01800D */ lui $at, %hi(D_800D6E78) # $at, 0x800d /* 050B18 800A88C8 AC206E78 */ sw $zero, %lo(D_800D6E78)($at) /* 050B1C 800A88CC 3C01800D */ lui $at, %hi(D_800D6E68) # $at, 0x800d /* 050B20 800A88D0 AC206E68 */ sw $zero, %lo(D_800D6E68)($at) /* 050B24 800A88D4 3C01800D */ lui $at, %hi(D_800D6E7C) # $at, 0x800d /* 050B28 800A88D8 AC206E7C */ sw $zero, %lo(D_800D6E7C)($at) /* 050B2C 800A88DC 3C01800D */ lui $at, %hi(D_800D6E6C) # $at, 0x800d /* 050B30 800A88E0 AC206E6C */ sw $zero, %lo(D_800D6E6C)($at) /* 050B34 800A88E4 3C01800D */ lui $at, %hi(D_800D6E80) # $at, 0x800d /* 050B38 800A88E8 AC206E80 */ sw $zero, %lo(D_800D6E80)($at) /* 050B3C 800A88EC 3C01800D */ lui $at, %hi(D_800D6E70) # $at, 0x800d /* 050B40 800A88F0 AC206E70 */ sw $zero, %lo(D_800D6E70)($at) /* 050B44 800A88F4 8FBF0034 */ lw $ra, 0x34($sp) /* 050B48 800A88F8 3C01800D */ lui $at, %hi(D_800D6E84) # $at, 0x800d /* 050B4C 800A88FC AC206E84 */ sw $zero, %lo(D_800D6E84)($at) /* 050B50 800A8900 02C01025 */ move $v0, $s6 /* 050B54 800A8904 3C01800D */ lui $at, %hi(D_800D6E74) # $at, 0x800d /* 050B58 800A8908 8FB6002C */ lw $s6, 0x2c($sp) /* 050B5C 800A890C 8FB00014 */ lw $s0, 0x14($sp) /* 050B60 800A8910 8FB10018 */ lw $s1, 0x18($sp) /* 050B64 800A8914 8FB2001C */ lw $s2, 0x1c($sp) /* 050B68 800A8918 8FB30020 */ lw $s3, 0x20($sp) /* 050B6C 800A891C 8FB40024 */ lw $s4, 0x24($sp) /* 050B70 800A8920 8FB50028 */ lw $s5, 0x28($sp) /* 050B74 800A8924 8FB70030 */ lw $s7, 0x30($sp) /* 050B78 800A8928 AC206E74 */ sw $zero, %lo(D_800D6E74)($at) /* 050B7C 800A892C 03E00008 */ jr $ra /* 050B80 800A8930 27BD0038 */ addiu $sp, $sp, 0x38 .type func_800A8724, @function .size func_800A8724, . - func_800A8724
412
0.590562
1
0.590562
game-dev
MEDIA
0.789229
game-dev
0.629478
1
0.629478
sebas77/Svelto.MiniExamples
23,272
Example1-Unity-DoofusesMustEat/DOOFUSES_GAMEOBJECTS/Packages/com.sebaslab.svelto.ecs/Core/SpecialEnumerators/DoubleIterationEnumerator.cs
using System; using Svelto.ECS.Internal; namespace Svelto.ECS { public readonly ref struct DoubleEntitiesEnumerator<T1> where T1 : struct, _IInternalEntityComponent { public DoubleEntitiesEnumerator(GroupsEnumerable<T1> groupsEnumerable) { _groupsEnumerable = groupsEnumerable; } public EntityGroupsIterator GetEnumerator() { return new EntityGroupsIterator(_groupsEnumerable); } readonly GroupsEnumerable<T1> _groupsEnumerable; public ref struct EntityGroupsIterator { public EntityGroupsIterator(GroupsEnumerable<T1> groupsEnumerable) : this() { _groupsEnumerableA = groupsEnumerable.GetEnumerator(); _groupsEnumerableA.MoveNext(); _groupsEnumerableB = _groupsEnumerableA; _indexA = 0; _indexB = 0; } public bool MoveNext() { //once GroupEnumerables complete, they reset. If they reset and moveNext doesn't happen, they are invalid while (_groupsEnumerableA.isValid) { var (buffersA, _) = _groupsEnumerableA.Current; var (buffersB, _) = _groupsEnumerableB.Current; //current index A must iterate as long as is less than the current A group count while (_indexA < buffersA.count) { //current index B must iterate as long as is less than the current B group count if (++_indexB < buffersB.count) { return true; } //if B iteration is over, move to the next group if (_groupsEnumerableB.MoveNext() == false) { //if there is no valid next groups, we reset B and we need to move to the next A element _groupsEnumerableB = _groupsEnumerableA; (buffersB, _) = _groupsEnumerableB.Current; ++_indexA; //next A element _indexB = _indexA; } else //otherwise the current A will be checked against the new B group. IndexB must be reset //to work on the new group { _indexB = -1; } } //the current group A iteration is done, so we move to the next A group if (_groupsEnumerableA.MoveNext() == true) { //there is a new group, we reset the iteration _indexA = 0; _indexB = 0; _groupsEnumerableB = _groupsEnumerableA; } else return false; } return false; } public void Reset() { throw new Exception(); } public ValueRef Current { get { var valueRef = new ValueRef(_groupsEnumerableA.Current, _indexA, _groupsEnumerableB.Current , _indexB); return valueRef; } } public void Dispose() { } GroupsEnumerable<T1>.GroupsIterator _groupsEnumerableA; GroupsEnumerable<T1>.GroupsIterator _groupsEnumerableB; int _indexA; int _indexB; } public readonly ref struct ValueRef { readonly GroupsEnumerable<T1>.RefCurrent _current; readonly int _indexA; readonly GroupsEnumerable<T1>.RefCurrent _refCurrent; readonly int _indexB; public ValueRef (GroupsEnumerable<T1>.RefCurrent current, int indexA, GroupsEnumerable<T1>.RefCurrent refCurrent , int indexB) { _current = current; _indexA = indexA; _refCurrent = refCurrent; _indexB = indexB; } public void Deconstruct (out EntityCollection<T1> buffers, out int indexA, out EntityCollection<T1> refCurrent, out int indexB) { buffers = _current._buffers; indexA = _indexA; refCurrent = _refCurrent._buffers; indexB = _indexB; } public void Deconstruct (out EntityCollection<T1> buffers, out int indexA, out ExclusiveGroupStruct groupA , out EntityCollection<T1> refCurrent, out int indexB, out ExclusiveGroupStruct groupB) { buffers = _current._buffers; indexA = _indexA; refCurrent = _refCurrent._buffers; indexB = _indexB; groupA = _current._group; groupB = _refCurrent._group; } } } public readonly ref struct DoubleIterationEnumerator<T1, T2> where T1 : struct, _IInternalEntityComponent where T2 : struct, _IInternalEntityComponent { public DoubleIterationEnumerator(GroupsEnumerable<T1, T2> groupsEnumerable) { _groupsEnumerable = groupsEnumerable; } public EntityGroupsIterator GetEnumerator() { return new EntityGroupsIterator(_groupsEnumerable); } readonly GroupsEnumerable<T1, T2> _groupsEnumerable; public ref struct EntityGroupsIterator { public EntityGroupsIterator(GroupsEnumerable<T1, T2> groupsEnumerable) : this() { _groupsEnumerableA = groupsEnumerable.GetEnumerator(); _groupsEnumerableA.MoveNext(); _groupsEnumerableB = _groupsEnumerableA; _indexA = 0; _indexB = 0; } public bool MoveNext() { //once GroupEnumerables complete, they reset. If they reset and moveNext doesn't happen, they are invalid while (_groupsEnumerableA.isValid) { var (buffersA, _) = _groupsEnumerableA.Current; var (buffersB, _) = _groupsEnumerableB.Current; //current index A must iterate as long as is less than the current A group count while (_indexA < buffersA.count) { //current index B must iterate as long as is less than the current B group count if (++_indexB < buffersB.count) { return true; } //if B iteration is over, move to the next group if (_groupsEnumerableB.MoveNext() == false) { //if there is no valid next groups, we reset B and we need to move to the next A element _groupsEnumerableB = _groupsEnumerableA; (buffersB, _) = _groupsEnumerableB.Current; ++_indexA; //next A element _indexB = _indexA; } else //otherwise the current A will be checked against the new B group. IndexB must be reset //to work on the new group { _indexB = -1; } } //the current group A iteration is done, so we move to the next A group if (_groupsEnumerableA.MoveNext() == true) { //there is a new group, we reset the iteration _indexA = 0; _indexB = 0; _groupsEnumerableB = _groupsEnumerableA; } else return false; } return false; } public void Reset() { throw new Exception(); } public ValueRef Current { get { var valueRef = new ValueRef(_groupsEnumerableA.Current, _indexA, _groupsEnumerableB.Current , _indexB); return valueRef; } } public void Dispose() { } GroupsEnumerable<T1, T2>.GroupsIterator _groupsEnumerableA; GroupsEnumerable<T1, T2>.GroupsIterator _groupsEnumerableB; int _indexA; int _indexB; } public readonly ref struct ValueRef { public readonly GroupsEnumerable<T1, T2>.RefCurrent _current; public readonly int _indexA; public readonly GroupsEnumerable<T1, T2>.RefCurrent _refCurrent; public readonly int _indexB; public ValueRef (GroupsEnumerable<T1, T2>.RefCurrent current, int indexA, GroupsEnumerable<T1, T2>.RefCurrent refCurrent , int indexB) { _current = current; _indexA = indexA; _refCurrent = refCurrent; _indexB = indexB; } public void Deconstruct(out EntityCollection<T1, T2> buffers, out int indexA, out EntityCollection<T1, T2> refCurrent, out int indexB) { buffers = _current._buffers; indexA = _indexA; refCurrent = _refCurrent._buffers; indexB = _indexB; } public void Deconstruct (out EntityCollection<T1, T2> buffers, out int indexA, out ExclusiveGroupStruct groupA , out EntityCollection<T1, T2> refCurrent, out int indexB, out ExclusiveGroupStruct groupB) { buffers = _current._buffers; indexA = _indexA; refCurrent = _refCurrent._buffers; indexB = _indexB; groupA = _current._group; groupB = _refCurrent._group; } } } /// <summary> /// Special Enumerator to iterate a group of entities against themselves with complexity n*(n+1)/2 (skips already tested couples) /// </summary> /// <typeparam name="T1"></typeparam> /// <typeparam name="T2"></typeparam> /// <typeparam name="T3"></typeparam> public readonly ref struct DoubleEntitiesEnumerator<T1, T2, T3> where T1 : struct, _IInternalEntityComponent where T2 : struct, _IInternalEntityComponent where T3 : struct, _IInternalEntityComponent { public DoubleEntitiesEnumerator(GroupsEnumerable<T1, T2, T3> groupsEnumerable) { _groupsEnumerable = groupsEnumerable; } public EntityGroupsIterator GetEnumerator() { return new EntityGroupsIterator(_groupsEnumerable); } readonly GroupsEnumerable<T1, T2, T3> _groupsEnumerable; public ref struct EntityGroupsIterator { public EntityGroupsIterator(GroupsEnumerable<T1, T2, T3> groupsEnumerable) : this() { _groupsEnumerableA = groupsEnumerable.GetEnumerator(); _groupsEnumerableA.MoveNext(); _groupsEnumerableB = _groupsEnumerableA; _indexA = 0; _indexB = 0; } public bool MoveNext() { //once GroupEnumerables complete, they reset. If they reset and moveNext doesn't happen, they are invalid while (_groupsEnumerableA.isValid) { var (buffersA, _) = _groupsEnumerableA.Current; var (buffersB, _) = _groupsEnumerableB.Current; //current index A must iterate as long as is less than the current A group count while (_indexA < buffersA.count) { //current index B must iterate as long as is less than the current B group count if (++_indexB < buffersB.count) { return true; } //if B iteration is over, move to the next group if (_groupsEnumerableB.MoveNext() == false) { //if there is no valid next groups, we reset B and we need to move to the next A element _groupsEnumerableB = _groupsEnumerableA; (buffersB, _) = _groupsEnumerableB.Current; ++_indexA; //next A element _indexB = _indexA; } else //otherwise the current A will be checked against the new B group. IndexB must be reset //to work on the new group { _indexB = -1; } } //the current group A iteration is done, so we move to the next A group if (_groupsEnumerableA.MoveNext() == true) { //there is a new group, we reset the iteration _indexA = 0; _indexB = 0; _groupsEnumerableB = _groupsEnumerableA; } else return false; } return false; } public void Reset() { throw new Exception(); } public ValueRef Current { get { var valueRef = new ValueRef(_groupsEnumerableA.Current, _indexA, _groupsEnumerableB.Current , _indexB); return valueRef; } } public void Dispose() { } GroupsEnumerable<T1, T2, T3>.GroupsIterator _groupsEnumerableA; GroupsEnumerable<T1, T2, T3>.GroupsIterator _groupsEnumerableB; int _indexA; int _indexB; } public readonly ref struct ValueRef { readonly GroupsEnumerable<T1, T2, T3>.RefCurrent _current; readonly int _indexA; readonly GroupsEnumerable<T1, T2, T3>.RefCurrent _refCurrent; readonly int _indexB; public ValueRef (GroupsEnumerable<T1, T2, T3>.RefCurrent current, int indexA , GroupsEnumerable<T1, T2, T3>.RefCurrent refCurrent, int indexB) { _current = current; _indexA = indexA; _refCurrent = refCurrent; _indexB = indexB; } public void Deconstruct (out EntityCollection<T1, T2, T3> buffers, out int indexA, out EntityCollection<T1, T2, T3> refCurrent , out int indexB) { buffers = _current._buffers; indexA = _indexA; refCurrent = _refCurrent._buffers; indexB = _indexB; } public void Deconstruct (out EntityCollection<T1, T2, T3> buffers, out int indexA, out ExclusiveGroupStruct groupA , out EntityCollection<T1, T2, T3> refCurrent, out int indexB, out ExclusiveGroupStruct groupB) { buffers = _current._buffers; indexA = _indexA; refCurrent = _refCurrent._buffers; indexB = _indexB; groupA = _current._group; groupB = _refCurrent._group; } } } /// <summary> /// Special Enumerator to iterate a group of entities against themselves with complexity n*(n+1)/2 (skips already tested couples) /// </summary> /// <typeparam name="T1"></typeparam> /// <typeparam name="T2"></typeparam> /// <typeparam name="T3"></typeparam> /// <typeparam name="T4"></typeparam> public readonly ref struct DoubleEntitiesEnumerator<T1, T2, T3, T4> where T1 : struct, _IInternalEntityComponent where T2 : struct, _IInternalEntityComponent where T3 : struct, _IInternalEntityComponent where T4 : struct, _IInternalEntityComponent { public DoubleEntitiesEnumerator(GroupsEnumerable<T1, T2, T3, T4> groupsEnumerable) { _groupsEnumerable = groupsEnumerable; } public EntityGroupsIterator GetEnumerator() { return new EntityGroupsIterator(_groupsEnumerable); } readonly GroupsEnumerable<T1, T2, T3, T4> _groupsEnumerable; public ref struct EntityGroupsIterator { public EntityGroupsIterator(GroupsEnumerable<T1, T2, T3, T4> groupsEnumerable) : this() { _groupsEnumerableA = groupsEnumerable.GetEnumerator(); _groupsEnumerableA.MoveNext(); _groupsEnumerableB = _groupsEnumerableA; _indexA = 0; _indexB = 0; } public bool MoveNext() { //once GroupEnumerables complete, they reset. If they reset and moveNext doesn't happen, they are invalid while (_groupsEnumerableA.isValid) { var (buffersA, _) = _groupsEnumerableA.Current; var (buffersB, _) = _groupsEnumerableB.Current; //current index A must iterate as long as is less than the current A group count while (_indexA < buffersA.count) { //current index B must iterate as long as is less than the current B group count if (++_indexB < buffersB.count) { return true; } //if B iteration is over, move to the next group if (_groupsEnumerableB.MoveNext() == false) { //if there is no valid next groups, we reset B and we need to move to the next A element _groupsEnumerableB = _groupsEnumerableA; (buffersB, _) = _groupsEnumerableB.Current; ++_indexA; //next A element _indexB = _indexA; } else //otherwise the current A will be checked against the new B group. IndexB must be reset //to work on the new group { _indexB = -1; } } //the current group A iteration is done, so we move to the next A group if (_groupsEnumerableA.MoveNext() == true) { //there is a new group, we reset the iteration _indexA = 0; _indexB = 0; _groupsEnumerableB = _groupsEnumerableA; } else return false; } return false; } public void Reset() { throw new Exception(); } public ValueRef Current { get { var valueRef = new ValueRef(_groupsEnumerableA.Current, _indexA, _groupsEnumerableB.Current , _indexB); return valueRef; } } public void Dispose() { } GroupsEnumerable<T1, T2, T3, T4>.GroupsIterator _groupsEnumerableA; GroupsEnumerable<T1, T2, T3, T4>.GroupsIterator _groupsEnumerableB; int _indexA; int _indexB; } public ref struct ValueRef { public readonly GroupsEnumerable<T1, T2, T3, T4>.RefCurrent _current; public readonly int _indexA; public readonly GroupsEnumerable<T1, T2, T3, T4>.RefCurrent _refCurrent; public readonly int _indexB; public ValueRef (GroupsEnumerable<T1, T2, T3, T4>.RefCurrent current, int indexA , GroupsEnumerable<T1, T2, T3, T4>.RefCurrent refCurrent, int indexB) { _current = current; _indexA = indexA; _refCurrent = refCurrent; _indexB = indexB; } public void Deconstruct (out EntityCollection<T1, T2, T3, T4> buffers, out int indexA, out EntityCollection<T1, T2, T3, T4> refCurrent , out int indexB) { buffers = _current._buffers; indexA = _indexA; refCurrent = _refCurrent._buffers; indexB = _indexB; } public void Deconstruct (out EntityCollection<T1, T2, T3, T4> buffers, out int indexA, out ExclusiveGroupStruct groupA , out EntityCollection<T1, T2, T3, T4> refCurrent, out int indexB, out ExclusiveGroupStruct groupB) { buffers = _current._buffers; indexA = _indexA; refCurrent = _refCurrent._buffers; indexB = _indexB; groupA = _current._group; groupB = _refCurrent._group; } } } }
412
0.843699
1
0.843699
game-dev
MEDIA
0.564565
game-dev
0.844592
1
0.844592
phuocle/Dynamics-Crm-DevKit
19,636
test/3.44.44.44/Test.Cli.Generator.Vn/Dev.DevKit.Shared/Entities/AppModuleComponentNode.generated.cs
//--------------------------------------------------------------------------------------------------- // <auto-generated> // Changes to this file may cause incorrect behavior and will be lost if the code is regenerated. // Generated by DynamicsCrm.DevKit - https://github.com/phuocle/Dynamics-Crm-DevKit // Last Modified: 2024-07-30 10:00:04 // </auto-generated> //--------------------------------------------------------------------------------------------------- using Microsoft.Xrm.Sdk; using System; using System.Diagnostics; using System.Linq; namespace Dev.DevKit.Shared.Entities.AppModuleComponentNodeOptionSets { public enum statecode { /// <summary> /// <para><strong>Display Name</strong>: Hiện hoạt</para> /// <para><strong>Value</strong>: 0</para> /// </summary> Hien_hoat = 0, /// <summary> /// <para><strong>Display Name</strong>: Không hoạt động</para> /// <para><strong>Value</strong>: 1</para> /// </summary> Khong_hoat_dong = 1 } public enum statuscode { /// <summary> /// <para><strong>Display Name</strong>: Hiện hoạt</para> /// <para><strong>Value</strong>: 1</para> /// <para><strong>StateCode.Hien_hoat</strong></para> /// </summary> Hien_hoat = 1, /// <summary> /// <para><strong>Display Name</strong>: Không hoạt động</para> /// <para><strong>Value</strong>: 2</para> /// <para><strong>StateCode.Khong_hoat_dong</strong></para> /// </summary> Khong_hoat_dong = 2 } public enum ValidationStatus { /// <summary> /// <para><strong>Display Name</strong>: Lỗi</para> /// <para><strong>Value</strong>: 2</para> /// </summary> Loi = 2, /// <summary> /// <para><strong>Display Name</strong>: Thành công</para> /// <para><strong>Value</strong>: 1</para> /// </summary> Thanh_cong = 1 } } namespace Dev.DevKit.Shared.Entities { [DebuggerNonUserCode()] public partial class AppModuleComponentNode : EntityBase { public struct Fields { public const string AppModuleComponentNodeId = "appmodulecomponentnodeid"; public const string ComponentDatabaseVersion = "componentdatabaseversion"; public const string ComponentObjectId = "componentobjectid"; public const string ComponentType = "componenttype"; public const string CreatedBy = "createdby"; public const string CreatedOn = "createdon"; public const string CreatedOnBehalfBy = "createdonbehalfby"; public const string ImportSequenceNumber = "importsequencenumber"; public const string ModifiedBy = "modifiedby"; public const string ModifiedOn = "modifiedon"; public const string ModifiedOnBehalfBy = "modifiedonbehalfby"; public const string Name = "name"; public const string OrganizationId = "organizationid"; public const string OverriddenCreatedOn = "overriddencreatedon"; public const string SnapshotVersionNumber = "snapshotversionnumber"; public const string statecode = "statecode"; public const string statuscode = "statuscode"; public const string TimeZoneRuleVersionNumber = "timezoneruleversionnumber"; public const string UTCConversionTimeZoneCode = "utcconversiontimezonecode"; public const string ValidationResult = "validationresult"; public const string ValidationStatus = "validationstatus"; public const string VersionNumber = "versionnumber"; } public const string EntityLogicalName = "appmodulecomponentnode"; [System.Obsolete("This value is different for each instance. Please don't use it.")] public const int EntityTypeCode = 10063; public const string EntityCollectionSchemaName = "AppModuleComponentNodes"; public const string EntityDisplayCollectionName = "Nút thành phần ứng dụng dựa trên mô hình"; public const string DisplayName = "Nút thành phần ứng dụng dựa trên mô hình"; public const string EntitySetName = "appmodulecomponentnodes"; public const string EntityLogicalCollectionName = "appmodulecomponentnodes"; public const string EntityPrimaryIdAttribute = "appmodulecomponentnodeid"; public const string EntityPrimaryImageAttribute = ""; public const string EntityPrimaryNameAttribute = "name"; public const string EntitySchemaName = "AppModuleComponentNode"; [DebuggerNonUserCode()] public AppModuleComponentNode() { Entity = new Entity(EntityLogicalName, Guid.Empty); PreEntity = CloneThisEntity(Entity); } [DebuggerNonUserCode()] public AppModuleComponentNode(Guid AppModuleComponentNodeId) { Entity = new Entity(EntityLogicalName, AppModuleComponentNodeId); PreEntity = CloneThisEntity(Entity); } [DebuggerNonUserCode()] public AppModuleComponentNode(string keyName, object keyValue) { Entity = new Entity(EntityLogicalName, keyName, keyValue); PreEntity = CloneThisEntity(Entity); } /// <summary> /// Instance new late bound class <see cref="AppModuleComponentNode"/> with <paramref name="targetEntity"/>. /// </summary> [DebuggerNonUserCode()] public AppModuleComponentNode(Entity targetEntity) { Entity = targetEntity ?? new Entity(EntityLogicalName, Guid.Empty); PreEntity = CloneThisEntity(Entity); } /// <summary> /// Instance new late bound class <see cref="AppModuleComponentNode"/> with <paramref name="preEntity"/>. Then copy all attributes from <paramref name="targetEntity"/> to <paramref name="preEntity"/>. Existing attribute will be overwritten. /// </summary> /// <exception cref="InvalidPluginExecutionException">when <paramref name="targetEntity"/> is null.</exception> [DebuggerNonUserCode()] public AppModuleComponentNode(Entity preEntity, Entity targetEntity) { if (targetEntity == null) throw new InvalidPluginExecutionException($"new AppModuleComponentNode(preEntity, targetEntity) with targetEntity = null"); if (preEntity == null) preEntity = new Entity(targetEntity.LogicalName, targetEntity.Id); Entity = CloneThisEntity(preEntity); foreach (var property in targetEntity?.Attributes?.ToList()) { var key = property.Key; var value = property.Value; Entity[key] = value; } PreEntity = CloneThisEntity(Entity); } /// <summary> /// Instance new late bound class <see cref="AppModuleComponentNode"/> with <paramref name="preEntity"/>. Then copy all attributes from <paramref name="targetEntity"/> to <paramref name="preEntity"/>. After that copy all attributes from <paramref name="postEntity"/> to the last result. Existing attribute will be overwritten. /// </summary> /// <exception cref="InvalidPluginExecutionException">when <paramref name="targetEntity"/> is null.</exception> [DebuggerNonUserCode()] public AppModuleComponentNode(Entity preEntity, Entity targetEntity, Entity postEntity) { if (targetEntity == null) throw new InvalidPluginExecutionException($"new AppModuleComponentNode(preEntity, targetEntity, postEntity) with targetEntity = null"); if (preEntity == null) preEntity = new Entity(targetEntity.LogicalName, targetEntity.Id); if (postEntity == null) postEntity = new Entity(targetEntity.LogicalName, targetEntity.Id); Entity = CloneThisEntity(preEntity); foreach (var property in targetEntity?.Attributes?.ToList()) { var key = property.Key; var value = property.Value; Entity[key] = value; } foreach (var property in postEntity?.Attributes?.ToList()) { var key = property.Key; var value = property.Value; Entity[key] = value; } PreEntity = CloneThisEntity(Entity); } [DebuggerNonUserCode()] public AppModuleComponentNode(KeyAttributeCollection keys) { Entity = new Entity(EntityLogicalName, keys); PreEntity = CloneThisEntity(Entity); } /// <summary> /// <para><strong>Display Name</strong>: Mã định danh duy nhất cho nút thành phần ứng dụng dựa trên mô hình</para> /// <para><strong>Description</strong>: Mã định danh duy nhất của phiên bản thực thể</para> /// <para><strong>Primary Key</strong>: <strong>Uniqueidentifier</strong></para> /// </summary> [DebuggerNonUserCode()] public Guid AppModuleComponentNodeId { get { return Id; } set { Entity.Attributes[Fields.AppModuleComponentNodeId] = value; Entity.Id = value; } } /// <summary> /// <para><strong>Display Name</strong>: ComponentDatabaseVersion</para> /// <para><strong>Single Line of Text</strong> - <strong>MaxLength</strong>: 100</para> /// </summary> [DebuggerNonUserCode()] public string ComponentDatabaseVersion { get { return Entity.GetAttributeValue<string>(Fields.ComponentDatabaseVersion); } set { Entity.Attributes[Fields.ComponentDatabaseVersion] = value; } } /// <summary> /// <para><strong>Display Name</strong>: ID thành phần Ứng dụng dựa trên mô hình</para> /// <para><strong>Description</strong>: Mã định danh duy nhất cho thành phần Ứng dụng dựa trên mô hình.</para> /// <para><strong>Single Line of Text</strong> - <strong>MaxLength</strong>: 100</para> /// </summary> [DebuggerNonUserCode()] public string ComponentObjectId { get { return Entity.GetAttributeValue<string>(Fields.ComponentObjectId); } set { Entity.Attributes[Fields.ComponentObjectId] = value; } } /// <summary> /// <para><strong>Display Name</strong>: Loại thành phần Ứng dụng dựa trên mô hình.</para> /// <para><strong>Description</strong>: Loại thành phần Ứng dụng dựa trên mô hình.</para> /// <para><strong>Whole Number</strong> - <strong>MinValue</strong>: -2,147,483,648 - <strong>MaxValue</strong>: 2,147,483,647</para> /// </summary> [DebuggerNonUserCode()] public int? ComponentType { get { return Entity.GetAttributeValue<int?>(Fields.ComponentType); } set { Entity.Attributes[Fields.ComponentType] = value; } } /// <summary> /// <para><strong>Display Name</strong>: Người Tạo</para> /// <para><strong>Description</strong>: Mã định danh duy nhất của người dùng đã tạo bản ghi.</para> /// <para><strong>ReadOnly</strong> - <strong>Lookup</strong>: <see cref="systemuser"/></para> /// </summary> [DebuggerNonUserCode()] public EntityReference CreatedBy { get { return Entity.GetAttributeValue<EntityReference>(Fields.CreatedBy); } } /// <summary> /// <para><strong>Display Name</strong>: Ngày Tạo</para> /// <para><strong>Description</strong>: Ngày và giờ tạo bản ghi.</para> /// <para><strong>ReadOnly</strong> - <strong>Date and Time</strong> - <strong>DateTimeBehavior</strong>: UserLocal - <strong>DateTimeFormat</strong>: DateAndTime</para> /// </summary> [DebuggerNonUserCode()] public DateTime? CreatedOnUtc { get { return Entity.GetAttributeValue<DateTime?>(Fields.CreatedOn); } } /// <summary> /// <para><strong>Display Name</strong>: Người Tạo (Đại diện)</para> /// <para><strong>Description</strong>: Mã định danh duy nhất của người dùng đại diện đã tạo bản ghi.</para> /// <para><strong>ReadOnly</strong> - <strong>Lookup</strong>: <see cref="systemuser"/></para> /// </summary> [DebuggerNonUserCode()] public EntityReference CreatedOnBehalfBy { get { return Entity.GetAttributeValue<EntityReference>(Fields.CreatedOnBehalfBy); } } /// <summary> /// <para><strong>Display Name</strong>: Nhập Số Thứ tự</para> /// <para><strong>Description</strong>: Số thứ tự của quá trình nhập đã tạo bản ghi này.</para> /// <para><strong>Whole Number</strong> - <strong>MinValue</strong>: -2,147,483,648 - <strong>MaxValue</strong>: 2,147,483,647</para> /// </summary> [DebuggerNonUserCode()] public int? ImportSequenceNumber { get { return Entity.GetAttributeValue<int?>(Fields.ImportSequenceNumber); } set { Entity.Attributes[Fields.ImportSequenceNumber] = value; } } /// <summary> /// <para><strong>Display Name</strong>: Người Sửa đổi</para> /// <para><strong>Description</strong>: Mã định danh duy nhất của người dùng đã sửa đổi bản ghi.</para> /// <para><strong>ReadOnly</strong> - <strong>Lookup</strong>: <see cref="systemuser"/></para> /// </summary> [DebuggerNonUserCode()] public EntityReference ModifiedBy { get { return Entity.GetAttributeValue<EntityReference>(Fields.ModifiedBy); } } /// <summary> /// <para><strong>Display Name</strong>: Ngày Sửa đổi</para> /// <para><strong>Description</strong>: Ngày và giờ sửa đổi bản ghi.</para> /// <para><strong>ReadOnly</strong> - <strong>Date and Time</strong> - <strong>DateTimeBehavior</strong>: UserLocal - <strong>DateTimeFormat</strong>: DateAndTime</para> /// </summary> [DebuggerNonUserCode()] public DateTime? ModifiedOnUtc { get { return Entity.GetAttributeValue<DateTime?>(Fields.ModifiedOn); } } /// <summary> /// <para><strong>Display Name</strong>: Người Sửa đổi (Đại diện)</para> /// <para><strong>Description</strong>: Mã định danh duy nhất của người dùng đại diện đã sửa đổi bản ghi.</para> /// <para><strong>ReadOnly</strong> - <strong>Lookup</strong>: <see cref="systemuser"/></para> /// </summary> [DebuggerNonUserCode()] public EntityReference ModifiedOnBehalfBy { get { return Entity.GetAttributeValue<EntityReference>(Fields.ModifiedOnBehalfBy); } } /// <summary> /// <para><strong>Display Name</strong>: Tên</para> /// <para><strong>Description</strong>: Tên của thực thể AppModuleComponentNode.</para> /// <para><strong>Primary Name</strong>: <strong>Single Line of Text</strong> - <strong>MaxLength</strong>: 100</para> /// </summary> [DebuggerNonUserCode()] public string Name { get { return Entity.GetAttributeValue<string>(Fields.Name); } set { Entity.Attributes[Fields.Name] = value; } } /// <summary> /// <para><strong>Display Name</strong>: ID tổ chức</para> /// <para><strong>Description</strong>: Mã định danh duy nhất cho tổ chức</para> /// <para><strong>ReadOnly</strong> - <strong>Lookup</strong>: <see cref="organization"/></para> /// </summary> [DebuggerNonUserCode()] public EntityReference OrganizationId { get { return Entity.GetAttributeValue<EntityReference>(Fields.OrganizationId); } } /// <summary> /// <para><strong>Display Name</strong>: Ngày Tạo Bản ghi</para> /// <para><strong>Description</strong>: Ngày và giờ di chuyển bản ghi.</para> /// <para><strong>Date and Time</strong> - <strong>DateTimeBehavior</strong>: UserLocal - <strong>DateTimeFormat</strong>: DateOnly</para> /// </summary> [DebuggerNonUserCode()] public DateTime? OverriddenCreatedOnUtc { get { return Entity.GetAttributeValue<DateTime?>(Fields.OverriddenCreatedOn); } set { Entity.Attributes[Fields.OverriddenCreatedOn] = value; } } /// <summary> /// <para><strong>Display Name</strong>: Số phiên bản ảnh tức thời ứng dụng dựa trên mô hình.</para> /// <para><strong>Description</strong>: Phiên bản ảnh tức thời Ứng dụng dựa trên mô hình.</para> /// <para><strong>Whole Number</strong> - <strong>MinValue</strong>: -2,147,483,648 - <strong>MaxValue</strong>: 2,147,483,647</para> /// </summary> [DebuggerNonUserCode()] public int? SnapshotVersionNumber { get { return Entity.GetAttributeValue<int?>(Fields.SnapshotVersionNumber); } set { Entity.Attributes[Fields.SnapshotVersionNumber] = value; } } /// <summary> /// <para><strong>Display Name</strong>: Trạng thái</para> /// <para><strong>Description</strong>: Trạng thái AppModuleComponentNode</para> /// <para><strong>Status</strong>: <see cref="Dev.DevKit.Shared.Entities.AppModuleComponentNodeOptionSets.statecode"/></para> /// </summary> [DebuggerNonUserCode()] public Dev.DevKit.Shared.Entities.AppModuleComponentNodeOptionSets.statecode? statecode { get { var value = Entity.GetAttributeValue<OptionSetValue>(Fields.statecode); if (value == null) return null; return (Dev.DevKit.Shared.Entities.AppModuleComponentNodeOptionSets.statecode)value.Value; } set { if (value.HasValue) Entity.Attributes[Fields.statecode] = new OptionSetValue((int)value.Value); else Entity.Attributes[Fields.statecode] = null; } } /// <summary> /// <para><strong>Display Name</strong>: Lý do dẫn đến Trạng thái</para> /// <para><strong>Description</strong>: Lý do dẫn đến trạng thái của Nút thành phần ứng dụng dựa trên mô hình</para> /// <para><strong>Status Reason</strong>: <see cref="Dev.DevKit.Shared.Entities.AppModuleComponentNodeOptionSets.statuscode"/></para> /// <para><strong>Default Value</strong>: <see langword="null"/></para> /// </summary> [DebuggerNonUserCode()] public Dev.DevKit.Shared.Entities.AppModuleComponentNodeOptionSets.statuscode? statuscode { get { var value = Entity.GetAttributeValue<OptionSetValue>(Fields.statuscode); if (value == null) return null; return (Dev.DevKit.Shared.Entities.AppModuleComponentNodeOptionSets.statuscode)value.Value; } set { if (value.HasValue) Entity.Attributes[Fields.statuscode] = new OptionSetValue((int)value.Value); else Entity.Attributes[Fields.statuscode] = null; } } /// <summary> /// <para><strong>Display Name</strong>: Số phiên bản của quy tắc múi giờ</para> /// <para><strong>Description</strong>: Chỉ sử dụng nội bộ.</para> /// <para><strong>Whole Number</strong> - <strong>MinValue</strong>: -1 - <strong>MaxValue</strong>: 2,147,483,647</para> /// </summary> [DebuggerNonUserCode()] public int? TimeZoneRuleVersionNumber { get { return Entity.GetAttributeValue<int?>(Fields.TimeZoneRuleVersionNumber); } set { Entity.Attributes[Fields.TimeZoneRuleVersionNumber] = value; } } /// <summary> /// <para><strong>Display Name</strong>: Mã múi giờ chuyển đổi UTC</para> /// <para><strong>Description</strong>: Mã múi giờ đã dùng khi tạo bản ghi.</para> /// <para><strong>Whole Number</strong> - <strong>MinValue</strong>: -1 - <strong>MaxValue</strong>: 2,147,483,647</para> /// </summary> [DebuggerNonUserCode()] public int? UTCConversionTimeZoneCode { get { return Entity.GetAttributeValue<int?>(Fields.UTCConversionTimeZoneCode); } set { Entity.Attributes[Fields.UTCConversionTimeZoneCode] = value; } } /// <summary> /// <para><strong>Display Name</strong>: Kết quả xác thực</para> /// <para><strong>Description</strong>: Kết quả xác nhận tạo ảnh tức thời.</para> /// <para><strong>Single Line of Text</strong> - <strong>MaxLength</strong>: 4,000</para> /// </summary> [DebuggerNonUserCode()] public string ValidationResult { get { return Entity.GetAttributeValue<string>(Fields.ValidationResult); } set { Entity.Attributes[Fields.ValidationResult] = value; } } /// <summary> /// <para><strong>Display Name</strong>: ValidationStatus</para> /// <para><strong>OptionSet</strong>: <see cref="Dev.DevKit.Shared.Entities.AppModuleComponentNodeOptionSets.ValidationStatus"/></para> /// <para><strong>Default Value</strong>: <see langword="null"/></para> /// </summary> [DebuggerNonUserCode()] public Dev.DevKit.Shared.Entities.AppModuleComponentNodeOptionSets.ValidationStatus? ValidationStatus { get { var value = Entity.GetAttributeValue<OptionSetValue>(Fields.ValidationStatus); if (value == null) return null; return (Dev.DevKit.Shared.Entities.AppModuleComponentNodeOptionSets.ValidationStatus)value.Value; } set { if (value.HasValue) Entity.Attributes[Fields.ValidationStatus] = new OptionSetValue((int)value.Value); else Entity.Attributes[Fields.ValidationStatus] = null; } } /// <summary> /// <para><strong>Display Name</strong>: Version Number</para> /// <para><strong>Description</strong>: Version Number</para> /// <para><strong>ReadOnly</strong> - <strong>BigInt</strong></para> /// </summary> [DebuggerNonUserCode()] public long? VersionNumber { get { return Entity.GetAttributeValue<long?>(Fields.VersionNumber); } } } }
412
0.733379
1
0.733379
game-dev
MEDIA
0.658788
game-dev
0.6853
1
0.6853
project-topaz/topaz
1,310
scripts/globals/mobskills/oblivion_smash.lua
--------------------------------------------- -- Oblivion Smash -- -- Description: Deals damage to players within area of effect and inflicts blind, silence, bind, and weight. -- Type: Physical -- Utsusemi/Blink absorb: 2-3 shadows -- Range: Unknown radial --------------------------------------------- require("scripts/globals/monstertpmoves") require("scripts/globals/settings") require("scripts/globals/status") --------------------------------------------- function onMobSkillCheck(target, mob, skill) return 0 end function onMobWeaponSkill(target, mob, skill) local numhits = 3 local accmod = 1 local dmgmod = 2.5 local info = MobPhysicalMove(mob, target, skill, numhits, accmod, dmgmod, TP_DMG_VARIES, 1, 1.5, 2) local dmg = MobFinalAdjustments(info.dmg, mob, skill, target, tpz.attackType.PHYSICAL, tpz.damageType.SLASHING, info.hitslanded) MobPhysicalStatusEffectMove(mob, target, skill, tpz.effect.BLINDNESS, 20, 0, 120) MobPhysicalStatusEffectMove(mob, target, skill, tpz.effect.SILENCE, 0, 0, 120) MobPhysicalStatusEffectMove(mob, target, skill, tpz.effect.BIND, 0, 0, 120) MobPhysicalStatusEffectMove(mob, target, skill, tpz.effect.WEIGHT, 50, 0, 120) target:takeDamage(dmg, mob, tpz.attackType.PHYSICAL, tpz.damageType.SLASHING) return dmg end
412
0.839146
1
0.839146
game-dev
MEDIA
0.990189
game-dev
0.845826
1
0.845826
cbovar/ConvNetSharp
1,637
src/ConvNetSharp.Core/Layers/LeakyReluLayer.cs
using System; using System.Collections.Generic; using ConvNetSharp.Volume; namespace ConvNetSharp.Core.Layers { /// <summary> /// Implements LeakyReLU nonlinearity elementwise /// x -> x > 0, x, otherwise alpha * x /// </summary> public class LeakyReluLayer<T> : LayerBase<T> where T : struct, IEquatable<T>, IFormattable { public LeakyReluLayer(T alpha) { this.Alpha = alpha; } public LeakyReluLayer(Dictionary<string, object> data) : base(data) { this.Alpha = (T)Convert.ChangeType(data["Alpha"], typeof(T)); } public T Alpha { get; set; } public override Dictionary<string, object> GetData() { var dico = base.GetData(); dico["Alpha"] = this.Alpha; return dico; } public override void Backward(Volume<T> outputGradient) { this.OutputActivationGradients = outputGradient; this.OutputActivation.LeakyReluGradient(this.OutputActivationGradients, this.InputActivationGradients, this.Alpha); } protected override Volume<T> Forward(Volume<T> input, bool isTraining = false) { input.LeakyRelu(this.Alpha, this.OutputActivation); return this.OutputActivation; } public override void Init(int inputWidth, int inputHeight, int inputDepth) { base.Init(inputWidth, inputHeight, inputDepth); this.OutputDepth = inputDepth; this.OutputWidth = inputWidth; this.OutputHeight = inputHeight; } } }
412
0.790532
1
0.790532
game-dev
MEDIA
0.490723
game-dev
0.914815
1
0.914815
Facepunch/garrysmod
3,644
garrysmod/gamemodes/terrortown/entities/entities/ttt_carry_handler.lua
AddCSLuaFile() ENT.Type = "anim" ENT.Carried = nil ENT.CarriedMass = 0 ENT.PrevThink = 0 ENT.TargetPos = Vector(0,0,0) ENT.TargetAng = Angle(0,0,0) ENT.Owner = nil function ENT:Initialize() if SERVER and IsValid(self.Carried) then -- self:SetModel("models/weapons/w_bugbait.mdl") self:SetModel(self.Carried:GetModel()) -- self:SetSkin(self.Carried:GetSkin()) -- self:SetColor(se.Carried:GetColor()) end self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self:SetCollisionGroup(COLLISION_GROUP_NONE) -- self:SetSolid(SOLID_NONE) self:SetNoDraw(true) -- self:SetHealth(9999) -- local ply = self:GetOwner() -- self.Owner = ply -- if IsValid(ply) then -- self.TargetPos = ply:GetShootPos() + (ply:GetAimVector() * 70) -- self.TargetAng = ply:GetAimVector() -- end if SERVER and IsValid(self.Carried) then local phys = self:GetPhysicsObject() local carphys = self.Carried:GetPhysicsObject() if IsValid(phys) and IsValid(carphys) then phys:Wake() carphys:Wake() phys:SetMass(9999) phys:SetDamping(0, 1000) carphys:SetDamping(0, 1000) -- if not carphys:IsPenetrating() then -- phys:SetPos(carphys:GetPos()) -- phys:SetAngle(carphys:GetAngle()) -- carphys:SetPos( phys:GetPos() ) -- carphys:SetAngle( phys:GetAngle() ) -- end end self.Carried:SetGravity(false) self.Carried:SetOwner(self:GetOwner()) -- self.Carried:SetNoDraw(true) -- self.Carried:SetSolid(SOLID_NONE) end end function ENT:OnRemove() if IsValid(self.Carried) then self.Carried:SetGravity(true) self.Carried:SetOwner(nil) -- self.Carried:SetNoDraw(false) -- self.Carried:SetSolid(SOLID_VPHYSICS) self.Carried:SetMoveType(MOVETYPE_VPHYSICS) local carphys = self.Carried:GetPhysicsObject() if IsValid(carphys) then carphys:SetDamping(0,0) end self.Carried:PhysWake() end end --function ENT:Think() -- if CLIENT then return end -- -- -- Check on all entities involved -- -- local obj = self.Carried -- local ply = self:GetOwner() -- if not IsValid(obj) or not IsValid(ply) or not ply:Alive() then -- self:Remove() -- return -- end -- -- -- -- -- Check some other requirements -- local spos = ply:GetShootPos() -- if ply:GetGroundEntity() == obj or obj:NearestPoint(spos):Distance(spos) > 150 then -- self:Remove() -- return -- end -- -- -- self.TargetPos = spos + (ply:GetAimVector() * 70) -- self.TargetAng = ply:GetAimVector() -- -- local phys = self:GetPhysicsObject() -- local carryphys = obj:GetPhysicsObject() -- if IsValid(phys) and IsValid(carryphys) then -- if phys:IsPenetrating() then -- self:Remove() -- return ---- self.TargetPos = phys:GetPos() + Vector(0,0,5) ---- phys:SetPos(self.TargetPos) -- end -- -- carryphys:SetPos(phys:GetPos()) -- carryphys:SetAngle(phys:GetAngles()) -- carryphys:SetVelocity(phys:GetVelocity()) -- end -- --end --function ENT:PhysicsSimulate(phys, delta) -- phys:Wake() -- -- local p = {} -- p.pos = self.TargetPos -- p.angle = self.TargetAng -- p.secondstoarrive = 0.05 -- p.maxangular = 100 -- p.maxangulardamp = 10000 -- p.maxspeed = 100 -- p.maxspeeddamp = 1000 -- p.dampfactor = 0.8 -- p.teleportdistance = 0 -- p.deltatime = delta -- -- phys:ComputeShadowControl(p) --end function ENT:OnTakeDamage(dmg) -- do nothing end
412
0.834134
1
0.834134
game-dev
MEDIA
0.718282
game-dev
0.979372
1
0.979372
Nextpeer/Nextpeer-UFORUN
6,724
cocos2d-x-2.2/external/emscripten/tests/bullet/src/BulletCollision/CollisionDispatch/btGhostObject.cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2008 Erwin Coumans http://bulletphysics.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "btGhostObject.h" #include "btCollisionWorld.h" #include "BulletCollision/CollisionShapes/btConvexShape.h" #include "LinearMath/btAabbUtil2.h" btGhostObject::btGhostObject() { m_internalType = CO_GHOST_OBJECT; } btGhostObject::~btGhostObject() { ///btGhostObject should have been removed from the world, so no overlapping objects btAssert(!m_overlappingObjects.size()); } void btGhostObject::addOverlappingObjectInternal(btBroadphaseProxy* otherProxy,btBroadphaseProxy* thisProxy) { btCollisionObject* otherObject = (btCollisionObject*)otherProxy->m_clientObject; btAssert(otherObject); ///if this linearSearch becomes too slow (too many overlapping objects) we should add a more appropriate data structure int index = m_overlappingObjects.findLinearSearch(otherObject); if (index==m_overlappingObjects.size()) { //not found m_overlappingObjects.push_back(otherObject); } } void btGhostObject::removeOverlappingObjectInternal(btBroadphaseProxy* otherProxy,btDispatcher* dispatcher,btBroadphaseProxy* thisProxy) { btCollisionObject* otherObject = (btCollisionObject*)otherProxy->m_clientObject; btAssert(otherObject); int index = m_overlappingObjects.findLinearSearch(otherObject); if (index<m_overlappingObjects.size()) { m_overlappingObjects[index] = m_overlappingObjects[m_overlappingObjects.size()-1]; m_overlappingObjects.pop_back(); } } btPairCachingGhostObject::btPairCachingGhostObject() { m_hashPairCache = new (btAlignedAlloc(sizeof(btHashedOverlappingPairCache),16)) btHashedOverlappingPairCache(); } btPairCachingGhostObject::~btPairCachingGhostObject() { m_hashPairCache->~btHashedOverlappingPairCache(); btAlignedFree( m_hashPairCache ); } void btPairCachingGhostObject::addOverlappingObjectInternal(btBroadphaseProxy* otherProxy,btBroadphaseProxy* thisProxy) { btBroadphaseProxy*actualThisProxy = thisProxy ? thisProxy : getBroadphaseHandle(); btAssert(actualThisProxy); btCollisionObject* otherObject = (btCollisionObject*)otherProxy->m_clientObject; btAssert(otherObject); int index = m_overlappingObjects.findLinearSearch(otherObject); if (index==m_overlappingObjects.size()) { m_overlappingObjects.push_back(otherObject); m_hashPairCache->addOverlappingPair(actualThisProxy,otherProxy); } } void btPairCachingGhostObject::removeOverlappingObjectInternal(btBroadphaseProxy* otherProxy,btDispatcher* dispatcher,btBroadphaseProxy* thisProxy1) { btCollisionObject* otherObject = (btCollisionObject*)otherProxy->m_clientObject; btBroadphaseProxy* actualThisProxy = thisProxy1 ? thisProxy1 : getBroadphaseHandle(); btAssert(actualThisProxy); btAssert(otherObject); int index = m_overlappingObjects.findLinearSearch(otherObject); if (index<m_overlappingObjects.size()) { m_overlappingObjects[index] = m_overlappingObjects[m_overlappingObjects.size()-1]; m_overlappingObjects.pop_back(); m_hashPairCache->removeOverlappingPair(actualThisProxy,otherProxy,dispatcher); } } void btGhostObject::convexSweepTest(const btConvexShape* castShape, const btTransform& convexFromWorld, const btTransform& convexToWorld, btCollisionWorld::ConvexResultCallback& resultCallback, btScalar allowedCcdPenetration) const { btTransform convexFromTrans,convexToTrans; convexFromTrans = convexFromWorld; convexToTrans = convexToWorld; btVector3 castShapeAabbMin, castShapeAabbMax; /* Compute AABB that encompasses angular movement */ { btVector3 linVel, angVel; btTransformUtil::calculateVelocity (convexFromTrans, convexToTrans, 1.0, linVel, angVel); btTransform R; R.setIdentity (); R.setRotation (convexFromTrans.getRotation()); castShape->calculateTemporalAabb (R, linVel, angVel, 1.0, castShapeAabbMin, castShapeAabbMax); } /// go over all objects, and if the ray intersects their aabb + cast shape aabb, // do a ray-shape query using convexCaster (CCD) int i; for (i=0;i<m_overlappingObjects.size();i++) { btCollisionObject* collisionObject= m_overlappingObjects[i]; //only perform raycast if filterMask matches if(resultCallback.needsCollision(collisionObject->getBroadphaseHandle())) { //RigidcollisionObject* collisionObject = ctrl->GetRigidcollisionObject(); btVector3 collisionObjectAabbMin,collisionObjectAabbMax; collisionObject->getCollisionShape()->getAabb(collisionObject->getWorldTransform(),collisionObjectAabbMin,collisionObjectAabbMax); AabbExpand (collisionObjectAabbMin, collisionObjectAabbMax, castShapeAabbMin, castShapeAabbMax); btScalar hitLambda = btScalar(1.); //could use resultCallback.m_closestHitFraction, but needs testing btVector3 hitNormal; if (btRayAabb(convexFromWorld.getOrigin(),convexToWorld.getOrigin(),collisionObjectAabbMin,collisionObjectAabbMax,hitLambda,hitNormal)) { btCollisionWorld::objectQuerySingle(castShape, convexFromTrans,convexToTrans, collisionObject, collisionObject->getCollisionShape(), collisionObject->getWorldTransform(), resultCallback, allowedCcdPenetration); } } } } void btGhostObject::rayTest(const btVector3& rayFromWorld, const btVector3& rayToWorld, btCollisionWorld::RayResultCallback& resultCallback) const { btTransform rayFromTrans; rayFromTrans.setIdentity(); rayFromTrans.setOrigin(rayFromWorld); btTransform rayToTrans; rayToTrans.setIdentity(); rayToTrans.setOrigin(rayToWorld); int i; for (i=0;i<m_overlappingObjects.size();i++) { btCollisionObject* collisionObject= m_overlappingObjects[i]; //only perform raycast if filterMask matches if(resultCallback.needsCollision(collisionObject->getBroadphaseHandle())) { btCollisionWorld::rayTestSingle(rayFromTrans,rayToTrans, collisionObject, collisionObject->getCollisionShape(), collisionObject->getWorldTransform(), resultCallback); } } }
412
0.763748
1
0.763748
game-dev
MEDIA
0.984732
game-dev
0.88888
1
0.88888
ladislav-zezula/CascLib
46,581
src/CascReadFile.cpp
/****************************************************************************/ /* CascOpenFile.cpp Copyright (c) Ladislav Zezula 2014 */ /*---------------------------------------------------------------------------*/ /* System-dependent directory functions for CascLib */ /*---------------------------------------------------------------------------*/ /* Date Ver Who Comment */ /* -------- ---- --- ------- */ /* 01.05.14 1.00 Lad The first version of CascOpenFile.cpp */ /*****************************************************************************/ #define __CASCLIB_SELF__ #include "CascLib.h" #include "CascCommon.h" //----------------------------------------------------------------------------- // Local functions static DWORD GetStreamEncodedSize(TFileStream * pStream) { ULONGLONG FileSize = 0; FileStream_GetSize(pStream, &FileSize); assert((FileSize >> 32) == 0); return (DWORD)(FileSize); } static DWORD OpenDataStream(TCascFile * hf, PCASC_FILE_SPAN pFileSpan, PCASC_CKEY_ENTRY pCKeyEntry, bool bDownloadFileIf) { TCascStorage * hs = hf->hs; TFileStream * pStream = NULL; TCHAR szPlainName[0x80]; DWORD dwErrCode; // If the file is available locally, we rely on data files. // If not, we download the file and open the stream if(pCKeyEntry->Flags & CASC_CE_FILE_IS_LOCAL) { DWORD dwArchiveIndex = pFileSpan->ArchiveIndex; // Lock the storage to make the operation thread-safe CascLock(hs->StorageLock); // If the data archive is not open yet, open it now. if(hs->DataFiles[dwArchiveIndex] == NULL) { // Prepare the name of the data file CascStrPrintf(szPlainName, _countof(szPlainName), _T("data.%03u"), dwArchiveIndex); // Create the full path of the data file CASC_PATH<TCHAR> DataFile(hs->szIndexPath, szPlainName, NULL); // Open the data stream with read+write sharing to prevent Battle.net agent // detecting a corruption and redownloading the entire package pStream = FileStream_OpenFile(DataFile, STREAM_FLAG_READ_ONLY | STREAM_FLAG_WRITE_SHARE | STREAM_PROVIDER_FLAT | STREAM_FLAG_FILL_MISSING | BASE_PROVIDER_FILE); hs->DataFiles[dwArchiveIndex] = pStream; } // Unlock the storage CascUnlock(hs->StorageLock); // Return error or success pFileSpan->pStream = hs->DataFiles[dwArchiveIndex]; return (pFileSpan->pStream != NULL) ? ERROR_SUCCESS : ERROR_FILE_NOT_FOUND; } else { if(bDownloadFileIf) { CASC_ARCHIVE_INFO ArchiveInfo = {0}; CASC_PATH<TCHAR> LocalPath; CPATH_TYPE PathType = (pCKeyEntry->Flags & CASC_CE_FILE_PATCH) ? PathTypePatch : PathTypeData; // Fetch the file dwErrCode = FetchCascFile(hs, PathType, pCKeyEntry->EKey, NULL, LocalPath, &ArchiveInfo); if(dwErrCode == ERROR_SUCCESS) { pStream = FileStream_OpenFile(LocalPath, BASE_PROVIDER_FILE | STREAM_PROVIDER_FLAT); if(pStream != NULL) { // Initialize information about the position and size of the file in archive // On loose files, their position is zero and encoded size is length of the file if(CascIsValidMD5(ArchiveInfo.ArchiveKey)) { // Archive position pFileSpan->ArchiveIndex = ArchiveInfo.ArchiveIndex; pFileSpan->ArchiveOffs = ArchiveInfo.ArchiveOffs; // Encoded size if(pCKeyEntry->EncodedSize == CASC_INVALID_SIZE) pCKeyEntry->EncodedSize = ArchiveInfo.EncodedSize; assert(pCKeyEntry->EncodedSize == ArchiveInfo.EncodedSize); } else { // Archive position pFileSpan->ArchiveIndex = 0; pFileSpan->ArchiveOffs = 0; // Encoded size if(pCKeyEntry->EncodedSize == CASC_INVALID_SIZE) pCKeyEntry->EncodedSize = GetStreamEncodedSize(pStream); assert(pCKeyEntry->EncodedSize == GetStreamEncodedSize(pStream)); } // We need to close the file stream after we're done pFileSpan->pStream = pStream; hf->bCloseFileStream = true; return ERROR_SUCCESS; } } return dwErrCode; } return ERROR_FILE_OFFLINE; } } #ifdef CASCLIB_DEBUG static unsigned int table_16C57A8[0x10] = { 0x049396B8, 0x72A82A9B, 0xEE626CCA, 0x9917754F, 0x15DE40B1, 0xF5A8A9B6, 0x421EAC7E, 0xA9D55C9A, 0x317FD40C, 0x04FAF80D, 0x3D6BE971, 0x52933CFD, 0x27F64B7D, 0xC6F5C11B, 0xD5757E3A, 0x6C388745 }; // Obtained from Agent.exe v 2.15.0.6296 (d14ec9d9a1b396a42964b05f40ea55f37eae5478d550c07ebb6cb09e50968d62) // Note the "Checksum" value probably won't match with older game versions. static void VerifyHeaderSpan(PBLTE_ENCODED_HEADER pBlteHeader, ULONGLONG HeaderOffset) { LPBYTE pbBlteHeader = (LPBYTE)pBlteHeader; DWORD dwInt32; BYTE EncodedOffset[4] = { 0 }; BYTE HashedHeader[4] = { 0 }; BYTE JenkinsHash[4]; BYTE Checksum[4]; size_t i, j; // Seems to be hardcoded to zero assert(pBlteHeader->field_15 == 0); // Calculate the Jenkins hash and write it to the header dwInt32 = hashlittle(pbBlteHeader, FIELD_OFFSET(BLTE_ENCODED_HEADER, JenkinsHash), 0x3D6BE971); ConvertIntegerToBytes_4_LE(dwInt32, JenkinsHash); // assert(memcmp(pBlteHeader->JenkinsHash, JenkinsHash, sizeof(JenkinsHash)) == 0); // Encode the lower 32-bits of the offset dwInt32 = (DWORD)(HeaderOffset + FIELD_OFFSET(BLTE_ENCODED_HEADER, Signature)); dwInt32 = table_16C57A8[dwInt32 & 0x0F] ^ dwInt32; ConvertIntegerToBytes_4_LE(dwInt32, EncodedOffset); // Calculate checksum of the so-far filled structure for(i = 0; i < FIELD_OFFSET(BLTE_ENCODED_HEADER, Checksum); i++) HashedHeader[i & 3] ^= pbBlteHeader[i]; // XOR the two values together to get the final checksum. for(j = 0; j < 4; j++, i++) Checksum[j] = HashedHeader[i & 3] ^ EncodedOffset[i & 3]; // assert(memcmp(pBlteHeader->Checksum, Checksum, sizeof(Checksum)) == 0); } #endif static DWORD ParseBlteHeader(PCASC_FILE_SPAN pFileSpan, ULONGLONG HeaderOffset, LPBYTE pbEncodedBuffer, size_t cbEncodedBuffer, size_t * pcbHeaderSize) { PBLTE_HEADER pBlteHeader = (PBLTE_HEADER)pbEncodedBuffer; DWORD ExpectedHeaderSize; DWORD ExHeaderSize = 0; DWORD HeaderSize; DWORD FrameCount = 0; CASCLIB_UNUSED(HeaderOffset); // On files within storage segments ("data.###"), there is BLTE_ENCODED_HEADER // On local files, there is just BLTE_HEADER if(ConvertBytesToInteger_4_LE(pBlteHeader->Signature) != BLTE_HEADER_SIGNATURE) { PBLTE_ENCODED_HEADER pEncodedHeader; // There must be at least some bytes if(cbEncodedBuffer < FIELD_OFFSET(BLTE_ENCODED_HEADER, MustBe0F)) return ERROR_BAD_FORMAT; pEncodedHeader = (PBLTE_ENCODED_HEADER)pbEncodedBuffer; // Since Jul-2023, users report that the the encoded part of the BLTE header // may contain zeros or even complete garbage. Do NOT test anything else than the signature // Tested on WoW Classic 49821, file "Sound\\Music\\GlueScreenMusic\\wow_main_theme.mp3" // Data File: data.004, file offset 00000000-18BDD2AA (encoded header zeroed) if(ConvertBytesToInteger_4_LE(pEncodedHeader->Signature) != BLTE_HEADER_SIGNATURE) return ERROR_BAD_FORMAT; pBlteHeader = (PBLTE_HEADER)(pEncodedHeader->Signature); ExHeaderSize = FIELD_OFFSET(BLTE_ENCODED_HEADER, Signature); #ifdef CASCLIB_DEBUG // Not really needed, it's here just for explanation of what the values mean //assert(memcmp(pCKeyEntry->EKey, pEncodedHeader->EKey.Value, MD5_HASH_SIZE) == 0); VerifyHeaderSpan(pEncodedHeader, HeaderOffset); #endif } // Capture the header size. If this is non-zero, then array // of chunk headers follow. Otherwise, the file is just one chunk HeaderSize = ConvertBytesToInteger_4(pBlteHeader->HeaderSize); if(HeaderSize != 0) { if(pBlteHeader->MustBe0F != 0x0F) return ERROR_BAD_FORMAT; // Verify the header size FrameCount = ConvertBytesToInteger_3(pBlteHeader->FrameCount); ExpectedHeaderSize = 0x0C + FrameCount * sizeof(BLTE_FRAME); if(ExpectedHeaderSize != HeaderSize) return ERROR_BAD_FORMAT; // Give the values pcbHeaderSize[0] = ExHeaderSize + FIELD_OFFSET(BLTE_HEADER, MustBe0F) + sizeof(DWORD); } else { pcbHeaderSize[0] = ExHeaderSize + FIELD_OFFSET(BLTE_HEADER, MustBe0F); } // Give the frame count pFileSpan->FrameCount = FrameCount; return ERROR_SUCCESS; } static LPBYTE ReadMissingHeaderData(PCASC_FILE_SPAN pFileSpan, ULONGLONG DataFileOffset, LPBYTE pbEncodedBuffer, size_t cbEncodedBuffer, size_t cbTotalHeaderSize) { LPBYTE pbNewBuffer; // Reallocate the buffer. Note that if this fails, the original buffer is still valid pbNewBuffer = CASC_REALLOC(pbEncodedBuffer, cbTotalHeaderSize); if(pbNewBuffer != NULL) { // Load the missing data DataFileOffset += cbEncodedBuffer; if(FileStream_Read(pFileSpan->pStream, &DataFileOffset, pbNewBuffer + cbEncodedBuffer, (DWORD)(cbTotalHeaderSize - cbEncodedBuffer))) { return pbNewBuffer; } } // If anything failed, we free the original buffer and return NULL; CASC_FREE(pbEncodedBuffer); return NULL; } static LPBYTE CaptureBlteFileFrame(CASC_FILE_FRAME & Frame, LPBYTE pbFramePtr, LPBYTE pbFrameEnd) { PBLTE_FRAME pFileFrame = (PBLTE_FRAME)pbFramePtr; // Check whether we have enough data ready if((pbFramePtr + sizeof(BLTE_FRAME)) > pbFrameEnd) return NULL; Frame.FrameHash = pFileFrame->FrameHash; Frame.ContentSize = ConvertBytesToInteger_4(pFileFrame->ContentSize); Frame.EncodedSize = ConvertBytesToInteger_4(pFileFrame->EncodedSize); return pbFramePtr + sizeof(BLTE_FRAME); } static DWORD LoadSpanFrames(PCASC_FILE_SPAN pFileSpan, PCASC_CKEY_ENTRY pCKeyEntry, ULONGLONG DataFileOffset, LPBYTE pbFramePtr, LPBYTE pbFrameEnd, size_t cbHeaderSize) { PCASC_FILE_FRAME pFrames = NULL; DWORD ContentSize = 0; DWORD dwErrCode = ERROR_SUCCESS; assert(pFileSpan != NULL); assert(pFileSpan->pStream != NULL); assert(pFileSpan->pFrames == NULL); if(pFileSpan->FrameCount != 0) { // Move the raw archive offset DataFileOffset += ((ULONGLONG)pFileSpan->FrameCount * sizeof(BLTE_FRAME)); // Allocate array of file frames pFrames = CASC_ALLOC<CASC_FILE_FRAME>(pFileSpan->FrameCount); if(pFrames != NULL) { // Copy the frames to the file structure for(DWORD i = 0; i < pFileSpan->FrameCount; i++) { CASC_FILE_FRAME & Frame = pFrames[i]; // Capture the single BLTE frame pbFramePtr = CaptureBlteFileFrame(Frame, pbFramePtr, pbFrameEnd); if(pbFramePtr == NULL) { dwErrCode = ERROR_BAD_FORMAT; break; } // Fill-in the file range of the frame Frame.StartOffset = pFileSpan->StartOffset + ContentSize; Frame.EndOffset = Frame.StartOffset + Frame.ContentSize; ContentSize += Frame.ContentSize; // Fill-in the archive range of the frame assert((DataFileOffset + Frame.EncodedSize) > DataFileOffset); Frame.DataFileOffset = DataFileOffset; DataFileOffset += Frame.EncodedSize; } // Save the content size of the file if(pCKeyEntry->ContentSize == CASC_INVALID_SIZE) { pCKeyEntry->ContentSize = ContentSize; } } else { dwErrCode = ERROR_NOT_ENOUGH_MEMORY; } } else { // Allocate single "dummy" frame pFrames = CASC_ALLOC<CASC_FILE_FRAME>(1); if(pFrames != NULL) { // Fill the single frame memset(&pFrames->FrameHash, 0, sizeof(CONTENT_KEY)); pFrames->StartOffset = pFileSpan->StartOffset; pFrames->EndOffset = pFileSpan->EndOffset; pFrames->DataFileOffset = DataFileOffset; pFrames->EncodedSize = (DWORD)(pCKeyEntry->EncodedSize - cbHeaderSize); pFrames->ContentSize = pCKeyEntry->ContentSize; // Save the number of file frames pFileSpan->FrameCount = 1; } else { dwErrCode = ERROR_NOT_ENOUGH_MEMORY; } } // Free the frame array on error if(dwErrCode != ERROR_SUCCESS) { pFileSpan->FrameCount = 0; CASC_FREE(pFrames); } pFileSpan->pFrames = pFrames; return dwErrCode; } static DWORD LoadSpanFramesForPlainFile(PCASC_FILE_SPAN pFileSpan, PCASC_CKEY_ENTRY pCKeyEntry) { PCASC_FILE_FRAME pFrames; // Allocate single "dummy" frame pFrames = CASC_ALLOC<CASC_FILE_FRAME>(1); if(pFrames != NULL) { // Setup the size pFileSpan->EndOffset = pFileSpan->StartOffset + pCKeyEntry->ContentSize; pCKeyEntry->Flags |= CASC_CE_PLAIN_DATA; // Fill the single frame memset(&pFrames->FrameHash, 0, sizeof(CONTENT_KEY)); pFrames->StartOffset = pFileSpan->StartOffset; pFrames->EndOffset = pFrames->StartOffset + pCKeyEntry->ContentSize; pFrames->DataFileOffset = 0; pFrames->EncodedSize = pCKeyEntry->EncodedSize; pFrames->ContentSize = pCKeyEntry->ContentSize; // Save the number of file frames pFileSpan->FrameCount = 1; pFileSpan->pFrames = pFrames; return ERROR_SUCCESS; } return ERROR_NOT_ENOUGH_MEMORY; } static DWORD LoadEncodedHeaderAndSpanFrames(PCASC_FILE_SPAN pFileSpan, PCASC_CKEY_ENTRY pCKeyEntry) { LPBYTE pbEncodedBuffer; size_t cbEncodedBuffer = MAX_ENCODED_HEADER; DWORD dwErrCode = ERROR_SUCCESS; // Should only be called when the file frames are NOT loaded assert(pFileSpan->pFrames == NULL); assert(pFileSpan->FrameCount == 0); // Allocate the initial buffer for the encoded headers pbEncodedBuffer = CASC_ALLOC<BYTE>(MAX_ENCODED_HEADER); if(pbEncodedBuffer != NULL) { ULONGLONG ReadOffset = pFileSpan->ArchiveOffs; size_t cbTotalHeaderSize; size_t cbHeaderSize = 0; // At this point, we expect encoded size to be known assert(pCKeyEntry->EncodedSize != CASC_INVALID_SIZE); // Do not read more than encoded size cbEncodedBuffer = CASCLIB_MIN(cbEncodedBuffer, pCKeyEntry->EncodedSize); // Load the entire (eventual) header area. This is faster than doing // two read operations in a row. Read as much as possible. If the file is cut, // the FileStream will pad it with zeros if(FileStream_Read(pFileSpan->pStream, &ReadOffset, pbEncodedBuffer, (DWORD)cbEncodedBuffer)) { // Parse the BLTE header dwErrCode = ParseBlteHeader(pFileSpan, ReadOffset, pbEncodedBuffer, cbEncodedBuffer, &cbHeaderSize); if(dwErrCode == ERROR_SUCCESS) { // If the headers are larger than the initial read size, we read the missing data pFileSpan->HeaderSize = (DWORD)(cbTotalHeaderSize = cbHeaderSize + (pFileSpan->FrameCount * sizeof(BLTE_FRAME))); if(cbTotalHeaderSize > cbEncodedBuffer) { pbEncodedBuffer = ReadMissingHeaderData(pFileSpan, ReadOffset, pbEncodedBuffer, cbEncodedBuffer, cbTotalHeaderSize); if(pbEncodedBuffer == NULL) dwErrCode = GetCascError(); cbEncodedBuffer = cbTotalHeaderSize; } // Load the array of frame headers if(dwErrCode == ERROR_SUCCESS) { assert((ReadOffset + cbHeaderSize) > ReadOffset); dwErrCode = LoadSpanFrames(pFileSpan, pCKeyEntry, ReadOffset + cbHeaderSize, pbEncodedBuffer + cbHeaderSize, pbEncodedBuffer + cbEncodedBuffer, cbHeaderSize); } } else { // Special treatment for plain files ("PATCH"): If the content size and encoded size // are equal, we will create a single fake frame if(pCKeyEntry->EncodedSize == pCKeyEntry->ContentSize) { dwErrCode = LoadSpanFramesForPlainFile(pFileSpan, pCKeyEntry); } } } else { dwErrCode = ERROR_FILE_CORRUPT; } // Free the frame buffer CASC_FREE(pbEncodedBuffer); } else { dwErrCode = ERROR_NOT_ENOUGH_MEMORY; } return dwErrCode; } static DWORD LoadSpanFrames(TCascFile * hf, PCASC_FILE_SPAN pFileSpan, PCASC_CKEY_ENTRY pCKeyEntry) { DWORD dwErrCode = ERROR_SUCCESS; // Sanity check assert(pFileSpan->pFrames == NULL); // Make sure that the data stream is open for that span if(pFileSpan->pStream == NULL) { dwErrCode = OpenDataStream(hf, pFileSpan, pCKeyEntry, hf->bDownloadFileIf); if(dwErrCode != ERROR_SUCCESS) return dwErrCode; } // Make sure we have header area loaded return LoadEncodedHeaderAndSpanFrames(pFileSpan, pCKeyEntry); } // Loads all file spans to memory static DWORD LoadFileSpanFrames(TCascFile * hf) { PCASC_CKEY_ENTRY pCKeyEntry = hf->pCKeyEntry; PCASC_FILE_SPAN pFileSpan = hf->pFileSpan; DWORD dwErrCode = ERROR_SUCCESS; // If the ContentSize/EncodedSize is still unknown, we need to get it from the file frames if(hf->ContentSize == CASC_INVALID_SIZE64 || hf->EncodedSize == CASC_INVALID_SIZE64) { // Set initially to zero hf->ContentSize = 0; hf->EncodedSize = 0; // Load file frames for all spans for(DWORD i = 0; i < hf->SpanCount; i++, pCKeyEntry++, pFileSpan++) { // Init the range of the file span pFileSpan->StartOffset = hf->ContentSize; pFileSpan->EndOffset = hf->ContentSize; // Load the frames of the file span dwErrCode = LoadSpanFrames(hf, pFileSpan, pCKeyEntry); if(dwErrCode != ERROR_SUCCESS) break; hf->ContentSize += pCKeyEntry->ContentSize; hf->EncodedSize += pCKeyEntry->EncodedSize; pFileSpan->EndOffset = hf->ContentSize; } } else { // Load file frames for all spans for(DWORD i = 0; i < hf->SpanCount; i++, pCKeyEntry++, pFileSpan++) { // Load the frames of the file span dwErrCode = LoadSpanFrames(hf, pFileSpan, pCKeyEntry); if(dwErrCode != ERROR_SUCCESS) break; } } return dwErrCode; } static DWORD EnsureFileSpanFramesLoaded(TCascFile * hf) { DWORD dwErrCode; if(hf->ContentSize == CASC_INVALID_SIZE64 || hf->pFileSpan->pFrames == NULL) { // Load all frames of all file spans dwErrCode = LoadFileSpanFrames(hf); if(dwErrCode != ERROR_SUCCESS) return dwErrCode; // Now the content size must be known if(hf->ContentSize == CASC_INVALID_SIZE64) return ERROR_CAN_NOT_COMPLETE; } return ERROR_SUCCESS; } static DWORD DecodeFileFrame( TCascFile * hf, PCASC_CKEY_ENTRY pCKeyEntry, PCASC_FILE_FRAME pFrame, LPBYTE pbEncoded, LPBYTE pbDecoded, DWORD FrameIndex) { TCascStorage * hs = hf->hs; LPBYTE pbWorkBuffer = NULL; DWORD cbDecodedExpected = 0; DWORD cbWorkBuffer = 0; DWORD dwStepCount = 0; DWORD dwErrCode = ERROR_SUCCESS; DWORD cbEncoded = pFrame->EncodedSize; DWORD cbDecoded = pFrame->ContentSize; bool bWorkComplete = false; //if(pFrame->EncodedSize == 0xda001) //{ // FILE * fp = fopen("E:\\frame-da001-002.dat", "wb"); // fwrite(pbEncoded, 1, pFrame->EncodedSize, fp); // fclose(fp); //} // If this is a file span with plain data, just copy the data if(pCKeyEntry->Flags & CASC_CE_PLAIN_DATA) { assert(pCKeyEntry->ContentSize == pCKeyEntry->EncodedSize); assert(pCKeyEntry->ContentSize == pFrame->ContentSize); assert(pFrame->ContentSize == pFrame->EncodedSize); memcpy(pbDecoded, pbEncoded, pCKeyEntry->ContentSize); return ERROR_SUCCESS; } // Shall we verify the frame integrity? if(hf->bVerifyIntegrity) { if(!CascVerifyDataBlockHash(pbEncoded, pFrame->EncodedSize, pFrame->FrameHash.Value)) return ERROR_FILE_CORRUPT; } // Perform the loop while(bWorkComplete == false) { // There should never be a 3rd step assert(dwStepCount < 2); // Perform the operation specific by the first byte switch(pbEncoded[0]) { case 'E': // Encrypted files // The work buffer should not have been allocated by any step assert(pbWorkBuffer == NULL && cbWorkBuffer == 0); // Allocate temporary buffer to decrypt into // Example storage: "2016 - WoW/23420", File: "4ee6bc9c6564227f1748abd0b088e950" pbWorkBuffer = CASC_ALLOC<BYTE>(cbEncoded - 1); cbWorkBuffer = cbEncoded - 1; if(pbWorkBuffer == NULL) return ERROR_NOT_ENOUGH_MEMORY; // Decrypt the stream to the work buffer dwErrCode = CascDecrypt(hs, pbWorkBuffer, &cbWorkBuffer, pbEncoded + 1, cbEncoded - 1, FrameIndex); if(dwErrCode != ERROR_SUCCESS) { bWorkComplete = true; break; } // When encrypted, there is always one more step after this. // Setup the work buffer as input buffer for the next operation pbEncoded = pbWorkBuffer; cbEncoded = cbWorkBuffer; break; case 'Z': // ZLIB compressed files // If we decompressed less than expected, we simply fill the rest with zeros // Example: INSTALL file from the TACT CASC storage cbDecodedExpected = cbDecoded; dwErrCode = CascDecompress(pbDecoded, &cbDecoded, pbEncoded + 1, cbEncoded - 1); // We exactly know what the output buffer size will be. // If the uncompressed data is smaller, fill the rest with zeros if(cbDecoded < cbDecodedExpected) memset(pbDecoded + cbDecoded, 0, (cbDecodedExpected - cbDecoded)); bWorkComplete = true; break; case 'N': // Normal stored files dwErrCode = CascDirectCopy(pbDecoded, &cbDecoded, pbEncoded + 1, cbEncoded - 1); bWorkComplete = true; break; case 'F': // Recursive frames (not supported) default: // Unrecognized. Could be a plain file data dwErrCode = ERROR_NOT_SUPPORTED; bWorkComplete = true; assert(false); break; } // Increment the step count dwStepCount++; } // Some people find it handy to extract data from partially encrypted file, // even at the cost of producing corrupt files. // We overcome missing decryption key by zeroing the encrypted portions if(dwErrCode == ERROR_FILE_ENCRYPTED && hf->bOvercomeEncrypted) { memset(pbDecoded, 0, cbDecoded); dwErrCode = ERROR_SUCCESS; } // Free the temporary buffer CASC_FREE(pbWorkBuffer); return dwErrCode; } static bool GetFileFullInfo(TCascFile * hf, void * pvFileInfo, size_t cbFileInfo, size_t * pcbLengthNeeded) { PCASC_FILE_FULL_INFO pFileInfo; PCASC_CKEY_ENTRY pCKeyEntry = hf->pCKeyEntry; TCascStorage * hs = hf->hs; DWORD dwErrCode; // Make sure that the file spans are loaded dwErrCode = EnsureFileSpanFramesLoaded(hf); if(dwErrCode != ERROR_SUCCESS) { SetCascError(dwErrCode); return false; } // Verify whether we have enough space in the buffer pFileInfo = (PCASC_FILE_FULL_INFO)ProbeOutputBuffer(pvFileInfo, cbFileInfo, sizeof(CASC_FILE_FULL_INFO), pcbLengthNeeded); if(pFileInfo != NULL) { // Reset the entire structure CopyMemory16(pFileInfo->CKey, pCKeyEntry->CKey); CopyMemory16(pFileInfo->EKey, pCKeyEntry->EKey); pFileInfo->FileDataId = CASC_INVALID_ID; pFileInfo->LocaleFlags = CASC_INVALID_ID; pFileInfo->ContentFlags = CASC_INVALID_ID; // Supply information not depending on root CascStrPrintf(pFileInfo->DataFileName, _countof(pFileInfo->DataFileName), "data.%03u", hf->pFileSpan->ArchiveIndex); pFileInfo->StorageOffset = pCKeyEntry->StorageOffset; pFileInfo->SegmentOffset = hf->pFileSpan->ArchiveOffs; pFileInfo->FileNameHash = 0; pFileInfo->TagBitMask = pCKeyEntry->TagBitMask; pFileInfo->ContentSize = hf->ContentSize; pFileInfo->EncodedSize = hf->EncodedSize; pFileInfo->SegmentIndex = hf->pFileSpan->ArchiveIndex; pFileInfo->SpanCount = hf->SpanCount; // Supply the root-specific information hs->pRootHandler->GetInfo(pCKeyEntry, pFileInfo); } return (pFileInfo != NULL); } static bool GetFileSpanInfo(TCascFile * hf, void * pvFileInfo, size_t cbFileInfo, size_t * pcbLengthNeeded) { PCASC_FILE_SPAN_INFO pFileInfo; PCASC_FILE_SPAN pFileSpan = hf->pFileSpan; PCASC_CKEY_ENTRY pCKeyEntry = hf->pCKeyEntry; DWORD dwErrCode = ERROR_SUCCESS; // Make sure that the file spans are loaded dwErrCode = EnsureFileSpanFramesLoaded(hf); if(dwErrCode != ERROR_SUCCESS) { SetCascError(dwErrCode); return false; } // Verify whether we have enough space in the buffer pFileInfo = (PCASC_FILE_SPAN_INFO)ProbeOutputBuffer(pvFileInfo, cbFileInfo, sizeof(CASC_FILE_SPAN_INFO) * hf->SpanCount, pcbLengthNeeded); if(pFileInfo != NULL) { // Copy all file spans for(DWORD i = 0; i < hf->SpanCount; i++, pFileInfo++, pFileSpan++, pCKeyEntry++) { CopyMemory16(pFileInfo->CKey, pCKeyEntry->CKey); CopyMemory16(pFileInfo->EKey, pCKeyEntry->EKey); pFileInfo->StartOffset = pFileSpan->StartOffset; pFileInfo->EndOffset = pFileSpan->EndOffset; pFileInfo->ArchiveIndex = pFileSpan->ArchiveIndex; pFileInfo->ArchiveOffs = pFileSpan->ArchiveOffs; pFileInfo->HeaderSize = pFileSpan->HeaderSize; pFileInfo->FrameCount = pFileSpan->FrameCount; } } return (pFileInfo != NULL); } // Reads the file data from cache. Returns the number of bytes read static DWORD ReadFile_Cache(TCascFile * hf, LPBYTE pbBuffer, ULONGLONG StartOffset, ULONGLONG EndOffset) { // Is there a file cache at all? if(hf->pbFileCache != NULL && hf->FileCacheStart <= StartOffset && StartOffset < hf->FileCacheEnd) { LPBYTE pbStartBlock = hf->pbFileCache + (size_t)(StartOffset - hf->FileCacheStart); // Can we handle the entire request from the cache? if(EndOffset <= hf->FileCacheEnd) { DWORD dwBytesToCopy = (DWORD)(EndOffset - StartOffset); memcpy(pbBuffer, pbStartBlock, dwBytesToCopy); return dwBytesToCopy; } // We copy as much bytes as available. The rest is handled by normal read else { DWORD dwBytesToCopy = (DWORD)(hf->FileCacheEnd - StartOffset); memcpy(pbBuffer, pbStartBlock, dwBytesToCopy); return dwBytesToCopy; } } // Can't handle the request from the cache return 0; } // No cache at all. The entire file will be read directly to the user buffer static DWORD ReadFile_WholeFile(TCascFile * hf, LPBYTE pbBuffer) { PCASC_CKEY_ENTRY pCKeyEntry = hf->pCKeyEntry; PCASC_FILE_SPAN pFileSpan = hf->pFileSpan; LPBYTE pbSaveBuffer = pbBuffer; LPBYTE pbEncoded; LPBYTE pbEncodedPtr; DWORD dwErrCode; for(DWORD SpanIndex = 0; SpanIndex < hf->SpanCount; SpanIndex++, pCKeyEntry++, pFileSpan++) { ULONGLONG ByteOffset = pFileSpan->ArchiveOffs + pFileSpan->HeaderSize; DWORD EncodedSize = pCKeyEntry->EncodedSize - pFileSpan->HeaderSize; // Allocate the buffer for the entire encoded span pbEncodedPtr = pbEncoded = CASC_ALLOC<BYTE>(EncodedSize); if(pbEncoded == NULL) { SetCascError(ERROR_NOT_ENOUGH_MEMORY); return 0; } // Load the encoded buffer if(FileStream_Read(pFileSpan->pStream, &ByteOffset, pbEncoded, EncodedSize)) { PCASC_FILE_FRAME pFileFrame = pFileSpan->pFrames; for(DWORD FrameIndex = 0; FrameIndex < pFileSpan->FrameCount; FrameIndex++, pFileFrame++) { // Decode the file frame dwErrCode = DecodeFileFrame(hf, pCKeyEntry, pFileFrame, pbEncodedPtr, pbBuffer, FrameIndex); if(dwErrCode != ERROR_SUCCESS) break; // Move pointers pbEncodedPtr += pFileFrame->EncodedSize; pbBuffer += pFileFrame->ContentSize; } } CASC_FREE(pbEncoded); } // Give the amount of bytes read return (DWORD)(pbBuffer - pbSaveBuffer); } static DWORD ReadFile_FrameCached(TCascFile * hf, LPBYTE pbBuffer, ULONGLONG StartOffset, ULONGLONG EndOffset) { PCASC_CKEY_ENTRY pCKeyEntry = hf->pCKeyEntry; PCASC_FILE_SPAN pFileSpan = hf->pFileSpan; PCASC_FILE_FRAME pFileFrame = NULL; LPBYTE pbSaveBuffer = pbBuffer; LPBYTE pbEncoded = NULL; LPBYTE pbDecoded = NULL; DWORD dwBytesRead = 0; DWORD dwErrCode = ERROR_SUCCESS; bool bNeedFreeDecoded = true; // Parse all file spans for(DWORD SpanIndex = 0; SpanIndex < hf->SpanCount; SpanIndex++, pCKeyEntry++, pFileSpan++) { if(pFileSpan->StartOffset <= StartOffset && StartOffset < pFileSpan->EndOffset) { for(DWORD FrameIndex = 0; FrameIndex < pFileSpan->FrameCount; FrameIndex++) { // Get the current file frame pFileFrame = pFileSpan->pFrames + FrameIndex; // Check the frame byte range if(pFileFrame->StartOffset <= StartOffset && StartOffset < pFileFrame->EndOffset) { // Check bytes read overflow if((dwBytesRead + pFileFrame->ContentSize) < dwBytesRead) { SetCascError(ERROR_BUFFER_OVERFLOW); return 0; } // Pick the buffer for decoded data. If we are going to read the entire frame, // there is a little chance that the caller will read the same file range again // So we can as well just unpack the entire frame into the output buffer if(pFileFrame->StartOffset < StartOffset || EndOffset < pFileFrame->EndOffset) { if((pbDecoded = CASC_ALLOC<BYTE>(pFileFrame->ContentSize)) == NULL) { SetCascError(ERROR_NOT_ENOUGH_MEMORY); return 0; } bNeedFreeDecoded = true; } else { bNeedFreeDecoded = false; pbDecoded = pbBuffer; } // Allocate the encoded frame if((pbEncoded = CASC_ALLOC<BYTE>(pFileFrame->EncodedSize)) == NULL) { CASC_FREE(pbDecoded); SetCascError(ERROR_NOT_ENOUGH_MEMORY); return 0; } // Load the frame to the encoded buffer if(FileStream_Read(pFileSpan->pStream, &pFileFrame->DataFileOffset, pbEncoded, pFileFrame->EncodedSize)) { ULONGLONG EndOfCopy = CASCLIB_MIN(pFileFrame->EndOffset, EndOffset); DWORD dwBytesToCopy = (DWORD)(EndOfCopy - StartOffset); // Decode the frame dwErrCode = DecodeFileFrame(hf, pCKeyEntry, pFileFrame, pbEncoded, pbDecoded, FrameIndex); if(dwErrCode == ERROR_SUCCESS) { // Copy the data if(pbDecoded != pbBuffer) memcpy(pbBuffer, pbDecoded + (DWORD)(StartOffset - pFileFrame->StartOffset), dwBytesToCopy); StartOffset += dwBytesToCopy; pbBuffer += dwBytesToCopy; } } // Free the encoded buffer CASC_FREE(pbEncoded); // If we are at the end of the read area, break all loops if(dwErrCode != ERROR_SUCCESS || StartOffset >= EndOffset) goto __WorkComplete; if(bNeedFreeDecoded) CASC_FREE(pbDecoded); } } } } __WorkComplete: if(dwErrCode == ERROR_SUCCESS) { // If there is some data left in the frame, we set it as cache if(pFileFrame != NULL && pbDecoded != NULL && EndOffset < pFileFrame->EndOffset) { CASC_FREE(hf->pbFileCache); hf->FileCacheStart = pFileFrame->StartOffset; hf->FileCacheEnd = pFileFrame->EndOffset; hf->pbFileCache = pbDecoded; pbDecoded = NULL; } } // Final free of the decoded buffer, if needeed if(bNeedFreeDecoded) CASC_FREE(pbDecoded); pbDecoded = NULL; // Return the number of bytes read. Always set LastError. SetCascError(dwErrCode); return (DWORD)(pbBuffer - pbSaveBuffer); } // No cache at all. The entire file will be read directly to the user buffer static DWORD ReadFile_NonCached(TCascFile * hf, LPBYTE pbBuffer, ULONGLONG StartOffset, ULONGLONG EndOffset) { // Reading the whole file? if(StartOffset == 0 && EndOffset == hf->ContentSize) { return ReadFile_WholeFile(hf, pbBuffer); } // Reading just a part of the file? else { assert(false); } return 0; } //----------------------------------------------------------------------------- // Public functions bool WINAPI CascGetFileInfo(HANDLE hFile, CASC_FILE_INFO_CLASS InfoClass, void * pvFileInfo, size_t cbFileInfo, size_t * pcbLengthNeeded) { TCascFile * hf; LPBYTE pbOutputValue = NULL; LPBYTE pbInfoValue = NULL; size_t cbInfoValue = 0; // Validate the file handle if((hf = TCascFile::IsValid(hFile)) == NULL) { SetCascError(ERROR_INVALID_HANDLE); return false; } // Differentiate between info classes switch(InfoClass) { case CascFileContentKey: // Do we have content key at all? if(hf->pCKeyEntry == NULL || (hf->pCKeyEntry->Flags & CASC_CE_HAS_CKEY) == 0) { SetCascError(ERROR_NOT_SUPPORTED); return false; } // Give the content key pbInfoValue = hf->pCKeyEntry->CKey; cbInfoValue = CASC_CKEY_SIZE; break; case CascFileEncodedKey: // Do we have content key at all? if(hf->pCKeyEntry == NULL || (hf->pCKeyEntry->Flags & CASC_CE_HAS_EKEY) == 0) { SetCascError(ERROR_NOT_SUPPORTED); return false; } // Give the content key pbInfoValue = hf->pCKeyEntry->EKey; cbInfoValue = CASC_CKEY_SIZE; break; case CascFileFullInfo: return GetFileFullInfo(hf, pvFileInfo, cbFileInfo, pcbLengthNeeded); case CascFileSpanInfo: return GetFileSpanInfo(hf, pvFileInfo, cbFileInfo, pcbLengthNeeded); default: SetCascError(ERROR_INVALID_PARAMETER); return false; } // Sanity check assert(pbInfoValue != NULL); assert(cbInfoValue != 0); // Give the result pbOutputValue = (LPBYTE)ProbeOutputBuffer(pvFileInfo, cbFileInfo, cbInfoValue, pcbLengthNeeded); if(pbOutputValue != NULL) memcpy(pbOutputValue, pbInfoValue, cbInfoValue); return (pbOutputValue != NULL); } bool WINAPI CascSetFileFlags(HANDLE hFile, DWORD dwOpenFlags) { TCascFile * hf; // Validate the file handle if((hf = TCascFile::IsValid(hFile)) == NULL) { SetCascError(ERROR_INVALID_HANDLE); return false; } // Currently, only CASC_OVERCOME_ENCRYPTED can be changed if(dwOpenFlags & ~CASC_OVERCOME_ENCRYPTED) { SetCascError(ERROR_INVALID_PARAMETER); return false; } // Set "overcome encrypted" flag. Will apply on next CascReadFile hf->bOvercomeEncrypted = (dwOpenFlags & CASC_OVERCOME_ENCRYPTED) ? true : false; return true; } // // THE FILE SIZE PROBLEM // // There are members called "FileSize" in many CASC-related structure // For various files, these variables have different meaning. // // Storage FileName FileSize FrameSum HdrArea CKeyEntry EKeyEntry RootEntry // ----------- -------- ---------- -------- -------- ---------- ---------- ---------- // HotS(29049) ENCODING 0x0024BA45 - 0x0024b98a 0x0024BA45 n/a 0x0024BA45 n/a // HotS(29049) ROOT 0x00193340 - 0x00193340 0x0010db65 0x00193340 0x0010db65 n/a // HotS(29049) (other) 0x00001080 - 0x00001080 0x000008eb 0x00001080 0x000008eb 0x00001080 // // WoW(18888) ENCODING 0x030d487b - 0x030dee79 0x030d487b n/a 0x030d487b n/a // WoW(18888) ROOT 0x016a9800 - n/a 0x0131313d 0x016a9800 0x0131313d n/a // WoW(18888) (other) 0x000007d0 - 0x000007d0 0x00000397 0x000007d0 0x00000397 n/a // bool WINAPI CascGetFileSize64(HANDLE hFile, PULONGLONG PtrFileSize) { TCascFile * hf; DWORD dwErrCode; // Validate the file pointer if(PtrFileSize == NULL) { SetCascError(ERROR_INVALID_PARAMETER); return false; } // Validate the file handle if((hf = TCascFile::IsValid(hFile)) == NULL) { SetCascError(ERROR_INVALID_HANDLE); return false; } // If the content key is zeros, we treat the file as a file with size of 0 if(hf->ContentSize == 0) { PtrFileSize[0] = 0; return true; } // ENCODING on older storages: Content size is not present in the BUILD file // For that reason, we need to query the content size from the file frames dwErrCode = EnsureFileSpanFramesLoaded(hf); if(dwErrCode != ERROR_SUCCESS) { SetCascError(dwErrCode); return false; } // Give the file size to the caller PtrFileSize[0] = hf->ContentSize; return true; } DWORD WINAPI CascGetFileSize(HANDLE hFile, PDWORD PtrFileSizeHigh) { ULONGLONG FileSize = 0; // Retrieve the 64-bit file size if(!CascGetFileSize64(hFile, &FileSize)) return CASC_INVALID_SIZE; // Give the file size to the caller if(PtrFileSizeHigh != NULL) PtrFileSizeHigh[0] = (DWORD)(FileSize >> 32); return (DWORD)(FileSize); } bool WINAPI CascSetFilePointer64(HANDLE hFile, LONGLONG DistanceToMove, PULONGLONG PtrNewPos, DWORD dwMoveMethod) { ULONGLONG FilePosition; TCascFile * hf; // If the hFile is not a valid file handle, return an error. hf = TCascFile::IsValid(hFile); if(hf == NULL) { SetCascError(ERROR_INVALID_HANDLE); return false; } // Get the relative point where to move from switch(dwMoveMethod) { case FILE_BEGIN: FilePosition = 0; break; case FILE_CURRENT: FilePosition = hf->FilePointer; break; case FILE_END: FilePosition = hf->ContentSize; break; default: SetCascError(ERROR_INVALID_PARAMETER); return false; } // Now calculate the new file pointer if(DistanceToMove >= 0) { // Do not allow the file pointer to overflow 64-bit range if((FilePosition + DistanceToMove) < FilePosition) { SetCascError(ERROR_INVALID_PARAMETER); return false; } // Do not allow the file pointer to overflow the file size if((FilePosition = FilePosition + DistanceToMove) > hf->ContentSize) FilePosition = hf->ContentSize; hf->FilePointer = FilePosition; } else { // Do not allow the file pointer to underflow 64-bit range if((FilePosition + DistanceToMove) > FilePosition) { SetCascError(ERROR_INVALID_PARAMETER); return false; } // Do not allow the file pointer to move to negative values if((LONGLONG)(FilePosition = FilePosition + DistanceToMove) < 0) FilePosition = 0; hf->FilePointer = FilePosition; } // Give the result size to the caller if(PtrNewPos != NULL) PtrNewPos[0] = hf->FilePointer; return true; } DWORD WINAPI CascSetFilePointer(HANDLE hFile, LONG lFilePos, LONG * PtrFilePosHigh, DWORD dwMoveMethod) { ULONGLONG NewPos = 0; LONGLONG DistanceToMove; // Assemble the 64-bit distance to move DistanceToMove = (PtrFilePosHigh != NULL) ? MAKE_OFFSET64(PtrFilePosHigh[0], lFilePos) : (LONGLONG)(LONG)lFilePos; // Set the file offset if(!CascSetFilePointer64(hFile, DistanceToMove, &NewPos, dwMoveMethod)) return CASC_INVALID_POS; // Give the result to the caller if(PtrFilePosHigh != NULL) PtrFilePosHigh[0] = (LONG)(NewPos >> 32); return (DWORD)(NewPos); } bool WINAPI CascReadFile(HANDLE hFile, void * pvBuffer, DWORD dwBytesToRead, PDWORD PtrBytesRead) { ULONGLONG SaveFilePointer; ULONGLONG StartOffset; ULONGLONG EndOffset; TCascFile * hf; LPBYTE pbBuffer = (LPBYTE)pvBuffer; DWORD dwBytesRead1 = 0; // From cache DWORD dwBytesRead2 = 0; // From file DWORD dwErrCode; // The buffer must be valid if(pvBuffer == NULL) { SetCascError(ERROR_INVALID_PARAMETER); return false; } // Validate the file handle if((hf = TCascFile::IsValid(hFile)) == NULL) { SetCascError(ERROR_INVALID_HANDLE); return false; } // Check files with zero size if(hf->ContentSize == 0) { PtrBytesRead[0] = 0; return true; } // If we don't have file frames loaded, we need to do it now. // Need to do it before file range check, as the file size may be unknown at this point dwErrCode = EnsureFileSpanFramesLoaded(hf); if(dwErrCode != ERROR_SUCCESS) { SetCascError(dwErrCode); return false; } // If the file position is at or beyond end of file, do nothing SaveFilePointer = StartOffset = hf->FilePointer; if(StartOffset >= hf->ContentSize) { PtrBytesRead[0] = 0; return true; } // If the read area goes beyond end of the file, cut the number of bytes to read EndOffset = StartOffset + dwBytesToRead; if(EndOffset > hf->ContentSize) { EndOffset = hf->ContentSize; } // Can we handle the request (at least partially) from the cache? if((dwBytesRead1 = ReadFile_Cache(hf, pbBuffer, StartOffset, EndOffset)) != 0) { // Move pointers StartOffset = StartOffset + dwBytesRead1; pbBuffer += dwBytesRead1; // Has the read request been fully satisfied? if(StartOffset == EndOffset) { if(PtrBytesRead != NULL) PtrBytesRead[0] = dwBytesRead1; hf->FilePointer = EndOffset; return true; } } // Perform the cache-strategy-specific read switch(hf->CacheStrategy) { // No caching at all. The entire file will be read directly to the user buffer // Used for loading internal files, where we need to read the whole file case CascCacheNothing: dwBytesRead2 = ReadFile_NonCached(hf, pbBuffer, StartOffset, EndOffset); break; // Read as many frames as we can. The last loaded frame, if not read entirely, // will stay in the cache - We expect the next read to continue from that offset. case CascCacheLastFrame: dwBytesRead2 = ReadFile_FrameCached(hf, pbBuffer, StartOffset, EndOffset); break; default: break; } // If the second-stage-read failed, we invalidate the entire operation and return 0 bytes read if(dwBytesRead2 != 0) { // Give the result to the caller if(PtrBytesRead != NULL) PtrBytesRead[0] = (dwBytesRead1 + dwBytesRead2); hf->FilePointer = StartOffset + dwBytesRead2; return true; } else { // Give the result to the caller if(PtrBytesRead != NULL) PtrBytesRead[0] = 0; hf->FilePointer = SaveFilePointer; // If 0 bytes were requested, it's actually a success return (dwBytesToRead == 0); } }
412
0.985535
1
0.985535
game-dev
MEDIA
0.363433
game-dev
0.997969
1
0.997969
latte-soft/datamodelpatch
26,906
src/PatchRoot/DataModelInstances/CoreGui/RobloxGui/Modules/LuaApp/Components/ExperienceDetails/ExperienceInfoTable.luau
local l_CorePackages_0 = game:GetService("CorePackages"); local l_Modules_0 = game:GetService("CoreGui").RobloxGui.Modules; local v2 = require(l_CorePackages_0.Packages.React); local v3 = require(l_CorePackages_0.Packages.Dash); local v4 = require(l_CorePackages_0.Workspace.Packages.RoactUtils); local v5 = require(l_CorePackages_0.Workspace.Packages.Localization); local l_useDispatch_0 = v4.Hooks.RoactRodux.useDispatch; local l_useLocalization_0 = v5.Hooks.useLocalization; local v8 = require(l_Modules_0.LuaApp.Hooks.useRoactService); local v9 = require(l_Modules_0.LuaApp.Components.ExperienceDetails.Hooks.useExperienceInfoData); local v10 = require(l_Modules_0.LuaApp.Flags.GetFFlagLuaAppRefactorExperienceInfoTable); local v11 = require(l_Modules_0.LuaApp.Flags.GetFFlagLuaAppFixExperienceInfoShowServersPolicy); local v12 = require(l_Modules_0.Common.RoactRodux); local v13 = require(l_CorePackages_0.Packages.t); local v14 = require(l_CorePackages_0.UIBlox); local v15 = require(l_Modules_0.LuaApp.Http.UrlBuilder); local l_memoize_0 = require(l_CorePackages_0.Workspace.Packages.AppCommonLib).memoize; local v17 = require(l_CorePackages_0.Workspace.Packages.VerifiedBadges); local l_RoactAppPolicy_0 = require(l_CorePackages_0.Workspace.Packages.UniversalAppPolicy).RoactAppPolicy; local v19 = require(l_Modules_0.LuaApp.Hooks.useAppPolicy); local l_RoactServices_0 = require(l_CorePackages_0.Workspace.Packages.RoactServices).RoactServices; local v21 = require(l_Modules_0.LuaApp.Services.RoactLocalization); local v22 = require(l_Modules_0.LuaApp.Services.AppEventIngestService); local l_AppLinking_0 = require(l_CorePackages_0.Workspace.Packages.RoactServiceTags).AppLinking; local v24 = require(l_CorePackages_0.Workspace.Packages.RoactAppExperiment); local v25 = require(l_Modules_0.LuaApp.Experiment.AppUserLayers); local v26 = require(l_Modules_0.LuaApp.Models.ExperienceGuidelinesApi.AgeRecommendationDetails); local l_getCommunityUrl_0 = require(l_CorePackages_0.Workspace.Packages.CommunityLinks).Utils.getCommunityUrl; local l_GuildedLogoWhiteAsset_0 = require(l_CorePackages_0.Workspace.Packages.CommunityLinks).Constants.GuildedLogoWhiteAsset; local l_Constants_0 = require(l_CorePackages_0.Workspace.Packages.CommunityLinks).Analytics.Constants; local l_clickCommunityLinkEvent_0 = require(l_CorePackages_0.Workspace.Packages.CommunityLinks).Analytics.Events.clickCommunityLinkEvent; local v31 = require(l_Modules_0.LuaApp.Thunks.NavigateDown); local v32 = require(l_Modules_0.LuaApp.Thunks.OpenExperienceGuidelinesExplained); local v33 = require(l_Modules_0.LuaApp.Thunks.OpenCentralOverlayForLeaveRobloxAlert); local v34 = require(l_Modules_0.LuaApp.Thunks.CloseCentralOverlay); local v35 = require(l_Modules_0.LuaApp.Flags.GetFFlagRemoveVerifiedBadgeReducer); local v36 = require(l_Modules_0.LuaApp.Flags.GetFFlagGameDetailsCameraChatFeatures); local v37 = require(l_Modules_0.LuaApp.Flags.GetFFlagGameDetailsDecoupledCommunication); local v38 = require(l_Modules_0.LuaApp.Flags.GetFFlagGameDetailsCommunication); local v39 = require(l_Modules_0.LuaApp.Flags.GetFFlagLuaAppExperienceInfoPanel); local v40 = require(l_Modules_0.LuaApp.Flags.GetFFlagShowCameraToU13); local l_GetFFlagEnableDetailsPageCommunityLinks_0 = require(l_CorePackages_0.Workspace.Packages.SharedFlags).GetFFlagEnableDetailsPageCommunityLinks; local l_GetFFlagEnableCommunityLinksClickLogging_0 = require(l_CorePackages_0.Workspace.Packages.SharedFlags).GetFFlagEnableCommunityLinksClickLogging; local v43 = require(l_Modules_0.LuaApp.Flags.GetFFlagRenamePassesAndGearToSubscriptionsAndPasses); local l_ListTable_0 = v14.App.Table.ListTable; local v45 = require(script.Parent.ExperienceInfoTableRow); local v46 = require(l_Modules_0.LuaApp.AppPage); local v47 = require(script.Parent.ExperienceDetailsPanel); if not v10() then local v48 = v2.PureComponent:extend("ExperienceInfoTable"); v48.validateProps = v13.interface({ universeId = v13.string, renderTextOverride = v13.optional(v13.callback), ageRecommendations = v13.optional(v26.validateModel) }); local v49 = { All = "Feature.GameDetails.Label.GenreAll", Adventure = "Feature.GameDetails.Label.GenreAdventure", Building = "Feature.GameDetails.Label.GenreBuilding", Comedy = "Feature.GameDetails.Label.GenreComedy", Fighting = "Feature.GameDetails.Label.GenreFighting", FPS = "Feature.GameDetails.Label.GenreFPS", Horror = "Feature.GameDetails.Label.LabelGenreHorror", Medieval = "Feature.GameDetails.Label.GenreMedieval", Military = "Feature.GameDetails.Label.GenreMilitary", Naval = "Feature.GameDetails.Label.GenreNaval", RPG = "Feature.GameDetails.Label.GenreRPG", ["Sci-Fi"] = "Feature.GameDetails.Label.GenreSciFi", Sports = "Feature.GameDetails.Label.LabelGenreSports", ["Town and City"] = "Feature.GameDetails.Label.LabelGenreTownAndCity", Western = "Feature.GameDetails.Label.GenreWestern" }; v48.init = function(v50) v50.getCells = l_memoize_0(function(v51, _, _) local v54 = {}; if v51 then local l_localization_0 = v50.props.localization; local l_l_localization_0_Locale_0 = l_localization_0:GetLocale(); local l_universeId_0 = v50.props.universeId; local l_rootPlaceId_0 = v51.rootPlaceId; local l_eventIngest_0 = v50.props.eventIngest; local l_navigateDown_0 = v50.props.navigateDown; local l_showBadgesRow_0 = v50.props.showBadgesRow; local l_showCreatedRow_0 = v50.props.showCreatedRow; local l_showDeveloperRow_0 = v50.props.showDeveloperRow; local l_showRNVDeveloper_0 = v50.props.showRNVDeveloper; local l_showGamepassesRow_0 = v50.props.showGamepassesRow; local l_showGenreRow_0 = v50.props.showGenreRow; local l_showMaxPlayersRow_0 = v50.props.showMaxPlayersRow; local v68 = if not v11() then v50.props.showGamepassesRow else v50.props.showServersRow; local l_showUpdatedRow_0 = v50.props.showUpdatedRow; local v70 = false; if not v36() then if not v40() then if v37() then v70 = not v50.props.isLocalUserUnder13; end; else v70 = true; end; else v70 = v50.props.userVoiceEnabled; end; local v71 = not v70 and v50.props.userVoiceEnabled; local l_experienceVoiceEnabled_0 = v50.props.experienceVoiceEnabled; local l_experienceVideoEnabled_0 = v50.props.experienceVideoEnabled; local l_showPasses_0 = v50.props.showPasses; local l_showBadges_0 = v50.props.showBadges; local l_webViewSupport_0 = v50.props.webViewSupport; if not l_showBadgesRow_0 then l_showBadges_0 = false; end; if not l_showGamepassesRow_0 then l_showPasses_0 = false; end; local l_communityLinksEnabled_0 = v50.props.communityLinksEnabled; local l_communityLinkVariant_0 = v50.props.communityLinkVariant; if not ((not l_GetFFlagEnableDetailsPageCommunityLinks_0() or not l_communityLinksEnabled_0) or not v50.props.communityLink) and l_communityLinkVariant_0 == "infolist" then table.insert(v54, v2.createElement(v45, { infoName = l_localization_0:Format("Feature.GameDetails.Label.Community"), infoData = "", infoIcon = l_GuildedLogoWhiteAsset_0, externalLinkProps = { linkUrl = l_getCommunityUrl_0(v50.props.communityLink.communityId), openLeaveRobloxAlert = v50.props.openLeaveRobloxAlert, closeAlert = v50.props.closeAlert, linking = v50.props.linking, clickCallback = if not l_GetFFlagEnableCommunityLinksClickLogging_0() then nil else function() l_clickCommunityLinkEvent_0(l_eventIngest_0, l_Constants_0.Context.ExperienceInfoList, { guildedServerId = v50.props.communityLink.communityId, entityType = "universe", entityId = l_universeId_0 }); end } })); end; if v50.props.ageRecommendations then local l_summary_0 = v50.props.ageRecommendations.summary; local v80 = if not not l_summary_0 and l_summary_0.ageRecommendation then l_summary_0.ageRecommendation.displayName else nil; table.insert(v54, v2.createElement(v45, { infoName = l_localization_0:Format("Feature.GameDetails.Label.AgeGuidelines"), infoData = v80 or l_localization_0:Format("Feature.GameDetails.Label.Unavailable"), linkProps = if not v80 then nil else { analyticsSubPage = v46.ExperienceGuidelinesExplained, rootPlaceId = l_rootPlaceId_0, eventIngest = l_eventIngest_0, navigate = v50.props.openExperienceGuidelinesExplained, navigateProps = l_universeId_0 } })); end; local l_creator_0 = v51.creator; local v82 = if not v35() then v50.props.creatorVerified else l_creator_0.hasVerifiedBadge; local l_renderTextOverride_0 = v50.props.renderTextOverride; if not (not l_showDeveloperRow_0 and (not l_showRNVDeveloper_0 or not l_creator_0.isRNVAccount)) then local l_id_0 = l_creator_0.id; local l_name_0 = l_creator_0.name; local l_type_0 = l_creator_0.type; local l_l_name_0_0 = l_name_0 --[[ copy: 32 -> 34 ]]; local l_l_id_0_0 = l_id_0 --[[ copy: 31 -> 35 ]]; table.insert(v54, v2.createElement(v45, { infoName = l_localization_0:Format("Feature.GameDetails.Label.Developer"), infoData = l_name_0, renderTextOverride = function() if not l_renderTextOverride_0 then return nil; else return l_renderTextOverride_0(l_l_name_0_0, l_l_id_0_0, l_universeId_0, v82); end; end, linkProps = if not l_webViewSupport_0 then nil else { linkPage = v15.game.info.creator({ creatorType = l_type_0, creatorId = l_id_0 }), analyticsSubPage = "Developer", rootPlaceId = l_rootPlaceId_0, eventIngest = l_eventIngest_0, navigate = l_navigateDown_0 }, externalLinkProps = if l_webViewSupport_0 then nil else { linkUrl = v15.game.info.creator({ creatorType = l_type_0, creatorId = l_id_0 }), openLeaveRobloxAlert = v50.props.openLeaveRobloxAlert, closeAlert = v50.props.closeAlert, linking = v50.props.linking } })); end; if l_showMaxPlayersRow_0 then table.insert(v54, v2.createElement(v45, { infoName = l_localization_0:Format("Feature.GameDetails.Label.MaxPlayers"), infoData = tostring(v51.maxPlayers) })); end; if l_showGenreRow_0 then local l_genre_0 = v51.genre; local v90 = v49[l_genre_0]; if v90 ~= nil then l_genre_0 = l_localization_0:Format(v90); end; table.insert(v54, v2.createElement(v45, { infoName = l_localization_0:Format("Feature.GameDetails.Label.Genre"), infoData = l_genre_0 })); end; if l_showCreatedRow_0 then local v91 = DateTime.fromIsoDate(v51.created); assert(v91, "invalid GameDetail created date"); table.insert(v54, v2.createElement(v45, { infoName = l_localization_0:Format("Feature.GameDetails.Label.Created"), infoData = v91:FormatLocalTime("l", l_l_localization_0_Locale_0) })); end; if l_showUpdatedRow_0 then local v92 = DateTime.fromIsoDate(v51.updated); assert(v92, "invalid GameDetail updated date"); table.insert(v54, v2.createElement(v45, { infoName = l_localization_0:Format("Feature.GameDetails.Label.Updated"), infoData = v92:FormatLocalTime("l", l_l_localization_0_Locale_0) })); end; if v71 then table.insert(v54, v2.createElement(v45, { infoName = l_localization_0:Format("Feature.GameDetails.Label.VoiceEnabled"), infoData = not not l_experienceVoiceEnabled_0 and l_localization_0:Format("Feature.GameDetails.Label.Yes") or l_localization_0:Format("Feature.GameDetails.Label.No") })); end; if v70 then local v93 = l_localization_0:Format("Feature.GameDetails.Label.None"); local v94 = nil; if not v37() then if l_experienceVoiceEnabled_0 then v93 = l_localization_0:Format("Feature.GameDetails.Label.Microphone"); if not v36() then v94 = "rbxasset://textures/ui/VoiceChat/Blank.png"; elseif l_experienceVideoEnabled_0 then v93 = v93 .. ", " .. l_localization_0:Format("Feature.GameDetails.Label.Camera"); end; end; table.insert(v54, v2.createElement(v45, { infoName = l_localization_0:Format(not v38() and "Feature.GameDetails.Label.ChatFeatures" or "Feature.AccountSettings.Heading.Communication"), infoData = v93, infoIcon = v94 })); else local v95 = {}; if not v40() then if l_experienceVoiceEnabled_0 then table.insert(v95, l_localization_0:Format("Feature.GameDetails.Label.Microphone")); end; elseif not (not l_experienceVoiceEnabled_0 or v50.props.isLocalUserUnder13) then table.insert(v95, l_localization_0:Format("Feature.GameDetails.Label.Microphone")); end; if l_experienceVideoEnabled_0 then table.insert(v95, l_localization_0:Format("Feature.GameDetails.Label.Camera")); end; if #v95 < 1 then table.insert(v95, l_localization_0:Format("Feature.GameDetails.Label.None")); end; table.insert(v54, v2.createElement(v45, { infoName = l_localization_0:Format("Feature.AccountSettings.Heading.Communication"), infoData = table.concat(v95, ", "), infoIcon = v94 })); end; end; if not (not l_showPasses_0 or not l_webViewSupport_0) then table.insert(v54, v2.createElement(v45, { infoName = l_localization_0:Format(not v43() and "Feature.GameDetails.Label.PassesAndGear" or "Feature.GameDetails.Label.SubscriptionsAndPasses"), infoData = "", linkProps = { linkPage = v15.game.info.store({ universeId = l_universeId_0 }), analyticsSubPage = "PassesAndGear", rootPlaceId = l_rootPlaceId_0, eventIngest = l_eventIngest_0, navigate = l_navigateDown_0 } })); end; if not (not l_showBadges_0 or not l_webViewSupport_0) then table.insert(v54, v2.createElement(v45, { infoName = l_localization_0:Format("CommonUI.Features.Label.Badges"), infoData = "", linkProps = { linkPage = v15.game.info.badges({ universeId = l_universeId_0 }), analyticsSubPage = "Badges", rootPlaceId = l_rootPlaceId_0, eventIngest = l_eventIngest_0, navigate = l_navigateDown_0 } })); end; if not (not v68 or not l_webViewSupport_0) then table.insert(v54, v2.createElement(v45, { infoName = l_localization_0:Format("Feature.GameDetails.Label.Servers"), infoData = "", linkProps = { linkPage = v15.game.info.servers({ universeId = l_universeId_0 }), analyticsSubPage = "Servers", rootPlaceId = l_rootPlaceId_0, eventIngest = l_eventIngest_0, navigate = l_navigateDown_0 } })); end; local l_groupLink_0 = v50.props.groupLink; local l_enableGroupLinks_0 = v50.props.enableGroupLinks; if not ((not l_groupLink_0 or not l_enableGroupLinks_0) or not l_webViewSupport_0) then table.insert(v54, v2.createElement(v45, { infoName = l_localization_0:Format("Feature.GameDetails.Label.Group"), infoData = "", linkProps = { linkPage = l_groupLink_0.url, analyticsSubPage = "Group", rootPlaceId = l_rootPlaceId_0, eventIngest = l_eventIngest_0, navigate = l_navigateDown_0 } })); end; return v54; else return v54; end; end); end; v48.render = function(v98) return v2.createElement(l_ListTable_0, { cells = v98.getCells(v98.props.gameDetail, v98.props.ageRecommendations, v98.props.communityLink), automaticSize = Enum.AutomaticSize.Y }); end; v48 = v12.connect(function(v99, v100) local l_universeId_1 = v100.universeId; local v102 = v99.GamePasses[l_universeId_1]; local v103 = v99.GameBadges[l_universeId_1]; local v104 = true; local v105 = true; if v102 and #v102 == 0 then v104 = false; end; if v103 and #v103 == 0 then v105 = false; end; local v106 = v99.VoiceChatOptInStatus.isUserOptIn or false; local v107 = false; local v108 = false; if v99.ShowAgeVerificationOverlay[l_universeId_1] then v107 = v99.ShowAgeVerificationOverlay[l_universeId_1].isUniverseEnabledForVoice; if not (not v36() and not v37()) then v108 = v99.ShowAgeVerificationOverlay[l_universeId_1].isUniverseEnabledForAvatarVideo; end; end; local v109 = v99.GameSocialLinks[l_universeId_1]; local v110 = v109 and v109.groupLink; local v111 = if not v35() then v17.isCreatorOfGameVerified(v99, v100) else nil; local v112 = nil; if l_GetFFlagEnableDetailsPageCommunityLinks_0() then v112 = v99.CommunityLinks.ExperienceCommunityLinks[l_universeId_1] or nil; end; return { gameDetail = v99.GameDetails[l_universeId_1], creatorVerified = v111, showPasses = v104, showBadges = v105, userVoiceEnabled = v106, experienceVoiceEnabled = v107, experienceVideoEnabled = v108, groupLink = v110, communityLink = v112, isLocalUserUnder13 = v99.IsLocalUserUnder13, ageRecommendations = v99.AgeRecommendations[l_universeId_1] }; end, function(v113) return { navigateDown = function(v114) return v113(v31(v114)); end, openExperienceGuidelinesExplained = function(v115) v113(v32(v115)); end, openLeaveRobloxAlert = function(v116) v113(v33(v116)); end, closeAlert = function() v113(v34()); end }; end)(v48); if l_GetFFlagEnableDetailsPageCommunityLinks_0() then v48 = v24.connectUserLayer({ v25.EDPCommunityLinksLayer }, function(v117) local v118 = (v117[v25.EDPCommunityLinksLayer] or {}).communityLinkDisplayConfig or {}; return { communityLinksEnabled = v118.inTreatment, communityLinkVariant = v118.linkVariant }; end, false)(v48); end; return l_RoactServices_0.connect({ localization = v21, eventIngest = v22, linking = l_AppLinking_0 })((l_RoactAppPolicy_0.connect(function(v119) return { showBadgesRow = v119.getGameInfoShowBadges(), showCreatedRow = v119.getGameInfoShowCreated(), showDeveloperRow = v119.getGameInfoListDeveloper(), showRNVDeveloper = v119.getGameInfoListShowRNVDeveloper(), showGamepassesRow = v119.getGameInfoShowGamepasses(), showGenreRow = v119.getGameInfoShowGenre(), showMaxPlayersRow = v119.getGameInfoShowMaxPlayers(), showServersRow = v119.getGameInfoShowServers(), showUpdatedRow = v119.getGameInfoShowUpdated(), enableGroupLinks = v119.getSocialGroupLinks(), webViewSupport = v119.getWebViewSupport(), showChatFeaturesRow = v119.getGameInfoShowChatFeatures() }; end)(v48))); else return v2.forwardRef(function(v120, v121) local v122 = v9(v120.universeId); local v123 = v8(v22); local v124 = l_useDispatch_0(); local v126 = v2.useCallback(function(v125) v124(v31(v125)); end); local v127 = if not l_GetFFlagEnableDetailsPageCommunityLinks_0() then nil else v8(l_AppLinking_0); local v129 = if not l_GetFFlagEnableDetailsPageCommunityLinks_0() then nil else v2.useCallback(function(v128) v124(v33(v128)); end, { v124 }); local v130 = if not l_GetFFlagEnableDetailsPageCommunityLinks_0() then nil else v2.useCallback(function() v124(v34()); end, { v124 }); local v132 = v19(function(v131) return v131.enableExperienceDetailsPanel(); end); local v133 = l_useLocalization_0({ StatsInfoTitle = "Feature.ExperienceDetails.Body.StatsInfoTitle" }); local v135 = v2.createElement(l_ListTable_0, { cells = v3.map(v122.rows, function(v134) return v2.createElement(v45, { infoName = v134.infoName, infoData = v134.infoData or "", infoIcon = v134.infoIcon, renderTextOverride = (not not v134.infoDataOverride and v120.renderTextOverride) and function() return v134.infoDataOverride(v120.renderTextOverride); end or nil, linkProps = if v134.linkPage or v134.navigateOverride then { eventIngest = v123, rootPlaceId = v122.rootPlaceId, linkPage = v134.linkPage, linkUrl = v134.linkUrl, navigate = v134.navigateOverride or v126, analyticsSubPage = v134.analyticsSubPage } else nil, externalLinkProps = if not not l_GetFFlagEnableDetailsPageCommunityLinks_0() and v134.linkUrl then { linkUrl = v134.linkUrl, openLeaveRobloxAlert = v129, closeAlert = v130, linking = v127, clickCallback = if not l_GetFFlagEnableCommunityLinksClickLogging_0() then nil else v134.linkClickCallback } else nil }); end), automaticSize = Enum.AutomaticSize.Y }); if not v39() or not v132 then return v135; else return v2.createElement(v47, { ref = v121, title = v133.StatsInfoTitle, roundContentCorners = true }, v135); end; end); end;
412
0.812378
1
0.812378
game-dev
MEDIA
0.921649
game-dev
0.9221
1
0.9221
jarjin/SimpleFramework_UGUI
1,473
Assets/uLua/Examples/03_AccessingLuaVariables/AccessingLuaVariables01.cs
using UnityEngine; using System.Collections; using LuaInterface; public class AccessingLuaVariables01 : MonoBehaviour { private string script = @" luanet.load_assembly('UnityEngine') GameObject = luanet.import_type('UnityEngine.GameObject') ParticleSystem = luanet.import_type('UnityEngine.ParticleSystem') particles = {} for i = 1, Objs2Spawn, 1 do local newGameObj = GameObject('NewObj' .. tostring(i)) local ps = newGameObj:AddComponent(luanet.ctype(ParticleSystem)) --local ps = newGameObj:AddComponent('ParticleSystem') PS:Unity5.x已经废弃这种方式,Unity4.x可用-- ps:Stop() table.insert(particles, ps) end var2read = 42 "; // Use this for initialization void Start () { LuaState l = new LuaState(); // Assign to global scope variables as if they're keys in a dictionary (they are really) l["Objs2Spawn"] = 5; l.DoString(script); // Read from the global scope the same way print("Read from lua: " + l["var2read"].ToString()); // Get the lua table as LuaTable object LuaTable particles = (LuaTable)l["particles"]; // Typical foreach over values in table foreach( ParticleSystem ps in particles.Values ) { ps.Play(); } } // Update is called once per frame void Update () { } }
412
0.580668
1
0.580668
game-dev
MEDIA
0.970003
game-dev
0.567346
1
0.567346
Rolisteam/rolisteam
2,494
src/binaries/rcse/controllers/rcseapplicationcontroller.cpp
/*************************************************************************** * Copyright (C) 2022 by Renaud Guezennec * * http://www.rolisteam.org/contact * * * * This software is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "rcseapplicationcontroller.h" #include "common/logcategory.h" RcseApplicationController::RcseApplicationController(QObject* parent) : AbstractApplicationController(parent) {} void RcseApplicationController::msgToGM(const QString& msg, const QString& characterId) { qCInfo(RcseCat) << "Sent message:" << msg << "to GM" << characterId; } void RcseApplicationController::msgToAll(const QString& msg, const QString& characterId) { qCInfo(RcseCat) << "Sent message:" << msg << "to All" << characterId; } void RcseApplicationController::rollDice(const QString& cmd, const QString& characterId, bool gmOnly) { auto f= [](bool b, const QString& yes, const QString& no) { return b ? yes : no; }; qCInfo(RcseCat) << "Roll dice command:" << cmd << " to " << f(gmOnly, tr("only the GM"), tr("All")) << characterId; } QString RcseApplicationController::characterId() const { return "TestPersonId"; } void RcseApplicationController::setCharacterId(const QString& newCharacterId) { Q_UNUSED(newCharacterId) }
412
0.876483
1
0.876483
game-dev
MEDIA
0.417557
game-dev,desktop-app
0.717528
1
0.717528
HHSmithy/PokerHandHistoryParser
1,297
HandHistories.Objects/GameDescription/PokerFormatUtils.cs
using System.Text; using System.Linq.Expressions; using System.Linq; using System.Collections.Generic; using System; namespace HandHistories.Objects.GameDescription { public static class PokerFormatUtils { public static string GetDisplayName(PokerFormat pokerFormat) { switch (pokerFormat) { case PokerFormat.CashGame: return "Cash Game"; default: return pokerFormat.ToString(); } } public static PokerFormat ParseFormatName(string pokerformat) { switch (pokerformat.ToLower()) { case "cash game": case "cashgame": case "cg": case "cash": return PokerFormat.CashGame; case "sng": case "sitandgo": case "sit and go": case "sitngo": case "sit&go": return PokerFormat.SitAndGo; case "mtt": case "multitabletournament": case "multi table tournament": return PokerFormat.MultiTableTournament; } return PokerFormat.Unknown; } } }
412
0.610393
1
0.610393
game-dev
MEDIA
0.81643
game-dev
0.781121
1
0.781121
Dimbreath/AzurLaneData
1,793
ja-JP/mod/battle/data/environment/battleenvironmentunit.lua
ys = ys or {} slot0 = ys slot1 = slot0.Battle.BattleConst slot2 = slot0.Battle.BattleConfig slot3 = slot0.Battle.BattleDataFunction slot4 = class("BattleEnvironmentUnit") slot0.Battle.BattleEnvironmentUnit = slot4 slot4.__name = "BattleEnvironmentUnit" function slot4.Ctor(slot0, slot1, slot2) uv0.EventDispatcher.AttachEventDispatcher(slot0) slot0._uid = slot1 end function slot4.ConfigCallback(slot0, slot1) slot0._callback = slot1 end function slot4.GetUniqueID(slot0) return slot0._uid end function slot4.SetTemplate(slot0, slot1) slot0._template = slot1 slot0:initBehaviours() end function slot4.SetAOEData(slot0, slot1) slot0._expireTimeStamp = pg.TimeMgr.GetInstance():GetCombatTime() + slot0._template.life_time slot0._aoeData = slot1 end function slot4.GetAOEData(slot0) return slot0._aoeData end function slot4.GetBehaviours(slot0) return slot0._behaviours end function slot4.GetTemplate(slot0) return slot0._template end function slot4.UpdateFrequentlyCollide(slot0, slot1) for slot5, slot6 in ipairs(slot0._behaviours) do slot6:UpdateCollideUnitList(slot1) end end function slot4.Update(slot0) for slot4, slot5 in ipairs(slot0._behaviours) do slot5:OnUpdate() end end function slot4.IsExpire(slot0, slot1) return slot0._expireTimeStamp < slot1 end function slot4.Dispose(slot0) if slot0._callback then slot0._callback() end for slot4, slot5 in ipairs(slot0._behaviours) do slot5:Dispose() end end function slot4.initBehaviours(slot0) slot0._behaviours = {} for slot6, slot7 in ipairs(uv0.GetEnvironmentBehaviour(slot0._template.behaviours).behaviour_list) do slot8 = uv1.Battle.BattleEnvironmentBehaviour.CreateBehaviour(slot7) slot8:SetUnitRef(slot0) slot8:SetTemplate(slot7) table.insert(slot0._behaviours, slot8) end end
412
0.536975
1
0.536975
game-dev
MEDIA
0.960639
game-dev
0.875306
1
0.875306
bastianleicht/badlion-src
4,409
com/mojang/realmsclient/gui/screens/RealmsBackupInfoScreen.java
package com.mojang.realmsclient.gui.screens; import com.mojang.realmsclient.dto.Backup; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import net.minecraft.realms.Realms; import net.minecraft.realms.RealmsButton; import net.minecraft.realms.RealmsScreen; import net.minecraft.realms.RealmsSimpleScrolledSelectionList; import net.minecraft.realms.Tezzelator; import org.lwjgl.input.Keyboard; public class RealmsBackupInfoScreen extends RealmsScreen { private final RealmsScreen lastScreen; private final int BUTTON_BACK_ID = 0; private final Backup backup; private List keys = new ArrayList(); private RealmsBackupInfoScreen.BackupInfoList backupInfoList; String[] difficulties = new String[]{getLocalizedString("options.difficulty.peaceful"), getLocalizedString("options.difficulty.easy"), getLocalizedString("options.difficulty.normal"), getLocalizedString("options.difficulty.hard")}; String[] gameModes = new String[]{getLocalizedString("selectWorld.gameMode.survival"), getLocalizedString("selectWorld.gameMode.creative"), getLocalizedString("selectWorld.gameMode.adventure")}; public RealmsBackupInfoScreen(RealmsScreen lastScreen, Backup backup) { this.lastScreen = lastScreen; this.backup = backup; if(backup.changeList != null) { for(Entry<String, String> entry : backup.changeList.entrySet()) { this.keys.add(entry.getKey()); } } } public void mouseEvent() { super.mouseEvent(); this.backupInfoList.mouseEvent(); } public void tick() { } public void init() { Keyboard.enableRepeatEvents(true); this.buttonsAdd(newButton(0, this.width() / 2 - 100, this.height() / 4 + 120 + 24, getLocalizedString("gui.back"))); this.backupInfoList = new RealmsBackupInfoScreen.BackupInfoList(); } public void removed() { Keyboard.enableRepeatEvents(false); } public void buttonClicked(RealmsButton button) { if(button.active()) { if(button.id() == 0) { Realms.setScreen(this.lastScreen); } } } public void keyPressed(char ch, int eventKey) { if(eventKey == 1) { Realms.setScreen(this.lastScreen); } } public void render(int xm, int ym, float a) { this.renderBackground(); this.drawCenteredString("Changes from last backup", this.width() / 2, 10, 16777215); this.backupInfoList.render(xm, ym, a); super.render(xm, ym, a); } private String checkForSpecificMetadata(String key, String value) { String k = key.toLowerCase(); return k.contains("game") && k.contains("mode")?this.gameModeMetadata(value):(k.contains("game") && k.contains("difficulty")?this.gameDifficultyMetadata(value):value); } private String gameDifficultyMetadata(String value) { try { return this.difficulties[Integer.parseInt(value)]; } catch (Exception var3) { return "UNKNOWN"; } } private String gameModeMetadata(String value) { try { return this.gameModes[Integer.parseInt(value)]; } catch (Exception var3) { return "UNKNOWN"; } } private class BackupInfoList extends RealmsSimpleScrolledSelectionList { public BackupInfoList() { super(RealmsBackupInfoScreen.this.width(), RealmsBackupInfoScreen.this.height(), 32, RealmsBackupInfoScreen.this.height() - 64, 36); } public int getItemCount() { return RealmsBackupInfoScreen.this.backup.changeList.size(); } public void selectItem(int item, boolean doubleClick, int xMouse, int yMouse) { } public boolean isSelectedItem(int item) { return false; } public int getMaxPosition() { return this.getItemCount() * 36; } public void renderBackground() { } protected void renderItem(int i, int x, int y, int h, Tezzelator t, int mouseX, int mouseY) { String key = (String)RealmsBackupInfoScreen.this.keys.get(i); RealmsBackupInfoScreen.this.drawString(key, this.width() / 2 - 40, y, 10526880); String metadataValue = (String)RealmsBackupInfoScreen.this.backup.changeList.get(key); RealmsBackupInfoScreen.this.drawString(RealmsBackupInfoScreen.this.checkForSpecificMetadata(key, metadataValue), this.width() / 2 - 40, y + 12, 16777215); } } }
412
0.966852
1
0.966852
game-dev
MEDIA
0.967362
game-dev
0.999178
1
0.999178
chaldea-center/chaldea
33,179
lib/app/modules/faker/state.dart
import 'dart:math'; import 'package:flutter_easyloading/flutter_easyloading.dart'; import 'package:wakelock_plus/wakelock_plus.dart'; import 'package:chaldea/app/api/atlas.dart'; import 'package:chaldea/app/api/cache.dart' show kExpireCacheOnly; import 'package:chaldea/app/app.dart'; import 'package:chaldea/app/modules/master_mission/solver/scheme.dart'; import 'package:chaldea/app/routes/delegate.dart'; import 'package:chaldea/generated/l10n.dart'; import 'package:chaldea/models/faker/cn/agent.dart'; import 'package:chaldea/models/faker/jp/agent.dart'; import 'package:chaldea/models/faker/shared/agent.dart'; import 'package:chaldea/models/faker/shared/network.dart'; import 'package:chaldea/models/gamedata/toplogin.dart'; import 'package:chaldea/models/models.dart'; import 'package:chaldea/packages/logger.dart'; import 'package:chaldea/utils/utils.dart'; import 'package:chaldea/widgets/widgets.dart'; import '../master_mission/solver/solver.dart'; import '_shared/menu_button.dart'; import 'history.dart'; part 'runtime/random_mission.dart'; part 'runtime/gacha.dart'; class FakerRuntime { static final Map<AutoLoginData, FakerRuntime> runtimes = {}; static final Set<Object> _awakeTasks = {}; final FakerAgent agent; final _FakerGameData gameData; FakerRuntime._(this.agent) : gameData = _FakerGameData(agent.user.region); // runtime data final runningTask = ValueNotifier<bool>(false); final activeToast = ValueNotifier<String?>(null); // stats - battle final totalRewards = <int, int>{}; final totalDropStat = _DropStatData(); final curLoopDropStat = _DropStatData(); // stats - gacha final gachaResultStat = _GachaDrawStatData(); final randomMissionStat = RandomMissionLoopStat(); // common late final mstData = agent.network.mstData; Region get region => agent.user.region; AutoBattleOptions get battleOption => agent.user.curBattleOption; final Map<State, bool> _dependencies = {}; // <state, isRoot> BuildContext? get context => _dependencies.keys.firstWhereOrNull((e) => e.mounted)?.context; bool get mounted => context != null; bool get hasMultiRoots => _dependencies.values.where((e) => e).length > 1; void addDependency(State s) { if (!_dependencies.containsKey(s)) _dependencies[s] = false; } void removeDependency(State s) { _dependencies.remove(s); } void update() async { await null; // in case called during parent build? for (final s in _dependencies.keys) { if (s.mounted) { // ignore: invalid_use_of_protected_member s.setState(() {}); } } } // builders void displayToast(String? msg, {double? progress}) { activeToast.value = msg; if (db.settings.fakerSettings.showProgressToast) { if (progress == null) { EasyLoading.show(status: msg); } else { EasyLoading.showProgress(progress, status: msg); } } } void dismissToast() { activeToast.value = null; EasyLoading.dismiss(); } Future<T?> showLocalDialog<T>(Widget child, {bool barrierDismissible = true}) async { BuildContext? ctx; for (final state in _dependencies.keys) { if (state.mounted && AppRouter.of(state.context) == router) { ctx = state.context; } } if (ctx == null) { for (final state in _dependencies.keys) { if (state.mounted) { ctx = state.context; } } } if (ctx == null) return null; return child.showDialog(ctx, barrierDismissible: barrierDismissible); } Widget buildHistoryButton(BuildContext context) { return IconButton( onPressed: () { router.pushPage(FakerHistoryViewer(agent: agent)); }, icon: const Icon(Icons.history), ); } Widget buildMenuButton(BuildContext context) { return IconButton( onPressed: () { router.showDialog(builder: (context) => FakerMenuButton(runtime: this)); }, icon: Icon(Icons.grid_view_rounded), ); } Widget buildCircularProgress({ required BuildContext context, double size = 16, bool showElapsed = false, Color? activeColor, Color? inactiveColor, EdgeInsetsGeometry? padding, }) { return ValueListenableBuilder( valueListenable: runningTask, builder: (context, running, _) { double? value; if (running) { final offstageParent = context.findAncestorWidgetOfExactType<Offstage>(); if (offstageParent != null && offstageParent.offstage) { value = 0.5; } } else { value = 1.0; } Widget child = ConstrainedBox( constraints: BoxConstraints(maxWidth: size, maxHeight: size), child: CircularProgressIndicator( value: value, color: running ? (activeColor ?? Colors.red) : (inactiveColor ?? Colors.green), ), ); if (showElapsed) { child = Stack( alignment: Alignment.center, children: [ child, if (running) ConstrainedBox( constraints: BoxConstraints(maxWidth: size, maxHeight: size), child: TimerUpdate( builder: (context, t) { final startedAt = agent.network.lastTaskStartedAt; final dt = min(99, t.timestamp - startedAt); if (startedAt <= 0 || dt < 0) return const SizedBox.shrink(); return Text(dt.toString(), style: TextStyle(fontSize: 10), textAlign: TextAlign.center); }, ), ), ], ); } if (padding != null) child = Padding(padding: padding, child: child); return child; }, ); } // init static Future<FakerRuntime> init(AutoLoginData user, State state) async { final top = (await showEasyLoading(AtlasApi.gametopsRaw))?.of(user.region); if (top == null) { throw SilentException('fetch game data failed'); } if (!state.mounted) { throw SilentException('Context already disposed'); } FakerRuntime runtime = runtimes.putIfAbsent(user, () { final FakerAgent agent = switch (user) { AutoLoginDataJP() => FakerAgentJP.s(gameTop: top, user: user), AutoLoginDataCN() => FakerAgentCN.s(gameTop: top, user: user), }; return FakerRuntime._(agent); }); runtime.agent.network.addListener(runtime.update); runtime._dependencies[state] = true; return runtime; } Future<void> loadInitData() async { await gameData.init(gameTop: agent.network.gameTop); update(); } // task void lockTask(VoidCallback callback) { if (runningTask.value) { showLocalDialog( SimpleConfirmDialog( title: Text(S.current.error), content: const Text("task is till running"), showCancel: false, ), ); return; } callback(); update(); } Future<void> runTask(Future Function() task, {bool check = true}) async { if (check && runningTask.value) { showLocalDialog( SimpleConfirmDialog( title: Text(S.current.error), content: const Text("previous task is till running"), showCancel: false, ), ); return; } try { if (isBuildingWidget) { await null; } if (check) runningTask.value = true; displayToast('running task...'); update(); await task(); dismissToast(); } catch (e, s) { logger.e('task failed', e, s); await Future.delayed(const Duration(milliseconds: 200)); if (mounted) { dismissToast(); showLocalDialog( SimpleConfirmDialog( title: Text(S.current.error), scrollable: true, content: Text(e is SilentException ? e.message.toString() : e.toString()), showCancel: false, ), barrierDismissible: false, ); } else { EasyLoading.showError(e.toString()); } } finally { if (check) runningTask.value = false; } update(); } Future<T> withWakeLock<T>(Object tag, Future<T> Function() task) async { try { WakelockPlus.enable(); _awakeTasks.add(tag); return await task(); } finally { _awakeTasks.remove(tag); if (_awakeTasks.isEmpty) { WakelockPlus.disable(); } } } // agents Future<void> startLoop({bool dialog = true}) async { if (agent.curBattle != null) { throw SilentException('last battle not finished'); } final battleOption = this.battleOption; if (battleOption.loopCount <= 0) { throw SilentException('loop count (${battleOption.loopCount}) must >0'); } // if (battleOption.targetDrops.values.any((v) => v < 0)) { // throw SilentException('loop target drop num must >=0 (0=always)'); // } if (battleOption.winTargetItemNum.values.any((v) => v <= 0)) { throw SilentException('win target drop num must >0'); } if (battleOption.recoverIds.isNotEmpty && battleOption.waitApRecover) { throw SilentException('Do not turn on both apple recover and wait AP recover'); } final questPhaseEntity = await AtlasApi.questPhase( battleOption.questId, battleOption.questPhase, region: agent.user.region, ); if (questPhaseEntity == null) { throw SilentException('quest not found'); } if (battleOption.loopCount > 1 && !(questPhaseEntity.afterClear == QuestAfterClearType.repeatLast && battleOption.questPhase == questPhaseEntity.phases.lastOrNull)) { throw SilentException('Not repeatable quest or phase'); } final now = DateTime.now().timestamp; if (questPhaseEntity.openedAt > now || questPhaseEntity.closedAt < now) { throw SilentException('quest not open'); } if (battleOption.winTargetItemNum.isNotEmpty && !questPhaseEntity.flags.contains(QuestFlag.actConsumeBattleWin)) { throw SilentException('Win target drops should be used only if Quest has flag actConsumeBattleWin'); } final shouldUseEventDeck = db.gameData.others.shouldUseEventDeck(questPhaseEntity.id); if (battleOption.useEventDeck != null && battleOption.useEventDeck != shouldUseEventDeck) { throw SilentException('This quest should set "Use Event Deck"=$shouldUseEventDeck'); } int finishedCount = 0, totalCount = battleOption.loopCount; List<int> elapseSeconds = []; curLoopDropStat.reset(); agent.network.lastTaskStartedAt = 0; displayToast('Battle $finishedCount/$totalCount', progress: finishedCount / totalCount); while (finishedCount < totalCount) { _checkStop(); checkSvtKeep(); if (battleOption.stopIfBondLimit) { _checkFriendship(battleOption, questPhaseEntity); } final int startTime = DateTime.now().timestamp; final msg = 'Battle ${finishedCount + 1}/$totalCount, ${Maths.mean(elapseSeconds).round()}s/${(Maths.sum(elapseSeconds) / 60).toStringAsFixed(1)}m'; logger.t(msg); displayToast(msg, progress: (finishedCount + 0.5) / totalCount); await _ensureEnoughApItem(quest: questPhaseEntity, option: battleOption); update(); FResponse setupResp; try { setupResp = await agent.battleSetupWithOptions(battleOption); } on NidCheckException catch (e, s) { if (e.nid == 'battle_setup' && e.detail?.resCode == '99' && e.detail?.fail?['errorType'] == 0) { logger.e('battle setup failed with nid check, retry', e, s); await Future.delayed(Duration(seconds: 10)); setupResp = await agent.battleSetupWithOptions(battleOption); } else { rethrow; } } update(); FResponse resultResp; if (setupResp.data.mstData.battles.isEmpty) { if (setupResp.request.normKey.contains('scenario')) { // do nothing resultResp = setupResp; } else { throw SilentException('[${setupResp.request.key}] battle data not found'); } } else { final battleEntity = setupResp.data.mstData.battles.single; final curBattleDrops = battleEntity.battleInfo?.getTotalDrops() ?? {}; logger.t('battle id: ${battleEntity.id}'); bool shouldRetire = false; if (battleOption.winTargetItemNum.isNotEmpty) { shouldRetire = true; for (final (itemId, targetNum) in battleOption.winTargetItemNum.items) { if ((curBattleDrops[itemId] ?? 0) >= targetNum) { shouldRetire = false; break; } } } if (questPhaseEntity.flags.contains(QuestFlag.raid)) { await agent.battleTurn(battleId: battleEntity.id); } if (shouldRetire) { resultResp = await agent.battleResultWithOptions( battleEntity: battleEntity, resultType: BattleResultType.cancel, actionLogs: "", sendDelay: const Duration(seconds: 1), ); } else { final delay = battleOption.battleDuration ?? (agent.network.gameTop.region == Region.cn ? 40 : 20); resultResp = await agent.battleResultWithOptions( battleEntity: battleEntity, resultType: BattleResultType.win, actionLogs: battleOption.actionLogs, sendDelay: Duration(seconds: delay), ); // if win totalDropStat.totalCount += 1; curLoopDropStat.totalCount += 1; Map<int, int> resultBattleDrops; final lastBattleResultData = agent.lastBattleResultData; if (lastBattleResultData != null && lastBattleResultData.battleId == battleEntity.id) { resultBattleDrops = {}; for (final drop in lastBattleResultData.resultDropInfos) { resultBattleDrops.addNum(drop.objectId, drop.num); } for (final reward in lastBattleResultData.rewardInfos) { totalRewards.addNum(reward.objectId, reward.num); } for (final reward in lastBattleResultData.friendshipRewardInfos) { totalRewards.addNum(reward.objectId, reward.num); } } else { resultBattleDrops = curBattleDrops; logger.t('last battle result data not found, use cur_battle_drops'); } totalDropStat.items.addDict(resultBattleDrops); curLoopDropStat.items.addDict(resultBattleDrops); totalRewards.addDict(resultBattleDrops); // check total drop target of this loop if (battleOption.targetDrops.isNotEmpty) { for (final (itemId, targetNum) in battleOption.targetDrops.items.toList()) { final dropNum = resultBattleDrops[itemId]; if (dropNum == null || dropNum <= 0) continue; battleOption.targetDrops[itemId] = targetNum - dropNum; } final reachedItems = battleOption.targetDrops.keys .where((itemId) => resultBattleDrops.containsKey(itemId) && battleOption.targetDrops[itemId]! <= 0) .toList(); if (reachedItems.isNotEmpty) { throw SilentException( 'Target drop reaches: ${reachedItems.map((e) => GameCardMixin.anyCardItemName(e).l).join(', ')}', ); } } } } final userQuest = mstData.userQuest[questPhaseEntity.id]; if (userQuest != null && userQuest.clearNum == 0 && questPhaseEntity.phases.contains(userQuest.questPhase + 1)) { battleOption.questPhase = userQuest.questPhase + 1; } for (final item in resultResp.data.mstData.userItem) { totalRewards.addNum(item.itemId, 0); } finishedCount += 1; battleOption.loopCount -= 1; elapseSeconds.add(DateTime.now().timestamp - startTime); update(); if (questPhaseEntity.flags.contains(QuestFlag.raid) && finishedCount % 5 == 1) { // update raid info await agent.homeTop(); } update(); await Future.delayed(const Duration(milliseconds: 100)); if (battleOption.stopIfBondLimit) { _checkFriendship(battleOption, questPhaseEntity); } } logger.t('finished all $finishedCount battles'); if (dialog) { showLocalDialog( SimpleConfirmDialog(title: const Text('Finished'), content: Text('$finishedCount battles'), showCancel: false), barrierDismissible: false, ); } } Future<void> seedWait(final int maxBuyCount) async { int boughtCount = 0; while (boughtCount < maxBuyCount) { const int apUnit = 40, seedUnit = 1; final apCount = mstData.user?.calCurAp() ?? 0; final seedCount = mstData.getItemOrSvtNum(Items.blueSaplingId); if (seedCount <= 0) { throw SilentException('no Blue Sapling left'); } int buyCount = Maths.min([maxBuyCount, apCount ~/ apUnit, seedCount ~/ seedUnit]); if (buyCount > 0) { await agent.terminalApSeedExchange(buyCount); boughtCount += buyCount; } update(); displayToast('Seed $boughtCount/$maxBuyCount - waiting...'); await Future.delayed(const Duration(minutes: 1)); _checkStop(); } } Future<void> svtEquipCombine([int count = 1]) async { final gachaOption = agent.user.gacha; displayToast('Combine Craft Essence ...'); while (count > 0) { final targetCEs = mstData.userSvt.where((userSvt) { final ce = db.gameData.craftEssencesById[userSvt.svtId]; if (ce == null) return false; if (!userSvt.locked) return false; final maxLv = userSvt.maxLv; if (maxLv == null || userSvt.lv >= maxLv - 1) return false; if (gachaOption.ceEnhanceBaseUserSvtIds.contains(userSvt.id)) return true; if (gachaOption.ceEnhanceBaseSvtIds.contains(userSvt.svtId)) { return userSvt.limitCount == 4; } return false; }).toList(); if (targetCEs.isEmpty) { throw SilentException('No valid Target Craft Essence'); } targetCEs.sort2((e) => e.lv); final targetCE = targetCEs.first; List<UserServantEntity> combineMaterialCEs = mstData.userSvt.where((userSvt) { final ce = db.gameData.craftEssencesById[userSvt.svtId]; if (ce == null || userSvt.locked || userSvt.lv != 1) return false; final bool isExp = ce.flags.contains(SvtFlag.svtEquipExp); if (ce.rarity > 4) { return false; } else if (ce.rarity == 4) { return gachaOption.feedExp4 && isExp; } else if (ce.rarity == 3) { if (isExp) { return gachaOption.feedExp3; } return ce.obtain == CEObtain.permanent; } else { return true; } }).toList(); combineMaterialCEs.sort2((e) => -e.createdAt); if (combineMaterialCEs.isEmpty) { update(); return; } combineMaterialCEs = combineMaterialCEs.take(20).toList(); await agent.servantEquipCombine( baseUserSvtId: targetCE.id, materialSvtIds: combineMaterialCEs.map((e) => e.id).toList(), ); count -= 1; gachaResultStat.lastEnhanceBaseCE = targetCE; gachaResultStat.lastEnhanceMaterialCEs = combineMaterialCEs.toList(); gachaResultStat.lastEnhanceMaterialCEs.sort( (a, b) => CraftFilterData.compare(a.dbCE, b.dbCE, keys: const [CraftCompare.rarity], reversed: const [true]), ); update(); } } // box gacha Future<void> boxGachaDraw({required EventLottery lottery, required int num, required Ref<int> loopCount}) async { final boxGachaId = lottery.id; while (loopCount.value > 0) { final userBoxGacha = mstData.userBoxGacha[boxGachaId]; if (userBoxGacha == null) throw SilentException('BoxGacha $boxGachaId not in user data'); final maxNum = lottery.getMaxNum(userBoxGacha.boxIndex); if (userBoxGacha.isReset && userBoxGacha.drawNum == maxNum) { await agent.boxGachaReset(gachaId: boxGachaId); update(); continue; } // if (userBoxGacha.isReset) throw SilentException('isReset=true, not tested'); num = min(num, maxNum - userBoxGacha.drawNum); if (userBoxGacha.resetNum <= 10 && num > 10) { throw SilentException('Cannot draw $num times in first 10 lotteries'); } final ownItemCount = mstData.userItem[lottery.cost.itemId]?.num ?? 0; if (ownItemCount < lottery.cost.amount) { throw SilentException('Item noy enough: $ownItemCount'); } num = min(num, ownItemCount ~/ lottery.cost.amount); if (num <= 0 || num > 100) { throw SilentException('Invalid draw num: $num'); } if (mstData.userPresentBox.length >= (gameData.timerData.constants.maxPresentBoxNum - 10)) { throw SilentException('Present Box Full'); } await agent.boxGachaDraw(gachaId: boxGachaId, num: num); loopCount.value -= 1; update(); } } // Future<void> svtCombine({int? loopCount}) async { final options = agent.user.svtCombine; while ((loopCount ?? options.loopCount) > 0) { final UserServantEntity? baseUserSvt = mstData.userSvt[options.baseUserSvtId]; if (baseUserSvt == null) throw SilentException('user svt ${options.baseUserSvtId} not found'); final baseSvt = baseUserSvt.dbSvt; if (baseSvt == null) throw SilentException('svt ${baseUserSvt.svtId} not found'); if (baseSvt.rarity == 0 || baseSvt.type != SvtType.normal || baseSvt.collectionNo == 0) { throw SilentException('Invalid base svt'); } final maxLv = baseUserSvt.maxLv; if (maxLv == null || baseUserSvt.lv >= maxLv) { throw SilentException('Lv.${baseUserSvt.lv}>=maxLv $maxLv'); } List<UserServantEntity> candidateMaterialSvts = mstData.userSvt.where((userSvt) { final svt = userSvt.dbEntity; if (svt == null || svt.type != SvtType.combineMaterial) return false; if (userSvt.locked || userSvt.lv != 1) return false; if (!options.svtMaterialRarities.contains(svt.rarity)) return false; return true; }).toList(); candidateMaterialSvts.sort2((e) => e.dbEntity?.rarity ?? 999); List<int> materialSvtIds = []; final curLvExp = baseSvt.expGrowth.getOrNull(baseUserSvt.lv - 1), nextAsenExp = baseSvt.expGrowth.getOrNull((baseUserSvt.maxLv ?? baseSvt.lvMax) - 1); if (curLvExp == null || nextAsenExp == null || curLvExp >= nextAsenExp || curLvExp > baseUserSvt.exp) { throw SilentException('no valid exp data found: $curLvExp <= ${baseUserSvt.exp} <= $nextAsenExp'); } int needExp = nextAsenExp - baseUserSvt.exp; int totalGetExp = 0, totalUseQp = 0; for (final userSvt in candidateMaterialSvts) { final svt = userSvt.dbEntity!; final sameClass = svt.classId == SvtClass.ALL.value || svt.classId == baseSvt.classId; int getExp = (1000 * (pow(3, svt.rarity - 1)) * (sameClass ? 1.2 : 1)).round(); int useQp = ((100 + (baseUserSvt.lv - 1) * 30) * ([1, 1.5, 2, 4, 6][baseSvt.rarity - 1])).round(); if (totalGetExp >= needExp || materialSvtIds.length >= options.maxMaterialCount) break; if (options.doubleExp) getExp *= 2; totalGetExp += getExp; totalUseQp += useQp; materialSvtIds.add(userSvt.id); } if (materialSvtIds.isEmpty) { throw SilentException('No valid 种火 found'); } await agent.servantCombine( baseUserSvtId: options.baseUserSvtId, materialSvtIds: materialSvtIds, useQp: totalUseQp, getExp: totalGetExp, ); if (loopCount != null) { loopCount -= 1; } else { options.loopCount -= 1; } update(); } } bool checkSvtLvExceed(int userSvtId) { final baseUserSvt = mstData.userSvt[userSvtId]; final svt = baseUserSvt?.dbSvt; if (baseUserSvt == null || svt == null) return false; if (baseUserSvt.lv < svt.lvMax || baseUserSvt.lv >= 120 || baseUserSvt.lv != baseUserSvt.maxLv) return false; if (mstData.getItemOrSvtNum(Items.grailId) < 1) return false; if (baseUserSvt.lv >= 100 && (mstData.userSvtCoin[baseUserSvt.svtId]?.num ?? 0) < 30) return false; return true; } // helpers void _checkStop() { if (agent.network.stopFlag) { agent.network.stopFlag = false; throw SilentException('Manual Stop'); } } void checkSvtKeep() { final counts = mstData.countSvtKeep(); final user = mstData.user!; if (counts.svtCount >= user.svtKeep) { throw SilentException('${S.current.servant}: ${counts.svtCount}>=${user.svtKeep}'); } if (counts.svtEquipCount >= user.svtEquipKeep) { throw SilentException('${S.current.craft_essence}: ${counts.svtEquipCount}>=${user.svtEquipKeep}'); } if (counts.ccCount >= gameData.timerData.constants.maxUserCommandCode) { throw SilentException( '${S.current.command_code}: ${counts.ccCount}>=${gameData.timerData.constants.maxUserCommandCode}', ); } } void _checkFriendship(AutoBattleOptions option, QuestPhase questPhase) { final deck = questPhase.isUseUserEventDeck() ? mstData.userEventDeck[UserEventDeckEntity.createPK( questPhase.logicEvent?.id ?? 0, questPhase.extraDetail?.useEventDeckNo ?? 1, )] : mstData.userDeck[battleOption.deckId]; final svts = deck?.deckInfo?.svts ?? []; for (final svt in svts) { if (svt.userSvtId > 0) { final userSvt = mstData.userSvt[svt.userSvtId]; if (userSvt == null) { throw SilentException('UserSvt ${svt.userSvtId} not found'); } final dbSvt = db.gameData.servantsById[userSvt.svtId]; if (dbSvt == null) { throw SilentException('Unknown Servant ID ${userSvt.svtId}'); } final svtCollection = mstData.userSvtCollection[userSvt.svtId]; if (svtCollection == null) { throw SilentException('UserServantCollection ${userSvt.svtId} not found'); } if (svtCollection.friendshipRank >= svtCollection.maxFriendshipRank) { throw SilentException( 'Svt No.${dbSvt.collectionNo} ${dbSvt.lName.l} reaches max bond Lv.${svtCollection.maxFriendshipRank}', ); } } } } Future<void> _ensureEnoughApItem({required QuestPhase quest, required AutoBattleOptions option}) async { if (quest.consumeType.useItem) { for (final item in quest.consumeItem) { final own = mstData.getItemOrSvtNum(item.itemId); if (own < item.amount) { throw SilentException('Consume Item not enough: ${item.itemId}: $own<${item.amount}'); } } } if (quest.consumeType.useAp) { final apConsume = option.isApHalf ? quest.consume ~/ 2 : quest.consume; if (mstData.user!.calCurAp() >= apConsume) { return; } for (final recoverId in option.recoverIds) { final recover = mstRecovers[recoverId]; if (recover == null) continue; int dt = mstData.user!.actRecoverAt - DateTime.now().timestamp; if ((recover.id == 1 || recover.id == 2) && option.waitApRecoverGold && dt > 300 && dt % 300 < 240) { final waitUntil = DateTime.now().timestamp + dt % 300 + 2; while (true) { final now = DateTime.now().timestamp; if (now >= waitUntil) break; displayToast('Wait ${waitUntil - now} seconds...'); await Future.delayed(Duration(seconds: min(5, waitUntil - now))); _checkStop(); } } if (recover.recoverType == RecoverType.stone && mstData.user!.stone > 0) { await agent.shopPurchaseByStone(id: recover.targetId, num: 1); break; } else if (recover.recoverType == RecoverType.item) { final item = db.gameData.items[recover.targetId]; if (item == null) continue; if (item.type == ItemType.apAdd) { final count = ((apConsume - mstData.user!.calCurAp()) / item.value).ceil(); if (count > 0 && count < mstData.getItemOrSvtNum(item.id)) { await agent.itemRecover(recoverId: recoverId, num: count); break; } } else if (item.type == ItemType.apRecover) { final count = ((apConsume - mstData.user!.calCurAp()) / (item.value / 1000 * mstData.user!.actMax).ceil()) .ceil(); if (count > 0 && count <= mstData.getItemOrSvtNum(item.id)) { await agent.itemRecover(recoverId: recoverId, num: count); break; } } } else { continue; } } if (mstData.user!.calCurAp() >= apConsume) { return; } if (option.waitApRecover) { while (mstData.user!.calCurAp() < apConsume) { update(); displayToast('Battle - waiting AP recover...'); await Future.delayed(const Duration(minutes: 1)); _checkStop(); } return; } throw SilentException('AP not enough: ${mstData.user!.calCurAp()}<$apConsume'); } } } class _FakerGameData { final Region region; _FakerGameData(this.region); GameTimerData timerData = GameTimerData(); Map<int, Item> get teapots { final now = DateTime.now().timestamp; return { for (final item in timerData.items) if (item.type == ItemType.friendshipUpItem && item.endedAt > now) item.id: item, }; } Future<void> init({GameTop? gameTop, bool refresh = false}) async { GameTimerData? _timerData; if (gameTop != null && !refresh) { final localTimerData = await AtlasApi.timerData(region, expireAfter: kExpireCacheOnly); if (localTimerData != null && localTimerData.updatedAt > DateTime.now().timestamp - 3 * kSecsPerDay) { if (localTimerData.hash != null && localTimerData.hash == gameTop.hash) { _timerData = localTimerData; } } } _timerData ??= await AtlasApi.timerData(region, expireAfter: refresh ? Duration.zero : null); timerData = _timerData ?? timerData; } } class _DropStatData { int totalCount = 0; Map<int, int> items = {}; // Map<int, int> groups = {}; void reset() { totalCount = 0; items.clear(); } } class _GachaDrawStatData { int totalCount = 0; Map<int, int> servants = {}; Map<int, int> coins = {}; //<svtId, num> List<GachaInfos> lastDrawResult = []; UserServantEntity? lastEnhanceBaseCE; List<UserServantEntity> lastEnhanceMaterialCEs = []; List<UserServantEntity> lastSellServants = []; void reset() { totalCount = 0; servants.clear(); coins.clear(); lastDrawResult = []; lastEnhanceBaseCE = null; lastEnhanceMaterialCEs = []; lastSellServants = []; } } class RandomMissionLoopStat { // List<int> randomMissionIds = []; Map<int, EventMission> eventMissions = {}; List<int> itemIds = []; List<Quest> cqs0 = []; List<Quest> fqs0 = []; List<QuestPhase> cqs = []; List<QuestPhase> fqs = []; BattleResultData? lastBattleResultData; Set<int> lastAddedMissionIds = {}; RandomMissionOption curLoopData = RandomMissionOption(); Future<void> load(FakerRuntime runtime) async { Event? event; final eventMap = {for (final e in runtime.gameData.timerData.events) e.id: e}; final now = DateTime.now().timestamp; for (final userRandomMission in runtime.mstData.userEventRandomMission) { final _event = eventMap[userRandomMission.missionTargetId]; if (_event != null && _event.startedAt < now && _event.endedAt > now) { event = _event; break; } } if (event == null) return; final maxRank = Maths.max(event.randomMissions.map((e) => e.condNum), 0); randomMissionIds = event.randomMissions.where((e) => e.condNum == maxRank).map((e) => e.missionId).toList(); randomMissionIds.sort(); final missionMap = {for (final m in event.missions) m.id: m}; eventMissions = {}; for (final id in randomMissionIds) { final mission = eventMissions[id] = missionMap[id]!; itemIds.addAll(mission.gifts.map((e) => e.objectId)); } itemIds = itemIds.toSet().toList(); itemIds.sort2((e) => db.gameData.items[e]?.priority ?? 0, reversed: true); final allQuests = db.gameData.wars[event.warIds.firstOrNull]?.quests ?? []; cqs0 = allQuests.where((e) => e.consume == 5 && e.flags.contains(QuestFlag.dropFirstTimeOnly)).toList(); fqs0 = allQuests.where((e) => e.isAnyFree && e.consume > 0).toList(); } } mixin FakerRuntimeStateMixin<T extends StatefulWidget> on State<T> { FakerRuntime get runtime; FakerAgent get agent => runtime.agent; MasterDataManager get mstData => runtime.mstData; @override void initState() { super.initState(); runtime.addDependency(this); } @override void dispose() { super.dispose(); runtime.removeDependency(this); } }
412
0.985417
1
0.985417
game-dev
MEDIA
0.694209
game-dev
0.987736
1
0.987736
Dimbreath/AzurLaneData
4,926
zh-CN/view/main/playerinfomediator.lua
slot0 = class("PlayerInfoMediator", import("..base.ContextMediator")) slot0.CHANGE_NAME = "PlayerInfoMediator:CHANGE_NAME" slot0.CHANGE_PAINT = "PlayerInfoMediator:CHANGE_ICON" slot0.CHANGE_PAINTS = "PlayerInfoMediator:CHANGE_ICONS" slot0.CHANGE_MANIFESTO = "PlayerInfoMediator:CHANGE_MANIFESTO" slot0.GO_BACKYARD = "PlayerInfoMediator:GO_BACKYARD" slot0.GO_COLLECTION = "PlayerInfoMediator:GO_COLLECTION" slot0.CHANGE_SKIN = "PlayerInfoMediator:CHANGE_SKIN" slot0.ON_CHANGE_PLAYER_NAME = "PlayerInfoMediator:ON_CHANGE_PLAYER_NAME" slot0.ON_CHANGE_MEDAL_DISPLAY = "PlayerInfoMediator:ON_CHANGE_MEDAL_DISPLAY" slot0.ON_ATTIRE = "PlayerInfoMediator:ON_ATTIRE" function slot0.register(slot0) slot0:bind(uv0.ON_CHANGE_PLAYER_NAME, function (slot0, slot1) uv0:sendNotification(GAME.CHANGE_PLAYER_NAME, { name = slot1 }) end) slot2 = getProxy(PlayerProxy):getData() slot0.viewComponent:setPlayer(slot2) slot3 = getProxy(BayProxy) slot0.viewComponent:setShipCount(slot3:getShipCount()) slot4 = slot3:getShipById(slot2.character) slot0.shipVO = slot4 slot0.viewComponent:setCurrentFlagship(slot4) slot5 = getProxy(CollectionProxy) slot0.viewComponent:setCollectionRate(slot5:getCollectionRate()) slot0.viewComponent:setTrophyList(slot5:getTrophys()) slot0.viewComponent:setMilitaryExercise(getProxy(MilitaryExerciseProxy):getSeasonInfo()) slot0:bind(uv0.CHANGE_PAINT, function (slot0, slot1) slot2 = {} uv0.contextData.showSelectCharacters = true for slot6, slot7 in ipairs(uv0.viewComponent.player.characters) do if not slot1 or slot7 ~= slot1.id then table.insert(slot2, slot7) end end uv0:sendNotification(GAME.GO_SCENE, SCENE.DOCKYARD, { callbackQuit = true, selectedMax = uv0.viewComponent.secretary_max, hideTagFlags = ShipStatus.TAG_HIDE_ADMIRAL, selectedIds = slot2, ignoredIds = pg.ShipFlagMgr.GetInstance():FilterShips({ isActivityNpc = true }), onSelected = function (slot0, slot1) uv0.contextData.showSelectCharacters = false uv0:sendNotification(GAME.CHANGE_PLAYER_ICON, { characterId = slot0, callback = slot1 }) end }) end) slot0:bind(uv0.CHANGE_PAINTS, function (slot0, slot1) uv0:sendNotification(GAME.CHANGE_PLAYER_ICON, { characterId = slot1 }) end) slot0:bind(uv0.GO_BACKYARD, function (slot0) uv0:sendNotification(GAME.GO_SCENE, SCENE.BACKYARD) end) slot0:bind(uv0.CHANGE_SKIN, function (slot0, slot1) uv0:addSubLayers(Context.New({ mediator = SwichSkinMediator, viewComponent = SwichSkinLayer, data = { shipVO = slot1 } })) end) slot0:bind(uv0.GO_COLLECTION, function (slot0) uv0:sendNotification(GAME.GO_SCENE, SCENE.COLLECTSHIP) end) slot0:bind(uv0.CHANGE_MANIFESTO, function (slot0, slot1) uv0:sendNotification(GAME.CHANGE_PLAYER_MANIFESTO, { manifesto = slot1 }) end) slot0:bind(uv0.ON_ATTIRE, function () uv0:sendNotification(GAME.GO_SCENE, SCENE.ATTIRE) end) slot0.viewComponent:setFleetGearScore(math.floor(getProxy(BayProxy):getBayPowerRooted())) slot0.viewComponent:updateFleetGSView() slot0:bind(uv0.ON_CHANGE_MEDAL_DISPLAY, function (slot0, slot1) uv0:sendNotification(GAME.CHANGE_PLAYER_MEDAL_DISPLAY, { medalList = slot1 }) end) slot0.viewComponent:updateAttireBtn(_.any(getProxy(AttireProxy):needTip(), function (slot0) return slot0 == true end)) if slot0.contextData.showSelectCharacters then slot0.viewComponent:showCharacters() slot0.contextData.showSelectCharacters = false end end function slot0.listNotificationInterests(slot0) return { SetShipSkinCommand.SKIN_UPDATED, PlayerProxy.UPDATED, GAME.CHANGE_PLAYER_ICON_DONE, GAME.CHANGE_PLAYER_NAME_DONE, GAME.CHANGE_PLAYER_MEDAL_DISPLAY_DONE, GAME.CHANGE_PAINT, BayProxy.SHIP_UPDATED, GAME.UPDATE_SKINCONFIG } end function slot0.handleNotification(slot0, slot1) if slot1:getName() == PlayerProxy.UPDATED then slot0.viewComponent:setPlayer(slot1:getBody()) elseif slot2 == SetShipSkinCommand.SKIN_UPDATED then slot0.shipVO = slot3.ship slot0.viewComponent:updateCardByShip(slot3.ship) elseif slot2 == GAME.CHANGE_PLAYER_ICON_DONE then slot0.shipVO = slot3.ship slot0.viewComponent:setCurrentFlagship(slot0.shipVO) slot0.viewComponent:showCharacters() slot0.contextData.shipIdToAdd = nil elseif slot2 == GAME.CHANGE_PLAYER_NAME_DONE then slot0.viewComponent:updatePlayerName() slot0.viewComponent:closeChangePlayerNamePanel() elseif slot2 == GAME.CHANGE_PLAYER_MEDAL_DISPLAY_DONE then slot0.viewComponent:updateMedalDisplay(getProxy(PlayerProxy):getData().displayTrophyList) slot0.viewComponent:closeAddMedalPanel() elseif slot2 == BayProxy.SHIP_UPDATED then if slot3.id == slot0.shipVO.id then slot0.viewComponent:setCurrentFlagship(slot3) end elseif slot2 == GAME.UPDATE_SKINCONFIG and slot3.skinId == slot0.shipVO.skinId then slot0.viewComponent:setCurrentFlagship(slot0.shipVO) end end return slot0
412
0.912524
1
0.912524
game-dev
MEDIA
0.930489
game-dev
0.961957
1
0.961957
qcdong2016/QCEditor
6,145
cocos2d/cocos/editor-support/spine/SkeletonAnimation.h
/****************************************************************************** * Spine Runtimes Software License v2.5 * * Copyright (c) 2013-2016, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable, and * non-transferable license to use, install, execute, and perform the Spine * Runtimes software and derivative works solely for personal or internal * use. Without the written permission of Esoteric Software (see Section 2 of * the Spine Software License Agreement), you may not (a) modify, translate, * adapt, or develop new applications using the Spine Runtimes or otherwise * create derivative works or improvements of the Spine Runtimes or (b) remove, * delete, alter, or obscure any trademarks or any copyright, trademark, patent, * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF * USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ #ifndef SPINE_SKELETONANIMATION_H_ #define SPINE_SKELETONANIMATION_H_ #include "spine/spine.h" #include "spine/SkeletonRenderer.h" #include "cocos2d.h" namespace spine { typedef std::function<void(spTrackEntry* entry)> StartListener; typedef std::function<void(spTrackEntry* entry)> InterruptListener; typedef std::function<void(spTrackEntry* entry)> EndListener; typedef std::function<void(spTrackEntry* entry)> DisposeListener; typedef std::function<void(spTrackEntry* entry)> CompleteListener; typedef std::function<void(spTrackEntry* entry, spEvent* event)> EventListener; /** Draws an animated skeleton, providing an AnimationState for applying one or more animations and queuing animations to be * played later. */ class SkeletonAnimation: public SkeletonRenderer { public: CREATE_FUNC(SkeletonAnimation); static SkeletonAnimation* createWithData (spSkeletonData* skeletonData, bool ownsSkeletonData = false); static SkeletonAnimation* createWithJsonFile (const std::string& skeletonJsonFile, spAtlas* atlas, float scale = 1); static SkeletonAnimation* createWithJsonFile (const std::string& skeletonJsonFile, const std::string& atlasFile, float scale = 1); static SkeletonAnimation* createWithBinaryFile (const std::string& skeletonBinaryFile, spAtlas* atlas, float scale = 1); static SkeletonAnimation* createWithBinaryFile (const std::string& skeletonBinaryFile, const std::string& atlasFile, float scale = 1); // Use createWithJsonFile instead CC_DEPRECATED_ATTRIBUTE static SkeletonAnimation* createWithFile (const std::string& skeletonJsonFile, spAtlas* atlas, float scale = 1) { return SkeletonAnimation::createWithJsonFile(skeletonJsonFile, atlas, scale); } // Use createWithJsonFile instead CC_DEPRECATED_ATTRIBUTE static SkeletonAnimation* createWithFile (const std::string& skeletonJsonFile, const std::string& atlasFile, float scale = 1) { return SkeletonAnimation::createWithJsonFile(skeletonJsonFile, atlasFile, scale); } virtual void update (float deltaTime) override; void setAnimationStateData (spAnimationStateData* stateData); void setMix (const std::string& fromAnimation, const std::string& toAnimation, float duration); spTrackEntry* setAnimation (int trackIndex, const std::string& name, bool loop); spTrackEntry* addAnimation (int trackIndex, const std::string& name, bool loop, float delay = 0); spTrackEntry* setEmptyAnimation (int trackIndex, float mixDuration); void setEmptyAnimations (float mixDuration); spTrackEntry* addEmptyAnimation (int trackIndex, float mixDuration, float delay = 0); spAnimation* findAnimation(const std::string& name) const; spTrackEntry* getCurrent (int trackIndex = 0); void clearTracks (); void clearTrack (int trackIndex = 0); void setStartListener (const StartListener& listener); void setInterruptListener (const InterruptListener& listener); void setEndListener (const EndListener& listener); void setDisposeListener (const DisposeListener& listener); void setCompleteListener (const CompleteListener& listener); void setEventListener (const EventListener& listener); void setTrackStartListener (spTrackEntry* entry, const StartListener& listener); void setTrackInterruptListener (spTrackEntry* entry, const InterruptListener& listener); void setTrackEndListener (spTrackEntry* entry, const EndListener& listener); void setTrackDisposeListener (spTrackEntry* entry, const DisposeListener& listener); void setTrackCompleteListener (spTrackEntry* entry, const CompleteListener& listener); void setTrackEventListener (spTrackEntry* entry, const EventListener& listener); virtual void onAnimationStateEvent (spTrackEntry* entry, spEventType type, spEvent* event); virtual void onTrackEntryEvent (spTrackEntry* entry, spEventType type, spEvent* event); spAnimationState* getState() const; CC_CONSTRUCTOR_ACCESS: SkeletonAnimation (); virtual ~SkeletonAnimation (); virtual void initialize () override; protected: spAnimationState* _state; bool _ownsAnimationStateData; StartListener _startListener; InterruptListener _interruptListener; EndListener _endListener; DisposeListener _disposeListener; CompleteListener _completeListener; EventListener _eventListener; private: typedef SkeletonRenderer super; }; } #endif /* SPINE_SKELETONANIMATION_H_ */
412
0.89753
1
0.89753
game-dev
MEDIA
0.629356
game-dev
0.686181
1
0.686181
wikimedia/limn
1,060
src/util/guid.co
/** * Generate unique IDs. * TODO: generateId, guidFor, and compareIds do not deal with *Globally* unique identifiers, they should be moved elsewhere */ UUID = 0 GUID_KEY = '__id__' OBJ_PREFIX = 'limn' NUMBER_CACHE = {} STRING_CACHE = {} export generateId = (prefix=OBJ_PREFIX) -> id = UUID++ "#prefix#id" export guidFor = (obj) -> # special cases where we don't want to add a key to object return '(undefined)' if obj is void return '(null)' if obj is null # Don't allow prototype changes to String etc. to change the guidFor switch typeof obj case 'number' then return NUMBER_CACHE[obj] or= "nu#obj" case 'string' then return STRING_CACHE[obj] or= "st#{(UUID++)}" case 'boolean' then return if obj then '(true)' else '(false)' return obj[GUID_KEY] if obj[GUID_KEY] return '(Object)' if obj is Object return '(Array)' if obj is Array return obj[GUID_KEY] = "#OBJ_PREFIX#{(UUID++)}" export compareIds = (a, b) -> guidFor(a) is guidFor(b)
412
0.752089
1
0.752089
game-dev
MEDIA
0.494008
game-dev
0.833612
1
0.833612
StarWarsFoundryVTT/StarWarsFFG
30,144
modules/helpers/modifiers.js
import PopoutModifiers from "../popout-modifiers.js"; export default class ModifierHelpers { /** * Calculate total value from embedded items * @param {array} items * @param {string} key */ static getCalculatedValueFromItems(items, key, modtype, includeSource) { // TODO: we are returning 0 from this; it can probably be removed. but we need to validate that it isn't making other changes let total = 0; let checked = false; let sources = []; try { items.forEach((item) => { if (!item) { // don't process null items return; } if (Object.keys(item.system).includes("active") && item.system.active === false) { // there is a mod or something, and it's not active - don't process it return; } if (item.system?.attributes) { const attrsToApply = Object.keys(item.system.attributes) .filter((id) => (item.system.attributes[id].mod === key || item.system.attributes[id].mod === "*") && item.system.attributes[id].modtype === modtype) .map((i) => item.system.attributes[i]); if (item.type === "armour" || item.type === "weapon" || item.type === "itemattachment") { if (item?.system?.equippable?.equipped || item.type === "itemattachment") { if (item.system?.itemmodifier) { total += this.getCalculatedValueFromItems(item.system.itemmodifier, key, modtype); } if (item.system?.itemattachment && item?.system?.equippable?.equipped) { total += this.getCalculatedValueFromItems(item.system.itemattachment, key, modtype); } if (key === "Soak" && item.system?.soak) { sources.push({ modtype, key, name: item.name, value: item.system.soak.adjusted, type: item.type }); total += parseInt(item.system.soak.adjusted, 10); } if ((key === "Defence-Melee" || key === "Defence-Ranged") && item.system?.defence) { // get the highest defense item const shouldUse = items.filter((i) => item.system.defence >= i.system.defence).length >= 0; if (shouldUse) { sources.push({ modtype, key, name: item.name, value: item.system.defence.adjusted, type: item.type }); total += parseInt(item.system.defence.adjusted, 10); } } if (attrsToApply.length > 0) { attrsToApply.forEach((attr) => { if (modtype === "Career Skill" || modtype === "Force Boost") { if (attr.value) { sources.push({ modtype, key, name: item.name, value: true, type: item.type }); checked = true; } } else { sources.push({ modtype, key, name: item.name, value: attr.value, type: item.type }); total += parseInt(attr.value, 10); } }); } } } else if (item.type === "forcepower" || item.type === "specialization" || item.type === "signatureability") { // apply basic force power/specialization modifiers if (attrsToApply.length > 0) { attrsToApply.forEach((attr) => { if (modtype === "Career Skill" || modtype === "Force Boost") { if (attr.value) { sources.push({ modtype, key, name: item.name, value: true, type: item.type }); checked = true; } } else { if ((modtype === "ForcePool" && total === 0) || modtype !== "ForcePool") { sources.push({ modtype, key, name: item.name, value: attr.value, type: item.type }); total += parseInt(attr.value, 10); } } }); } let upgrades; if (item.type === "forcepower" || item.type === "signatureability") { // apply force power upgrades upgrades = Object.keys(item.system.upgrades) .filter((k) => item.system.upgrades[k].islearned) .map((k) => { return { type: "talent", name: `${item.name}: ${item.system.upgrades[k].name}`, system: { attributes: item.system.upgrades[k]?.attributes ? item.system.upgrades[k]?.attributes : {}, ranks: { ranked: false, current: 1, }, }, }; }); } else if (item.type === "specialization") { // apply specialization talent modifiers upgrades = Object.keys(item.system.talents) .filter((k) => item.system.talents[k].islearned) .map((k) => { return { type: "talent", name: `${item.name}: ${item.system.talents[k].name}`, system: { attributes: item.system.talents[k].attributes, ranks: { ranked: item.system.talents[k].isRanked, current: 1, }, }, }; }); } if (modtype === "Career Skill" || modtype === "Force Boost") { if (this.getCalculatedValueFromItems(upgrades, key, modtype)) { sources.push({ modtype, key, name: item.name, value: true, type: item.type }); checked = true; } } else { if (includeSource) { const subValues = this.getCalculatedValueFromItems(upgrades, key, modtype, includeSource); total += subValues.total; sources = sources.concat(subValues.sources); } else { const subValues = this.getCalculatedValueFromItems(upgrades, key, modtype); total += subValues; } } } else { if (attrsToApply.length > 0) { attrsToApply.forEach((attr) => { if (modtype === "Career Skill" || modtype === "Force Boost") { if (attr.value) { sources.push({ modtype, key, name: item.name, value: true, type: item.type }); checked = true; } } else { if (item.type === "talent") { let multiplier = 1; if (item.system.ranks.ranked) { multiplier = item.system.ranks.current; } sources.push({ modtype, key, name: item.name, value: attr.value * multiplier, type: item.type }); total += parseInt(attr.value, 10) * multiplier; } else { const quantity = (isNaN(item.system?.quantity?.value)) ? 1 : item.system.quantity.value; sources.push({ modtype, key, name: item.name, value: attr.value, type: item.type }); total += parseInt(attr.value, 10) * quantity; } } }); } } } }); } catch (err) { CONFIG.logger.warn(`Error occured while trying to calculate modifiers from item list`, err); } if (modtype === "Career Skill" || modtype === "Force Boost") { if (includeSource) { checked = true; return { checked, sources }; } return 0; } if (includeSource) { return { total, sources }; } else { return 0; } } // TODO: this should probably be either removed or refactored static getCalculatedValueFromCurrentAndArray(item, items, key, modtype, includeSource) { let total = 0; let checked = false; let sources = []; let rank = item?.system?.rank; if(rank === null || rank === undefined) { rank = 1; } if (item?.system) { const filteredAttributes = Object.values(item.system.attributes).filter(a => a).filter((a) => a.modtype === modtype && a.mod === key); filteredAttributes.forEach((attr) => { sources.push({ modtype, key, name: item.name, value: attr.value * rank, type: item.type }); total += parseInt(attr.value * rank, 10); }); } const itemsTotal = ModifierHelpers.getCalculatedValueFromItems(items, key, modtype, includeSource); if (includeSource) { total += itemsTotal.total; sources = sources.concat(itemsTotal.sources); return { total, sources }; } else { total += itemsTotal; return total; } } static getBaseValue(items, key, modtype) { let total = 0; items.forEach((item) => { if (item.type === "species") { const attrsToApply = Object.keys(item.system.attributes) .filter((id) => item.system.attributes[id].mod === key && item.system.attributes[id].modtype === modtype) .map((i) => item.system.attributes[i]); if (attrsToApply.length > 0) { attrsToApply.forEach((attr) => { total += parseInt(attr.value, 10); }); } } }); return total; } /** * DOM event * @param {object} event */ static async onClickAttributeControl(event) { event.preventDefault(); const a = event.currentTarget; const action = a.dataset.action; if (["forcepower", "signatureability", "specialization"].includes(this.object.type)) { // used in the direct modifiers at the top of certain item types const form = this.form; if (action === "create") { const nk = new Date().getTime(); let newKey = document.createElement("div"); newKey.innerHTML = `<input type="text" name="data.attributes.attr${nk}.key" value="attr${nk}" style="display:none;"/><select class="attribute-modtype" name="data.attributes.attr${nk}.modtype"><option value="Characteristic">Characteristic</option></select><select class="attribute-mod" name="data.attributes.attr${nk}.mod"><option value="${Object.keys(CONFIG.FFG.characteristics)[0]}">${Object.keys(CONFIG.FFG.characteristics)[0]}</option></select><input class="attribute-value" type="text" name="data.attributes.attr${nk}.value" value="0" data-dtype="Number" placeholder="0"/>`; form.appendChild(newKey); await this._onSubmit(event); } else if (action === "delete") { const li = a.closest(".attribute"); li.parentElement.removeChild(li); await this._onSubmit(event); } } else { // Add new attribute if (action === "create") { CONFIG.logger.debug("Creating new modifier..."); const nk = new Date().getTime(); if (["criticaldamage", "shipattachment", "shipweapon"].includes(this.object.type)) { await this.object.update({ "system.attributes": { [`attr${nk}`]: { modtype: "Vehicle Stat", mod: "Armour", value: 0, }, } }); } else if (["itemmodifier", "itemattachment"].includes(this.object.type)) { await this.object.update({ "system.attributes": { [`attr${nk}`]: { modtype: "Stat All", mod: "Wounds", value: 0, }, } }); } else { await this.object.update({ "system.attributes": { [`attr${nk}`]: { modtype: "Stat", mod: "Wounds", value: 0, }, } }); } } // Remove existing attribute else if (action === "delete") { const li = a.closest(".attribute"); li.parentElement.removeChild(li); await this._onSubmit(event); } } } /** * Create popout Modifiers Window * @param {object} event */ static async popoutModiferWindow(event) { event.preventDefault(); const a = event.currentTarget.parentElement; const title = `${game.i18n.localize("SWFFG.TabModifiers")}: ${this.object.name}`; new PopoutModifiers(this.object, { title, }).render(true); } static async popoutModiferWindowUpgrade(event) { event.preventDefault(); const a = event.currentTarget.parentElement; const keyname = a.dataset.itemid; const title = `${game.i18n.localize("SWFFG.TabModifiers")}: ${this.object.system.upgrades[keyname].name}`; const data = { parent: this.object, keyname, data: { data: { ...this.object.system.upgrades[keyname], }, }, isUpgrade: true, }; new PopoutModifiers(data, { title, }).render(true); } static async getDicePoolModifiers(pool, item, items) { let dicePool = new DicePoolFFG(pool); dicePool.boost += ModifierHelpers.getCalculatedValueFromCurrentAndArray(item, items, "Add Boost", "Roll Modifiers"); dicePool.setback += ModifierHelpers.getCalculatedValueFromCurrentAndArray(item, items, "Add Setback", "Roll Modifiers"); dicePool.remsetback += ModifierHelpers.getCalculatedValueFromCurrentAndArray(item, items, "Remove Setback", "Roll Modifiers"); dicePool.advantage += ModifierHelpers.getCalculatedValueFromCurrentAndArray(item, items, "Add Advantage", "Result Modifiers"); dicePool.dark += ModifierHelpers.getCalculatedValueFromCurrentAndArray(item, items, "Add Dark", "Result Modifiers"); dicePool.failure += ModifierHelpers.getCalculatedValueFromCurrentAndArray(item, items, "Add Failure", "Result Modifiers"); dicePool.light += ModifierHelpers.getCalculatedValueFromCurrentAndArray(item, items, "Add Light", "Result Modifiers"); dicePool.success += ModifierHelpers.getCalculatedValueFromCurrentAndArray(item, items, "Add Success", "Result Modifiers"); dicePool.threat += ModifierHelpers.getCalculatedValueFromCurrentAndArray(item, items, "Add Threat", "Result Modifiers"); dicePool.triumph += ModifierHelpers.getCalculatedValueFromCurrentAndArray(item, items, "Add Triumph", "Result Modifiers"); dicePool.despair += ModifierHelpers.getCalculatedValueFromCurrentAndArray(item, items, "Add Despair", "Result Modifiers"); dicePool.difficulty += ModifierHelpers.getCalculatedValueFromCurrentAndArray(item, items, "Add Difficulty", "Dice Modifiers"); dicePool.upgradeDifficulty(ModifierHelpers.getCalculatedValueFromCurrentAndArray(item, items, "Upgrade Difficulty", "Dice Modifiers")); dicePool.upgradeDifficulty(-1 * ModifierHelpers.getCalculatedValueFromCurrentAndArray(item, items, "Downgrade Difficulty", "Dice Modifiers")); dicePool.upgrade(ModifierHelpers.getCalculatedValueFromCurrentAndArray(item, items, "Upgrade Ability", "Dice Modifiers")); dicePool.upgrade(-1 * ModifierHelpers.getCalculatedValueFromCurrentAndArray(item, items, "Downgrade Ability", "Dice Modifiers")); return dicePool; } static applyBrawnToDamage(data) { if(data.characteristic?.value !== "" && data.characteristic?.value !== undefined) { return true; } return false; } /** * Given a skill path, determine the modifier type for that skill (the revers eof getModKeyPath) * @param skillPath * @returns {string} */ static getModTypeByModPath(skillPath) { if (skillPath.endsWith("force")) { return "Force Boost"; } else if (skillPath.endsWith("advantage")) { return "Skill Add Advantage"; } else if (skillPath.endsWith("dark")) { return "Skill Add Dark"; } else if (skillPath.endsWith("despair")) { return "Skill Add Despair"; } else if (skillPath.endsWith("failure")) { return "Skill Add Failure"; } else if (skillPath.endsWith("light")) { return "Skill Add Light"; } else if (skillPath.endsWith("success")) { return "Skill Add Success"; } else if (skillPath.endsWith("threat")) { return "Skill Add Threat"; } else if (skillPath.endsWith("triumph")) { return "Skill Add Triumph"; } else if (skillPath.endsWith("upgrades")) { return "Skill Add Upgrade"; } else if (skillPath.endsWith("boost")) { return "Skill Boost"; } else if (skillPath.endsWith("rank")) { return "Skill Rank"; } else if (skillPath.endsWith("remsetback")) { return "Skill Remove Setback"; } else if (skillPath.endsWith("setback")) { return "Skill Setback"; } else if (skillPath.endsWith("careerskill")) { return "Career Skill"; } } /** * Given a mod and mod type, expand them into a list of mods which should be applied * For example, modifying Brawn also modifies Encumbrance * @param modType * @param mod * @returns {[{modType, mod}]|[{modType, mod: string},{modType, mod: string}]} */ static explodeMod(modType, mod) { if (mod.toLocaleLowerCase().includes("defense") || mod.toLocaleLowerCase().includes("defence")) { return [ { modType: "Stat", mod: "Defence.Melee", }, { modType: "Stat", mod: "Defence.Ranged", }, ]; } else if (["Shields"].includes(mod)) { return [ { modType: modType, mod: "Shields.Fore", }, { modType: modType, mod: "Shields.Aft", }, { modType: modType, mod: "Shields.Port", }, { modType: modType, mod: "Shields.Starboard", }, ]; } else if (["Brawn"].includes(mod)) { return [ { modType: modType, mod: "Brawn", }, { modType: modType, mod: "EncumbranceMax", }, { modType: "Stat", mod: "Soak", }, ]; } else if (["Willpower"].includes(mod)) { return [ { modType: modType, mod: "Willpower", }, ]; } else { return [{ modType: modType, mod: mod, }]; } } /** * Given a modifier type and selection, determine the property path for an active effect to apply changes to * @param modType * @param mod * @returns {string} */ static getModKeyPath(modType, mod) { if (["Wounds", "Strain", "EncumbranceMax", "Speed", "Hulltrauma", "Systemstrain"].includes(mod)) { modType = "Threshold"; } if (modType === "Characteristic") { return `system.characteristics.${mod}.value`; } else if (modType === "Stat All" || modType === "Stat") { if (mod === "ForcePool") { return `system.stats.forcePool.max`; } else if (mod === "Defence.Melee") { return `system.stats.defence.melee`; } else if (mod === "Defence.Ranged") { return `system.stats.defence.ranged`; } else { return `system.stats.${mod.toLocaleLowerCase()}.value`; } } else if (modType === "Threshold") { if (mod === "Hulltrauma") { return `system.stats.hullTrauma.max`; } else if (mod === "Systemstrain") { return `system.stats.systemStrain.max`; } else if (mod === "EncumbranceMax") { // the mod for this is different, so don't simply return the mod value return `system.stats.encumbrance.max`; } else { return `system.stats.${mod.toLocaleLowerCase()}.max`; } } else if (modType === "Force Boost") { return `system.skills.${mod}.force`; } else if (modType === "Skill Add Advantage") { return `system.skills.${mod}.advantage`; } else if (modType === "Skill Add Dark") { return `system.skills.${mod}.dark`; } else if (modType === "Skill Add Despair") { return `system.skills.${mod}.despair`; } else if (modType === "Skill Add Failure") { return `system.skills.${mod}.failure`; } else if (modType === "Skill Add Light") { return `system.skills.${mod}.light`; } else if (modType === "Skill Add Success") { return `system.skills.${mod}.success`; } else if (modType === "Skill Add Threat") { return `system.skills.${mod}.threat`; } else if (modType === "Skill Add Triumph") { return `system.skills.${mod}.triumph`; } else if (modType === "Skill Add Upgrade") { return `system.skills.${mod}.upgrades`; } else if (modType === "Skill Boost") { return `system.skills.${mod}.boost`; } else if (modType === "Skill Rank") { return `system.skills.${mod}.rank`; } else if (modType === "Skill Remove Setback") { return `system.skills.${mod}.remsetback`; } else if (modType === "Skill Setback") { return `system.skills.${mod}.setback`; } else if (modType === "Career Skill") { return `system.skills.${mod}.careerskill`; } else if (modType === "Vehicle Stat") { if (mod === "Shields.Fore") { return `system.stats.shields.fore`; } else if (mod === "Shields.Aft") { return `system.stats.shields.aft`; } else if (mod === "Shields.Port") { return `system.stats.shields.port`; } else if (mod === "Shields.Starboard") { return `system.stats.shields.starboard`; } else if (mod === "Vehicle.Hardpoints") { return `system.stats.customizationHardPoints.value`; } else { return `system.stats.${mod.toLocaleLowerCase()}.value`; } } else if (["Weapon Stat", "Armor Stat"].includes(modType) && mod === "encumbrance") { return `system.stats.encumbrance.value`; } else { // TODO: this probably shouldn't be a UI notification in the released version CONFIG.logger.debug(`Unknown mod type: ${modType}`); //ui.notifications.warn(`Unknown mod type: ${modType}`); } } static async applyActiveEffectOnUpdate(item, formData) { /** * Given an updateObject event, update active effects on the item being updated * @type {*|{}} */ CONFIG.logger.debug("Updating active effects on item update"); if (!Object.keys(formData).includes("data")) { CONFIG.logger.debug("Bailing on update as there was no form data"); // no changes were made, bail return; } // remove deleted keys formData = foundry.utils.deepClone(formData); if (Object.keys(formData.data).includes("attributes")) { for (const attr of Object.keys(formData.data.attributes)) { if (attr.startsWith("-=attr")) { delete formData.data.attributes[attr]; } } } // Handle the free-form attributes list const formAttrs = foundry.utils.expandObject(formData)?.data?.attributes || {}; const attributes = formAttrs const existing = item.getEmbeddedCollection("ActiveEffect"); const toDelete = []; const toCreate = []; // first update anything inherent to the item type (such as "brawn" on "species") const inherentEffectName = `(inherent)`; const inherentEffect = existing.find(e => e.name === inherentEffectName); if (inherentEffect && Object.keys(formData.data).includes("attributes")) { for (let k of Object.keys(formData.data.attributes)) { if (k.startsWith("attr")) { // inherent effects like "brawn" on "species" only - skip user-created active effects only continue; } const explodedMods = ModifierHelpers.explodeMod( formData.data.attributes[k].modtype, formData.data.attributes[k].mod ); for (const curMod of explodedMods) { const modPath = ModifierHelpers.getModKeyPath( curMod['modType'], curMod['mod'] ); const inherentEffectChangeIndex = inherentEffect.changes.findIndex(c => c.key === modPath); if (inherentEffectChangeIndex >= 0) { inherentEffect.changes[inherentEffectChangeIndex].value = formData.data.attributes[k].value; } } } await inherentEffect.update({changes: inherentEffect.changes}); } // some inherent effects are not in the `attribute` keyspace; make sure to get them as well if (inherentEffect && ["gear", "weapon", "armour"].includes(item.type)) { const explodedMods = ModifierHelpers.explodeMod( "Stat", "Encumbrance" ); for (const curMod of explodedMods) { const modPath = ModifierHelpers.getModKeyPath( curMod['modType'], curMod['mod'] ); const inherentEffectChangeIndex = inherentEffect.changes.findIndex(c => c.key === modPath); if (inherentEffectChangeIndex >= 0) { inherentEffect.changes[inherentEffectChangeIndex].value = formData.data.encumbrance.value; } } if (item.type === "armour") { let explodedMods = ModifierHelpers.explodeMod( "Stat", "Defence" ); for (const curMod of explodedMods) { const modPath = ModifierHelpers.getModKeyPath( curMod['modType'], curMod['mod'] ); const inherentEffectChangeIndex = inherentEffect.changes.findIndex(c => c.key === modPath); if (inherentEffectChangeIndex >= 0) { inherentEffect.changes[inherentEffectChangeIndex].value = formData.data.defence.value; } } explodedMods = ModifierHelpers.explodeMod( "Stat", "Soak" ); for (const curMod of explodedMods) { const modPath = ModifierHelpers.getModKeyPath( curMod['modType'], curMod['mod'] ); const inherentEffectChangeIndex = inherentEffect.changes.findIndex(c => c.key === modPath); if (inherentEffectChangeIndex >= 0) { inherentEffect.changes[inherentEffectChangeIndex].value = formData.data.soak.value; } } } await inherentEffect.update({changes: inherentEffect.changes}); } else if (inherentEffect && ["shipattachment"].includes(item.type)) { const explodedMods = ModifierHelpers.explodeMod( "Vehicle Stat", "Vehicle.Hardpoints" ); for (const curMod of explodedMods) { const modPath = ModifierHelpers.getModKeyPath( curMod['modType'], curMod['mod'] ); const inherentEffectChangeIndex = inherentEffect.changes.findIndex(c => c.key === modPath); if (inherentEffectChangeIndex >= 0) { // hardpoints are _spent_, not _gained_ inherentEffect.changes[inherentEffectChangeIndex].value = formData.data.hardpoints.value * -1; } } await inherentEffect.update({changes: inherentEffect.changes}); } // Remove attributes which are no longer used if (item.system?.attributes) { // iterate over existing attributes to remove them if they were deleted for (let k of Object.keys(item.system.attributes)) { const match = existing.find(i => i.name === k); if (!attributes.hasOwnProperty(k)) { attributes[`-=${k}`] = null; // delete the matching active effect if (match) { toDelete.push(match.id); } } } } // iterate over formdata attributes to add/update them if they were added if (formData.data?.attributes) { for (let k of Object.keys(formData.data.attributes)) { const match = existing.find(i => i.name === k); const explodedMods = ModifierHelpers.explodeMod( formData.data.attributes[k].modtype, formData.data.attributes[k].mod ); const changes = []; for (const curMod of explodedMods) { changes.push({ key: ModifierHelpers.getModKeyPath(curMod['modType'], curMod['mod']), mode: CONST.ACTIVE_EFFECT_MODES.ADD, value: formData.data.attributes[k].value, }); } // check if an active effect exists - create it if not, update it if it does if (match) { await match.update({ changes: changes, }); } else if (k.startsWith("attr")) { // user-created active effects only - skip inherent effects like "brawn" on "species" // new entry toCreate.push({ name: k, changes: changes, }); } } } const existingEffects = item.getEmbeddedCollection("ActiveEffect"); const itemEffect = existingEffects.find(i => i.name === `(inherent)`); if (itemEffect && item.type === "species") { // update the wound and strain changes to match const newChanges = foundry.utils.deepClone(itemEffect.changes); const newBrawn = newChanges.find(ae => ae.key === "system.characteristics.Brawn.value").value; const newWillpower = newChanges.find(ae => ae.key === "system.characteristics.Willpower.value").value; // read the values from the form, if available, otherwise from the object const wounds = formData?.data?.attributes?.Wounds?.value || item.system.attributes.Wounds.value; const strain = formData?.data?.attributes?.Strain?.value || item.system.attributes.Strain.value; for (const change of newChanges) { if (change.key === "system.stats.wounds.max") { change.value = parseInt(wounds) + parseInt(newBrawn); } else if (change.key === "system.stats.strain.max") { change.value = parseInt(strain) + parseInt(newWillpower); } else if (change.key === "system.stats.encumbrance.max") { change.value = parseInt(newBrawn) + 5; } } await itemEffect.update({changes: newChanges}); } if (toCreate.length) { await item.createEmbeddedDocuments("ActiveEffect", toCreate); } if (toDelete.length) { await item.deleteEmbeddedDocuments("ActiveEffect", toDelete); } CONFIG.logger.debug("applyActiveEffectOnUpdate", toCreate, toDelete); } }
412
0.881201
1
0.881201
game-dev
MEDIA
0.793173
game-dev
0.924285
1
0.924285
Fluorohydride/ygopro-scripts
1,227
c89235196.lua
--ビッグ・ワン・ウォリアー function c89235196.initial_effect(c) --special summon local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(89235196,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_HAND) e1:SetCost(c89235196.spcost) e1:SetTarget(c89235196.sptg) e1:SetOperation(c89235196.spop) c:RegisterEffect(e1) end function c89235196.cfilter(c) return c:IsLevel(1) and c:IsAbleToGraveAsCost() end function c89235196.spcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c89235196.cfilter,tp,LOCATION_HAND,0,1,e:GetHandler()) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g=Duel.SelectMatchingCard(tp,c89235196.cfilter,tp,LOCATION_HAND,0,1,1,e:GetHandler()) Duel.SendtoGrave(g,REASON_COST) end function c89235196.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0) end function c89235196.spop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if not c:IsRelateToEffect(e) then return end Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP) end
412
0.9409
1
0.9409
game-dev
MEDIA
0.921046
game-dev
0.937987
1
0.937987
arcusmaximus/VNTranslationTools
8,311
VNTextPatch.Shared/Scripts/Mware/MwareScript.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using VNTextPatch.Shared.Util; namespace VNTextPatch.Shared.Scripts.Mware { public class MwareScript : IScript { public string Extension => ".nut"; private byte[] _data; private bool _hasHeader; private List<SquirrelLiteralPool> _literalPools; private List<SquirrelLiteralReference> _literalRefs; private GuessedEncoding _encoding; public void Load(ScriptLocation location) { _data = File.ReadAllBytes(location.ToFilePath()); _literalPools = new List<SquirrelLiteralPool>(); _literalRefs = new List<SquirrelLiteralReference>(); _encoding = new GuessedEncoding(); MemoryStream stream = new MemoryStream(_data); using StreamWriter writer = null; //new StreamWriter(Path.ChangeExtension(location.ToFilePath(), ".txt")); SquirrelV2Disassembler disassembler = new SquirrelV2Disassembler(stream, _encoding, writer); disassembler.LiteralPoolEncountered += p => _literalPools.Add(p); disassembler.TextReferenceEncountered += r => _literalRefs.Add(r); disassembler.Disassemble(); _hasHeader = disassembler.HasHeader; } public IEnumerable<ScriptString> GetStrings() { foreach (SquirrelLiteralReference reference in _literalRefs) { string value = (string)reference.Value; foreach (Range range in GetTextRanges(value, reference.Type)) { yield return new ScriptString(value.Substring(range.Offset, range.Length), range.Type); } } } public void WritePatched(IEnumerable<ScriptString> strings, ScriptLocation location) { List<SquirrelLiteralReference> referencesToPatch = MergeIntoLiteralPools(strings); using Stream inputStream = new MemoryStream(_data); using Stream outputStream = File.Open(location.ToFilePath(), FileMode.Create, FileAccess.Write); BinaryPatcher patcher = new BinaryPatcher(inputStream, outputStream); PatchLiteralPools(patcher); patcher.CopyUpTo((int)inputStream.Length); if (_hasHeader) { patcher.PatchInt32(8, (int)outputStream.Length - 0x14); patcher.PatchInt32(0xC, (int)outputStream.Length - 4); } PatchLiteralReferences(patcher, referencesToPatch); } private List<SquirrelLiteralReference> MergeIntoLiteralPools(IEnumerable<ScriptString> strings) { SquirrelLiteralPool currentPool = null; int lastLiteralIndex = -1; List<SquirrelLiteralReference> referencesToPatch = new List<SquirrelLiteralReference>(); using IEnumerator<ScriptString> stringEnumerator = strings.GetEnumerator(); foreach (SquirrelLiteralReference reference in _literalRefs) { string newText = MergeIntoText((string)reference.Value, reference.Type, stringEnumerator); if (reference.Pool != currentPool) { currentPool = reference.Pool; lastLiteralIndex = -1; } if (reference.Index > lastLiteralIndex) { reference.Pool.Values[reference.Index] = newText; lastLiteralIndex = reference.Index; } else { reference.Pool.Values.Add(newText); reference.Index = reference.Pool.Values.Count - 1; referencesToPatch.Add(reference); } } if (stringEnumerator.MoveNext()) throw new Exception("Too many lines in translation"); return referencesToPatch; } private static string MergeIntoText(string origValue, ScriptStringType origType, IEnumerator<ScriptString> stringEnumerator) { StringBuilder newValue = new StringBuilder(); int origStart = 0; foreach (Range range in GetTextRanges(origValue, origType)) { if (!stringEnumerator.MoveNext()) throw new Exception("Too few lines in translation"); if (origStart < range.Offset) newValue.Append(origValue, origStart, range.Offset - origStart); string newText = ProportionalWordWrapper.Default.Wrap(stringEnumerator.Current.Text); newValue.Append(newText); origStart = range.Offset + range.Length; } if (origStart < origValue.Length) newValue.Append(origValue, origStart, origValue.Length - origStart); return newValue.ToString(); } private void PatchLiteralPools(BinaryPatcher patcher) { foreach (SquirrelLiteralPool pool in _literalPools.Where(p => p.Length > 0) .OrderBy(p => p.Offset)) { patcher.CopyUpTo(pool.Offset); patcher.PatchInt32(pool.CountOffset, pool.Values.Count); patcher.ReplaceBytes( pool.Length, writer => { foreach (object value in pool.Values) { SquirrelObject.Write(writer, value, _encoding); } } ); } } private static void PatchLiteralReferences(BinaryPatcher patcher, List<SquirrelLiteralReference> references) { foreach (SquirrelLiteralReference reference in references) { switch (reference.Length) { case 1: patcher.PatchByte(reference.Offset, (byte)reference.Index); break; case 4: patcher.PatchInt32(reference.Offset, reference.Index); break; } } } private static IEnumerable<Range> GetTextRanges(string value, ScriptStringType type) { if (type == ScriptStringType.CharacterName) { yield return new Range(0, value.Length, ScriptStringType.CharacterName); yield break; } TrackingStringReader reader = new TrackingStringReader(value); int paragraphStart = -1; while (true) { int lineStartOffset = reader.Position; string line = reader.ReadLine(); if (string.IsNullOrWhiteSpace(line)) { if (paragraphStart >= 0) { int length = lineStartOffset - paragraphStart; if (length >= 2 && value[paragraphStart + length - 2] == '\r' && value[paragraphStart + length - 1] == '\n') { length -= 2; } yield return new Range(paragraphStart, length, ScriptStringType.Message); } if (line == null) yield break; paragraphStart = -1; continue; } if (line.StartsWith("//")) continue; if (line.StartsWith("<voice")) { Match match = Regex.Match(line, @" name='([^']+)'"); if (match.Success) yield return new Range(lineStartOffset + match.Groups[1].Index, match.Groups[1].Length, ScriptStringType.CharacterName); continue; } if (paragraphStart < 0) paragraphStart = lineStartOffset; } } } }
412
0.928869
1
0.928869
game-dev
MEDIA
0.357018
game-dev
0.940207
1
0.940207
Dimbreath/AzurLaneData
3,449
ko-KR/view/activity/subpages/templatepage/pttemplatepage.lua
slot0 = class("PtTemplatePage", import("....base.BaseActivityPage")) function slot0.OnInit(slot0) slot0.bg = slot0:findTF("AD") slot0.slider = slot0:findTF("slider", slot0.bg) slot0.step = slot0:findTF("step", slot0.bg) slot0.progress = slot0:findTF("progress", slot0.bg) slot0.displayBtn = slot0:findTF("display_btn", slot0.bg) slot0.awardTF = slot0:findTF("award", slot0.bg) slot0.battleBtn = slot0:findTF("battle_btn", slot0.bg) slot0.getBtn = slot0:findTF("get_btn", slot0.bg) slot0.gotBtn = slot0:findTF("got_btn", slot0.bg) end function slot0.OnDataSetting(slot0) if slot0.ptData then slot0.ptData:Update(slot0.activity) else slot0.ptData = ActivityPtData.New(slot0.activity) end end function slot0.OnFirstFlush(slot0) onButton(slot0, slot0.displayBtn, function () uv0:emit(ActivityMediator.SHOW_AWARD_WINDOW, PtAwardWindow, { type = uv0.ptData.type, dropList = uv0.ptData.dropList, targets = uv0.ptData.targets, level = uv0.ptData.level, count = uv0.ptData.count, resId = uv0.ptData.resId }) end, SFX_PANEL) onButton(slot0, slot0.battleBtn, function () slot0, slot1 = nil if uv0.activity:getConfig("config_client") ~= "" and uv0.activity:getConfig("config_client").linkActID then slot1 = getProxy(ActivityProxy):getActivityById(slot0) end if not slot0 then uv0:emit(ActivityMediator.BATTLE_OPERA) elseif slot1 and not slot1:isEnd() then uv0:emit(ActivityMediator.BATTLE_OPERA) else pg.TipsMgr.GetInstance():ShowTips(i18n("common_activity_end")) end end, SFX_PANEL) onButton(slot0, slot0.getBtn, function () slot0 = {} if uv0.ptData:GetAward().type == DROP_TYPE_RESOURCE and slot1.id == PlayerConst.ResGold and getProxy(PlayerProxy):getData():GoldMax(slot1.count) then table.insert(slot0, function (slot0) pg.MsgboxMgr.GetInstance():ShowMsgBox({ content = i18n("gold_max_tip_title") .. i18n("award_max_warning"), onYes = slot0 }) end) end seriesAsync(slot0, function () slot0, slot1 = uv0.ptData:GetResProgress() uv0:emit(ActivityMediator.EVENT_PT_OPERATION, { cmd = 1, activity_id = uv0.ptData:GetId(), arg1 = slot1 }) end) end, SFX_PANEL) end function slot0.OnUpdateFlush(slot0) if checkExist(slot0.activity:getConfig("config_client").story, { slot0.ptData:getTargetLevel() }, { 1 }) then pg.NewStoryMgr.GetInstance():Play(slot2[slot1][1]) end slot3, slot4, slot5 = slot0.ptData:GetLevelProgress() slot6, slot7, slot8 = slot0.ptData:GetResProgress() setText(slot0.step, slot3 .. "/" .. slot4) setText(slot0.progress, (slot8 >= 1 and setColorStr(slot6, COLOR_GREEN) or slot6) .. "/" .. slot7) setSlider(slot0.slider, 0, 1, slot8) slot9 = slot0.ptData:CanGetAward() slot10 = slot0.ptData:CanGetNextAward() setActive(slot0.battleBtn, slot0.ptData:CanGetMorePt() and not slot9 and slot10) setActive(slot0.getBtn, slot9) setActive(slot0.gotBtn, not slot10) updateDrop(slot0.awardTF, slot0.ptData:GetAward()) onButton(slot0, slot0.awardTF, function () uv0:emit(BaseUI.ON_DROP, uv1) end, SFX_PANEL) end function slot0.OnDestroy(slot0) end function slot0.GetWorldPtData(slot0, slot1) if slot1 <= pg.TimeMgr.GetInstance():GetServerTime() - (ActivityMainScene.Data2Time or 0) then ActivityMainScene.Data2Time = pg.TimeMgr.GetInstance():GetServerTime() slot0:emit(ActivityMediator.EVENT_PT_OPERATION, { cmd = 2, activity_id = slot0.ptData:GetId() }) end end return slot0
412
0.575683
1
0.575683
game-dev
MEDIA
0.684756
game-dev
0.908206
1
0.908206
ProjectIgnis/CardScripts
2,771
rush/c160204001.lua
--メタリオン・アシュラスター --Metarion Ashurastar local s,id=GetID() function s.initial_effect(c) --fusion material c:EnableReviveLimit() Fusion.AddProcMix(c,true,true,CARD_IMAGINARY_ACTOR,160204009) --Destroy 1 face down-card local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(id,0)) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetCategory(CATEGORY_DESTROY) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1,0,EFFECT_COUNT_CODE_SINGLE) e1:SetCost(s.cost) e1:SetTarget(s.destg) e1:SetOperation(s.desop) c:RegisterEffect(e1) --1 Cyborg Type monster gains ATK equal to the ATK of Warrior monsters the opponent controls local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(id,1)) e2:SetCategory(CATEGORY_ATKCHANGE) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_MZONE) e2:SetCountLimit(1,0,EFFECT_COUNT_CODE_SINGLE) e2:SetCost(s.cost) e2:SetTarget(s.atktg) e2:SetOperation(s.atkop) c:RegisterEffect(e2) end function s.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsPlayerCanDiscardDeckAsCost(tp,1) end end --destroy 1 face down function s.destg(e,tp,eg,ep,ev,re,r,rp,chk) local dg=Duel.GetMatchingGroup(Card.IsFacedown,tp,0,LOCATION_ONFIELD,nil) if chk==0 then return #dg>0 end end function s.desop(e,tp,eg,ep,ev,re,r,rp) --Requirement local c=e:GetHandler() if Duel.DiscardDeck(tp,1,REASON_COST)<1 then return end --effect local dg=Duel.GetMatchingGroup(Card.IsFacedown,tp,0,LOCATION_ONFIELD,nil) if #dg>0 then local sg=dg:Select(tp,1,1,nil) Duel.HintSelection(sg) Duel.Destroy(sg,REASON_EFFECT) end end --gain atk function s.atktg(e,tp,eg,ep,ev,re,r,rp,chk) local g=Duel.GetMatchingGroup(aux.FilterMaximumSideFunctionEx(s.filter2),tp,0,LOCATION_MZONE,nil) local atk=g:GetSum(Card.GetAttack) if chk==0 then return Duel.IsExistingMatchingCard(aux.FilterMaximumSideFunctionEx(s.filter),tp,LOCATION_MZONE,0,1,nil) and #g>0 and atk>0 end end function s.filter(c) return c:IsFaceup() and c:IsRace(RACE_CYBORG) end function s.filter2(c) return c:IsFaceup() and c:IsRace(RACE_WARRIOR) end function s.atkop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() --Requirement local c=e:GetHandler() if Duel.DiscardDeck(tp,1,REASON_COST)<1 then return end --Effect Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP) local g=Duel.SelectMatchingCard(tp,aux.FilterMaximumSideFunctionEx(s.filter),tp,LOCATION_MZONE,0,1,1,nil) local g2=Duel.GetMatchingGroup(aux.FilterMaximumSideFunctionEx(s.filter2),tp,0,LOCATION_MZONE,nil) local atk=g2:GetSum(Card.GetAttack) if #g>0 and atk>0 then Duel.HintSelection(g) local tc=g:GetFirst() local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetValue(atk) e1:SetReset(RESETS_STANDARD_PHASE_END) tc:RegisterEffect(e1) end end
412
0.916906
1
0.916906
game-dev
MEDIA
0.992351
game-dev
0.978974
1
0.978974
ShadzXD/incompetent-Psych-engine
12,650
source/states/editors/MenuCharacterEditorState.hx
package states.editors; import openfl.net.FileReference; import openfl.events.Event; import openfl.events.IOErrorEvent; import flash.net.FileFilter; import haxe.Json; import objects.MenuCharacter; import states.editors.content.Prompt; import states.editors.content.PsychJsonPrinter; class MenuCharacterEditorState extends MusicBeatState implements PsychUIEventHandler.PsychUIEvent { var grpWeekCharacters:FlxTypedGroup<MenuCharacter>; var characterFile:MenuCharacterFile = null; var txtOffsets:FlxText; var defaultCharacters:Array<String> = ['dad', 'bf', 'gf']; var unsavedProgress:Bool = false; override function create() { characterFile = { image: 'Menu_Dad', scale: 1, position: [0, 0], idle_anim: 'M Dad Idle', confirm_anim: 'M Dad Idle', flipX: false, antialiasing: true }; #if DISCORD_ALLOWED // Updating Discord Rich Presence DiscordClient.changePresence("Menu Character Editor", "Editting: " + characterFile.image); #end grpWeekCharacters = new FlxTypedGroup<MenuCharacter>(); for (char in 0...3) { var weekCharacterThing:MenuCharacter = new MenuCharacter((FlxG.width * 0.25) * (1 + char) - 150, defaultCharacters[char]); weekCharacterThing.y += 70; weekCharacterThing.alpha = 0.2; grpWeekCharacters.add(weekCharacterThing); } add(new FlxSprite(0, 56).makeGraphic(FlxG.width, 386, 0xFFF9CF51)); add(grpWeekCharacters); txtOffsets = new FlxText(20, 10, 0, "[0, 0]", 32); txtOffsets.setFormat(Paths.font("vcr.ttf"), 32, FlxColor.WHITE, CENTER); txtOffsets.alpha = 0.7; add(txtOffsets); var tipText:FlxText = new FlxText(0, 540, FlxG.width, "Arrow Keys - Change Offset (Hold shift for 10x speed) \nSpace - Play \"Start Press\" animation (Boyfriend Character Type)", 16); tipText.setFormat(Paths.font("vcr.ttf"), 16, FlxColor.WHITE, CENTER); tipText.scrollFactor.set(); add(tipText); addEditorBox(); FlxG.mouse.visible = true; updateCharacters(); super.create(); } var UI_typebox:PsychUIBox; var UI_mainbox:PsychUIBox; function addEditorBox() { UI_typebox = new PsychUIBox(100, FlxG.height - 230, 120, 180, ['Character Type']); UI_typebox.scrollFactor.set(); addTypeUI(); add(UI_typebox); UI_mainbox = new PsychUIBox(FlxG.width - 340, FlxG.height - 265, 240, 215, ['Character']); UI_mainbox.scrollFactor.set(); addCharacterUI(); add(UI_mainbox); var loadButton:PsychUIButton = new PsychUIButton(0, 480, "Load Character", function() { loadCharacter(); }); loadButton.screenCenter(X); loadButton.x -= 60; add(loadButton); var saveButton:PsychUIButton = new PsychUIButton(0, 480, "Save Character", function() { saveCharacter(); }); saveButton.screenCenter(X); saveButton.x += 60; add(saveButton); } var characterTypeRadio:PsychUIRadioGroup; function addTypeUI() { var tab_group = UI_typebox.getTab('Character Type').menu; characterTypeRadio = new PsychUIRadioGroup(10, 20, ['Opponent', 'Boyfriend', 'Girlfriend'], 40); characterTypeRadio.checked = 0; characterTypeRadio.onClick = updateCharacters; tab_group.add(characterTypeRadio); } var imageInputText:PsychUIInputText; var idleInputText:PsychUIInputText; var confirmInputText:PsychUIInputText; var scaleStepper:PsychUINumericStepper; var flipXCheckbox:PsychUICheckBox; var antialiasingCheckbox:PsychUICheckBox; function addCharacterUI() { var tab_group = UI_mainbox.getTab('Character').menu; imageInputText = new PsychUIInputText(10, 20, 80, characterFile.image, 8); idleInputText = new PsychUIInputText(10, imageInputText.y + 35, 100, characterFile.idle_anim, 8); confirmInputText = new PsychUIInputText(10, idleInputText.y + 35, 100, characterFile.confirm_anim, 8); flipXCheckbox = new PsychUICheckBox(10, confirmInputText.y + 30, "Flip X", 100); flipXCheckbox.onClick = function() { grpWeekCharacters.members[characterTypeRadio.checked].flipX = flipXCheckbox.checked; characterFile.flipX = flipXCheckbox.checked; }; antialiasingCheckbox = new PsychUICheckBox(10, flipXCheckbox.y + 30, "Antialiasing", 100); antialiasingCheckbox.checked = grpWeekCharacters.members[characterTypeRadio.checked].antialiasing; antialiasingCheckbox.onClick = function() { grpWeekCharacters.members[characterTypeRadio.checked].antialiasing = antialiasingCheckbox.checked; characterFile.antialiasing = antialiasingCheckbox.checked; }; var reloadImageButton:PsychUIButton = new PsychUIButton(140, confirmInputText.y + 30, "Reload Char", function() { reloadSelectedCharacter(); }); scaleStepper = new PsychUINumericStepper(140, imageInputText.y, 0.05, 1, 0.1, 30, 2); var confirmDescText = new FlxText(10, confirmInputText.y - 18, 0, 'Start Press animation on the .XML:'); tab_group.add(new FlxText(10, imageInputText.y - 18, 0, 'Image file name:')); tab_group.add(new FlxText(10, idleInputText.y - 18, 0, 'Idle animation on the .XML:')); tab_group.add(new FlxText(scaleStepper.x, scaleStepper.y - 18, 0, 'Scale:')); tab_group.add(flipXCheckbox); tab_group.add(antialiasingCheckbox); tab_group.add(reloadImageButton); tab_group.add(confirmDescText); tab_group.add(imageInputText); tab_group.add(idleInputText); tab_group.add(confirmInputText); tab_group.add(scaleStepper); } function updateCharacters() { for (i in 0...3) { var char:MenuCharacter = grpWeekCharacters.members[i]; char.alpha = 0.2; char.character = ''; char.changeCharacter(defaultCharacters[i]); } reloadSelectedCharacter(); } function reloadSelectedCharacter() { var char:MenuCharacter = grpWeekCharacters.members[characterTypeRadio.checked]; char.alpha = 1; char.frames = Paths.getSparrowAtlas('menucharacters/' + characterFile.image); char.animation.addByPrefix('idle', characterFile.idle_anim, 24); if(characterTypeRadio.checked == 1) char.animation.addByPrefix('confirm', characterFile.confirm_anim, 24, false); char.flipX = (characterFile.flipX == true); char.scale.set(characterFile.scale, characterFile.scale); char.updateHitbox(); char.animation.play('idle'); updateOffset(); #if DISCORD_ALLOWED // Updating Discord Rich Presence DiscordClient.changePresence("Menu Character Editor", "Editting: " + characterFile.image); #end } public function UIEvent(id:String, sender:Dynamic) { if(id == PsychUICheckBox.CLICK_EVENT) unsavedProgress = true; if(id == PsychUIInputText.CHANGE_EVENT && (sender is PsychUIInputText)) { if(sender == imageInputText) { characterFile.image = imageInputText.text; unsavedProgress = true; } else if(sender == idleInputText) { characterFile.idle_anim = idleInputText.text; unsavedProgress = true; } else if(sender == confirmInputText) { characterFile.confirm_anim = confirmInputText.text; unsavedProgress = true; } } else if(id == PsychUINumericStepper.CHANGE_EVENT && (sender is PsychUINumericStepper)) { if (sender == scaleStepper) { characterFile.scale = scaleStepper.value; reloadSelectedCharacter(); unsavedProgress = true; } } } override function update(elapsed:Float) { if(PsychUIInputText.focusOn == null) { ClientPrefs.toggleVolumeKeys(true); if(FlxG.keys.justPressed.ESCAPE) { if(!unsavedProgress) { FlxG.switchState(() -> new states.editors.MasterEditorMenu()); FlxG.sound.playMusic(Paths.music('freakyMenu')); } else openSubState(new ExitConfirmationPrompt()); } var shiftMult:Int = 1; if(FlxG.keys.pressed.SHIFT) shiftMult = 10; if(FlxG.keys.justPressed.LEFT) { characterFile.position[0] += shiftMult; updateOffset(); } if(FlxG.keys.justPressed.RIGHT) { characterFile.position[0] -= shiftMult; updateOffset(); } if(FlxG.keys.justPressed.UP) { characterFile.position[1] += shiftMult; updateOffset(); } if(FlxG.keys.justPressed.DOWN) { characterFile.position[1] -= shiftMult; updateOffset(); } if(FlxG.keys.justPressed.SPACE && characterTypeRadio.checked == 1) { grpWeekCharacters.members[characterTypeRadio.checked].animation.play('confirm', true); } } else ClientPrefs.toggleVolumeKeys(false); var char:MenuCharacter = grpWeekCharacters.members[1]; if(char.animation.curAnim != null && char.animation.curAnim.name == 'confirm' && char.animation.curAnim.finished) char.animation.play('idle', true); super.update(elapsed); } function updateOffset() { var char:MenuCharacter = grpWeekCharacters.members[characterTypeRadio.checked]; char.offset.set(characterFile.position[0], characterFile.position[1]); txtOffsets.text = '' + characterFile.position; } var _file:FileReference = null; function loadCharacter() { var jsonFilter:FileFilter = new FileFilter('JSON', 'json'); _file = new FileReference(); _file.addEventListener(#if desktop Event.SELECT #else Event.COMPLETE #end, onLoadComplete); _file.addEventListener(Event.CANCEL, onLoadCancel); _file.addEventListener(IOErrorEvent.IO_ERROR, onLoadError); _file.browse([#if !mac jsonFilter #end]); } function onLoadComplete(_):Void { _file.removeEventListener(#if desktop Event.SELECT #else Event.COMPLETE #end, onLoadComplete); _file.removeEventListener(Event.CANCEL, onLoadCancel); _file.removeEventListener(IOErrorEvent.IO_ERROR, onLoadError); #if sys var fullPath:String = null; @:privateAccess if(_file.__path != null) fullPath = _file.__path; if(fullPath != null) { var rawJson:String = File.getContent(fullPath); if(rawJson != null) { var loadedChar:MenuCharacterFile = cast Json.parse(rawJson); if(loadedChar.idle_anim != null && loadedChar.confirm_anim != null) //Make sure it's really a character { var cutName:String = _file.name.substr(0, _file.name.length - 5); trace("Successfully loaded file: " + cutName); characterFile = loadedChar; reloadSelectedCharacter(); imageInputText.text = characterFile.image; idleInputText.text = characterFile.image; confirmInputText.text = characterFile.image; scaleStepper.value = characterFile.scale; updateOffset(); _file = null; return; } } } _file = null; #else trace("File couldn't be loaded! You aren't on Desktop, are you?"); #end } /** * Called when the save file dialog is cancelled. */ function onLoadCancel(_):Void { _file.removeEventListener(#if desktop Event.SELECT #else Event.COMPLETE #end, onLoadComplete); _file.removeEventListener(Event.CANCEL, onLoadCancel); _file.removeEventListener(IOErrorEvent.IO_ERROR, onLoadError); _file = null; trace("Cancelled file loading."); } /** * Called if there is an error while saving the gameplay recording. */ function onLoadError(_):Void { _file.removeEventListener(#if desktop Event.SELECT #else Event.COMPLETE #end, onLoadComplete); _file.removeEventListener(Event.CANCEL, onLoadCancel); _file.removeEventListener(IOErrorEvent.IO_ERROR, onLoadError); _file = null; trace("Problem loading file"); } function saveCharacter() { var data:String = PsychJsonPrinter.print(characterFile, ['position']); if (data.length > 0) { var splittedImage:Array<String> = imageInputText.text.trim().split('_'); var characterName:String = splittedImage[splittedImage.length-1].toLowerCase().replace(' ', ''); _file = new FileReference(); _file.addEventListener(#if desktop Event.SELECT #else Event.COMPLETE #end, onSaveComplete); _file.addEventListener(Event.CANCEL, onSaveCancel); _file.addEventListener(IOErrorEvent.IO_ERROR, onSaveError); _file.save(data, characterName + ".json"); } } function onSaveComplete(_):Void { _file.removeEventListener(#if desktop Event.SELECT #else Event.COMPLETE #end, onSaveComplete); _file.removeEventListener(Event.CANCEL, onSaveCancel); _file.removeEventListener(IOErrorEvent.IO_ERROR, onSaveError); _file = null; FlxG.log.notice("Successfully saved file."); } /** * Called when the save file dialog is cancelled. */ function onSaveCancel(_):Void { _file.removeEventListener(#if desktop Event.SELECT #else Event.COMPLETE #end, onSaveComplete); _file.removeEventListener(Event.CANCEL, onSaveCancel); _file.removeEventListener(IOErrorEvent.IO_ERROR, onSaveError); _file = null; } /** * Called if there is an error while saving the gameplay recording. */ function onSaveError(_):Void { _file.removeEventListener(#if desktop Event.SELECT #else Event.COMPLETE #end, onSaveComplete); _file.removeEventListener(Event.CANCEL, onSaveCancel); _file.removeEventListener(IOErrorEvent.IO_ERROR, onSaveError); _file = null; FlxG.log.error("Problem saving file"); } }
412
0.980706
1
0.980706
game-dev
MEDIA
0.827893
game-dev,desktop-app
0.991145
1
0.991145
TouchController/TouchController
4,404
mod/1.20.4/common-1.20.4/src/mixin/java/top/fifthlight/touchcontroller/mixin/InGameHudMixin.java
package top.fifthlight.touchcontroller.mixin; import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.AttackIndicatorStatus; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.LivingEntity; import org.koin.java.KoinJavaComponent; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import top.fifthlight.touchcontroller.common.event.RenderEvents; import top.fifthlight.touchcontroller.common.model.ControllerHudModel; @Mixin(Gui.class) public abstract class InGameHudMixin { @Shadow @Final private static ResourceLocation CROSSHAIR_ATTACK_INDICATOR_FULL_SPRITE; @Shadow @Final private static ResourceLocation CROSSHAIR_ATTACK_INDICATOR_BACKGROUND_SPRITE; @Shadow @Final private static ResourceLocation CROSSHAIR_ATTACK_INDICATOR_PROGRESS_SPRITE; @Shadow private int screenWidth; @Shadow private int screenHeight; @Shadow @Final private Minecraft minecraft; @Inject( method = "renderCrosshair", at = @At( value = "INVOKE", target = "Lnet/minecraft/client/gui/GuiGraphics;blitSprite(Lnet/minecraft/resources/ResourceLocation;IIII)V", ordinal = 0 ), cancellable = true ) private void renderCrosshair(GuiGraphics context, CallbackInfo callbackInfo) { boolean shouldRender = RenderEvents.INSTANCE.shouldRenderCrosshair(); if (!shouldRender) { if (this.minecraft.options.attackIndicator().get() == AttackIndicatorStatus.CROSSHAIR) { float attackCooldownProgress = this.minecraft.player.getAttackStrengthScale(0.0f); boolean renderFullTexture = false; if (this.minecraft.crosshairPickEntity != null && this.minecraft.crosshairPickEntity instanceof LivingEntity && attackCooldownProgress >= 1.0f) { renderFullTexture = this.minecraft.player.getCurrentItemAttackStrengthDelay() > 5.0f && this.minecraft.crosshairPickEntity.isAlive(); } int x = context.guiWidth() / 2; int y = context.guiHeight() / 2; if (renderFullTexture) { context.blitSprite(CROSSHAIR_ATTACK_INDICATOR_FULL_SPRITE, x - 8, y - 8, 16, 16); } else if (attackCooldownProgress < 1.0f) { int progress = (int) (attackCooldownProgress * 17.0f); context.blitSprite(CROSSHAIR_ATTACK_INDICATOR_BACKGROUND_SPRITE, x - 8, y - 2, 16, 4); context.blitSprite(CROSSHAIR_ATTACK_INDICATOR_PROGRESS_SPRITE, 16, 4, 0, 0, x - 8, y - 2, progress, 4); } } RenderSystem.defaultBlendFunc(); RenderSystem.disableBlend(); callbackInfo.cancel(); } } @Inject( method = "renderHotbar", at = @At( value = "INVOKE", target = "Lcom/mojang/blaze3d/vertex/PoseStack;popPose()V", ordinal = 0 ) ) private void renderHotbar(float tickDelta, GuiGraphics context, CallbackInfo ci) { var player = minecraft.player; if (player != null) { var controllerHudModel = (ControllerHudModel) KoinJavaComponent.get(ControllerHudModel.class); var inventory = controllerHudModel.getResult().getInventory(); var slots = inventory.getSlots(); var x = (screenWidth - 182) / 2 + 1; var y = screenHeight - 22 + 1; for (int i = 0; i < 9; i++) { var stack = player.getInventory().getItem(i); if (stack.isEmpty()) { continue; } var slot = slots[i]; var progress = slot.getProgress(); var height = (int) (16 * progress); context.fill(x + 20 * i + 2, y + 18 - height, x + 20 * i + 18, y + 18, 0xFF00BB00); } } } }
412
0.854651
1
0.854651
game-dev
MEDIA
0.952248
game-dev
0.975578
1
0.975578
Soaprman/FEFTwiddler
30,241
FEFTwiddler/Model/NewGamePlus/TimeMachine.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FEFTwiddler.Model.NewGamePlus { public class TimeMachine { private Model.IChapterSave _chapterSave; public TimeMachine(Model.IChapterSave chapterSave) { _chapterSave = chapterSave; } public void NewGamePlus() { } public void RemoveEveryoneButCorrin() { _chapterSave.UnitRegion.Units.RemoveAll((x) => !Data.Database.Characters.GetByID(x.CharacterID).IsCorrin); } public void InsertCharacters() { var characterDatas = Data.Database.Characters.GetAllNamedPlayable().Where((x) => !x.IsCorrin && x.CharacterID < Enums.Character.Kana_M); foreach (var characterData in characterDatas) { var unit = Model.Unit.Create(characterData.CharacterID); unit.UnitBlock = Enums.UnitBlock.Absent; _chapterSave.UnitRegion.Units.Add(unit); } } public void LevelUpAllUnits() { foreach (var unit in _chapterSave.UnitRegion.Units) { // TODO: Remove fixed value, determine based on which game is being played // Try without it this time //LevelUp(unit, 19); } } // TODO: Revert Corrin // Remove marriage byte (otherwise paralogue 2 stays available) /// <summary> /// Level a unit, giving them the average gains that their growth rates would dictate /// </summary> public void LevelUp(Model.Unit unit, int levels) { var characterGrowthRates = Data.Database.Characters.GetByID(unit.CharacterID).GrowthRates; var classGrowthRates = Data.Database.Classes.GetByID(unit.ClassID).GrowthRates; var combinedGrowthRates = characterGrowthRates + classGrowthRates; int hp; int str; int mag; int skl; int spd; int lck; int def; int res; hp = str = mag = skl = spd = lck = def = res = 0; for (var i = 0; i < levels; i++) { hp += combinedGrowthRates.HP; str += combinedGrowthRates.Str; mag += combinedGrowthRates.Mag; skl += combinedGrowthRates.Skl; spd += combinedGrowthRates.Spd; lck += combinedGrowthRates.Lck; def += combinedGrowthRates.Def; res += combinedGrowthRates.Res; } unit.Level += (byte)levels; unit.GainedStats.HP += (sbyte)(hp / 100); unit.GainedStats.Str += (sbyte)(str / 100); unit.GainedStats.Mag += (sbyte)(mag / 100); unit.GainedStats.Skl += (sbyte)(skl / 100); unit.GainedStats.Spd += (sbyte)(spd / 100); unit.GainedStats.Lck += (sbyte)(lck / 100); unit.GainedStats.Def += (sbyte)(def / 100); unit.GainedStats.Res += (sbyte)(res / 100); } public void EmptyConvoy() { _chapterSave.ConvoyRegion.Convoy.Clear(); } public bool CanUnplayChapter(Enums.Chapter chapterId) { var chapterData = Data.Database.Chapters.GetByID(chapterId); foreach (var unlockedChapterId in chapterData.UnlocksChapters) { if (_chapterSave.BattlefieldRegion.Battlefields .Where(x => x.ChapterID == unlockedChapterId && x.BattlefieldStatus == Enums.BattlefieldStatus.Completed) .Any()) return false; } return true; } public void UnplayChapter(Enums.Chapter chapterId) { // Set the newly unplayed chapter to available _chapterSave.UserRegion.ChapterHistory.RemoveAll((x) => x.ChapterID == chapterId); var battlefields = _chapterSave.BattlefieldRegion.Battlefields.Where((x) => x.ChapterID == chapterId); foreach (var battlefield in battlefields) { battlefield.BattlefieldStatus = Enums.BattlefieldStatus.Available; } // Set any chapters beating this chapter would unlock to unavailable var chapterData = Data.Database.Chapters.GetByID(chapterId); foreach (var unlockedChapterId in chapterData.UnlocksChapters) { var dependentBattlefield = _chapterSave.BattlefieldRegion.Battlefields.Where(x => x.ChapterID == unlockedChapterId).FirstOrDefault(); if (dependentBattlefield != null) dependentBattlefield.BattlefieldStatus = Enums.BattlefieldStatus.Unavailable; } // Update the header if we just unplayed a story chapter AND if we're not in battle or in a map save if (_chapterSave.GetSaveFileType() == Enums.SaveFileType.Chapter && _chapterSave.Header.IsBattlePrepSave == false && chapterData.Type == "Story") { UpdateHeaderChapter(chapterId); } // If we just unplayed chapter 6, do some special stuff to properly reset the branch of fate if (chapterId == Enums.Chapter.Birthright_Chapter6 || chapterId == Enums.Chapter.Conquest_Chapter6 || chapterId == Enums.Chapter.Revelation_Chapter6) { _chapterSave.UserRegion.Unknown_Block2_0xE6 = 0x00; _chapterSave.UserRegion.Unknown_Block2_0xE7 = 0x00; _chapterSave.UserRegion.Unknown_Block2_0xE8 = 0x00; _chapterSave.UserRegion.Unknown_Block2_0xEC = 0x04; _chapterSave.UserRegion.Unknown_Block2_0x10A = 0x00; // This flag is also used to denote whether a path has been chosen _chapterSave.Header.UnitsGoAbsentWhenKilled = true; _chapterSave.UserRegion.UnitsGoAbsentWhenKilled = true; // Set the game to the default (Birthright) _chapterSave.Header.Game = Enums.Game.Birthright; _chapterSave.UserRegion.Game = Enums.Game.Birthright; // Set the branch of fate header UpdateHeaderChapter(Enums.Chapter.Chapter6); // Set the gameplay chapter _chapterSave.UserRegion.CurrentChapter = Enums.Chapter.Chapter6; // Kill the story battlefields RemoveRouteSpecificStoryBattlefields(); AddBirthrightSpecificStoryBattlefields(); } } /// <summary> /// Unlocks a chapter and sets it available if it's currently set to unavailable. /// Mainly for amiibo chapter unlocking. /// </summary> public void UnlockChapter(Enums.Chapter chapterId) { var battlefields = _chapterSave.BattlefieldRegion.Battlefields.Where((x) => x.ChapterID == chapterId); foreach (var battlefield in battlefields) { if (battlefield.BattlefieldStatus == Enums.BattlefieldStatus.Unavailable) { battlefield.BattlefieldStatus = Enums.BattlefieldStatus.Available; } } } /// <summary> /// Update the header with the name of the given chapter /// </summary> public void UpdateHeaderChapter(Enums.Chapter chapterId) { var chapterData = Data.Database.Chapters.GetByID(chapterId); _chapterSave.Header.CurrentChapter = chapterId; _chapterSave.Header.ChapterName1 = chapterData.DisplayName1; _chapterSave.Header.ChapterName2 = chapterData.DisplayName2; } public void ReturnToPrologue() { ClearBattlefields(); // Pre-branch saves use the Birthright list. // Obviously, this is proof that Birthright is the One True Version of Fates! AddBirthrightBattlefields(); // I don't know what most of these are. // This is just setting them to what they're like in a legit "new" save. // I will list side effects as I find them in order to figure out what these are. // Side effect: Tutorials show for the battle prep and support menus when opening them. _chapterSave.UserRegion.Unknown_Block1_0x09 = 0x00; _chapterSave.UserRegion.Unknown_Block1_0x0A = 0x00; _chapterSave.UserRegion.Unknown_Block1_0x0B = 0x00; _chapterSave.UserRegion.Unknown_Block2_0xDF = 0x00; _chapterSave.UserRegion.Unknown_Block2_0xE0 = 0x00; _chapterSave.UserRegion.Unknown_Block2_0xE1 = 0x00; _chapterSave.UserRegion.Unknown_Block2_0xE2 = 0x00; _chapterSave.UserRegion.Unknown_Block2_0xE3 = 0x00; _chapterSave.UserRegion.Unknown_Block2_0xE6 = 0x01; _chapterSave.UserRegion.Unknown_Block2_0xE7 = 0x00; _chapterSave.UserRegion.Unknown_Block2_0xE8 = 0x00; _chapterSave.UserRegion.Unknown_Block2_0xEC = 0x00; _chapterSave.UserRegion.Unknown_Block2_0xED = 0x00; _chapterSave.UserRegion.Unknown_Block2_0x10A = 0x00; _chapterSave.UserRegion.Game = Enums.Game.Birthright; _chapterSave.UserRegion.ChapterHistory.Clear(); _chapterSave.UserRegion.CurrentChapter = Enums.Chapter.Prologue; _chapterSave.UserRegion.UnitsGoAbsentWhenKilled = true; // This is here too _chapterSave.BattlefieldRegion.CurrentChapter = Enums.Chapter.Prologue; // Just in case _chapterSave.UserRegion.Gold = 0; // Also refresh the header with data from the body regions _chapterSave.Header.UnitsGoAbsentWhenKilled = true; _chapterSave.Header.CurrentChapter = Enums.Chapter.Prologue; _chapterSave.Header.Unknown_0x07 = 0x00; _chapterSave.Header.Unknown_0x08 = 0x00; _chapterSave.Header.Game = Enums.Game.Birthright; _chapterSave.Header.ChapterName1 = "Prologue"; _chapterSave.Header.ChapterName2 = "Randomized"; } public void ReturnToChapter7() { foreach (var battlefield in _chapterSave.BattlefieldRegion.Battlefields) { switch (battlefield.ChapterID) { case Enums.Chapter.Prologue: case Enums.Chapter.Chapter1: case Enums.Chapter.Chapter2: case Enums.Chapter.Chapter3: case Enums.Chapter.Chapter4: case Enums.Chapter.Chapter5: case Enums.Chapter.Chapter6: case Enums.Chapter.Birthright_Chapter6: case Enums.Chapter.Conquest_Chapter6: case Enums.Chapter.Revelation_Chapter6: break; // Do nothing case Enums.Chapter.Birthright_Chapter7: case Enums.Chapter.Conquest_Chapter7: case Enums.Chapter.Revelation_Chapter7: battlefield.BattlefieldStatus = Enums.BattlefieldStatus.Available; _chapterSave.UserRegion.ChapterHistory.RemoveAll((x) => x.ChapterID == battlefield.ChapterID); break; default: battlefield.BattlefieldStatus = Enums.BattlefieldStatus.Unavailable; _chapterSave.UserRegion.ChapterHistory.RemoveAll((x) => x.ChapterID == battlefield.ChapterID); break; } } switch (_chapterSave.Header.Game) { case Enums.Game.Birthright: _chapterSave.UserRegion.CurrentChapter = Enums.Chapter.Birthright_Chapter7; break; case Enums.Game.Conquest: _chapterSave.UserRegion.CurrentChapter = Enums.Chapter.Conquest_Chapter7; break; case Enums.Game.Revelation: _chapterSave.UserRegion.CurrentChapter = Enums.Chapter.Revelation_Chapter7; break; } } public void ClearBattlefields() { _chapterSave.BattlefieldRegion.Battlefields.Clear(); } public void AddBirthrightBattlefields() { AddBattlefield(0x00, Enums.Chapter.Chapter1); AddBattlefield(0x01, Enums.Chapter.Chapter2); AddBattlefield(0x02, Enums.Chapter.Chapter3); AddBattlefield(0x03, Enums.Chapter.Chapter4); AddBattlefield(0x04, Enums.Chapter.Chapter5); AddBattlefield(0x05, Enums.Chapter.Birthright_Chapter6); AddBattlefield(0x06, Enums.Chapter.Birthright_Chapter7); AddBattlefield(0x07, Enums.Chapter.Birthright_Chapter8); AddBattlefield(0x08, Enums.Chapter.Birthright_Chapter9); AddBattlefield(0x09, Enums.Chapter.Birthright_Chapter10); AddBattlefield(0x0A, Enums.Chapter.Birthright_Chapter11); AddBattlefield(0x0B, Enums.Chapter.Birthright_Chapter12); AddBattlefield(0x0C, Enums.Chapter.Birthright_Chapter13); AddBattlefield(0x0D, Enums.Chapter.Birthright_Chapter14); AddBattlefield(0x0E, Enums.Chapter.Birthright_Chapter15); AddBattlefield(0x0F, Enums.Chapter.Birthright_Chapter16); AddBattlefield(0x10, Enums.Chapter.Birthright_Chapter17); AddBattlefield(0x11, Enums.Chapter.Birthright_Chapter18); AddBattlefield(0x12, Enums.Chapter.Birthright_Chapter19); AddBattlefield(0x13, Enums.Chapter.Birthright_Chapter20); AddBattlefield(0x14, Enums.Chapter.Birthright_Chapter21); AddBattlefield(0x15, Enums.Chapter.Birthright_Chapter22); AddBattlefield(0x16, Enums.Chapter.Birthright_Chapter23); AddBattlefield(0x17, Enums.Chapter.Birthright_Chapter24); AddBattlefield(0x18, Enums.Chapter.Birthright_Chapter25); AddBattlefield(0x19, Enums.Chapter.Birthright_Chapter26); AddBattlefield(0x1A, Enums.Chapter.Birthright_Chapter27); AddBattlefield(0x1B, Enums.Chapter.Birthright_Endgame); AddBattlefield(0x1C, Enums.Chapter.Paralogue1); AddBattlefield(0x1D, Enums.Chapter.Paralogue2); AddBattlefield(0x1E, Enums.Chapter.Paralogue3); AddBattlefield(0x1F, Enums.Chapter.Paralogue4); AddBattlefield(0x20, Enums.Chapter.Paralogue5); AddBattlefield(0x21, Enums.Chapter.Paralogue6); AddBattlefield(0x22, Enums.Chapter.Paralogue7); AddBattlefield(0x23, Enums.Chapter.Paralogue8); AddBattlefield(0x24, Enums.Chapter.Paralogue9); AddBattlefield(0x25, Enums.Chapter.Paralogue10); AddBattlefield(0x26, Enums.Chapter.Paralogue11); AddBattlefield(0x27, Enums.Chapter.Paralogue12); AddBattlefield(0x28, Enums.Chapter.Paralogue13); AddBattlefield(0x29, Enums.Chapter.Paralogue14); AddBattlefield(0x2A, Enums.Chapter.Birthright_Invasion1); AddBattlefield(0x2B, Enums.Chapter.Birthright_Invasion2); AddBattlefield(0x2C, Enums.Chapter.Birthright_Invasion3); AddBattlefield(0x2D, Enums.Chapter.DragonsGate); AddBattlefield(0x2E, Enums.Chapter.HeroBattle_Marth); AddBattlefield(0x2F, Enums.Chapter.HeroBattle_Ike); AddBattlefield(0x30, Enums.Chapter.HeroBattle_Lucina); AddBattlefield(0x31, Enums.Chapter.HeroBattle_Robin); } public void AddBirthrightSpecificStoryBattlefields() { AddBattlefield(0x05, Enums.Chapter.Birthright_Chapter6); AddBattlefield(0x06, Enums.Chapter.Birthright_Chapter7); AddBattlefield(0x07, Enums.Chapter.Birthright_Chapter8); AddBattlefield(0x08, Enums.Chapter.Birthright_Chapter9); AddBattlefield(0x09, Enums.Chapter.Birthright_Chapter10); AddBattlefield(0x0A, Enums.Chapter.Birthright_Chapter11); AddBattlefield(0x0B, Enums.Chapter.Birthright_Chapter12); AddBattlefield(0x0C, Enums.Chapter.Birthright_Chapter13); AddBattlefield(0x0D, Enums.Chapter.Birthright_Chapter14); AddBattlefield(0x0E, Enums.Chapter.Birthright_Chapter15); AddBattlefield(0x0F, Enums.Chapter.Birthright_Chapter16); AddBattlefield(0x10, Enums.Chapter.Birthright_Chapter17); AddBattlefield(0x11, Enums.Chapter.Birthright_Chapter18); AddBattlefield(0x12, Enums.Chapter.Birthright_Chapter19); AddBattlefield(0x13, Enums.Chapter.Birthright_Chapter20); AddBattlefield(0x14, Enums.Chapter.Birthright_Chapter21); AddBattlefield(0x15, Enums.Chapter.Birthright_Chapter22); AddBattlefield(0x16, Enums.Chapter.Birthright_Chapter23); AddBattlefield(0x17, Enums.Chapter.Birthright_Chapter24); AddBattlefield(0x18, Enums.Chapter.Birthright_Chapter25); AddBattlefield(0x19, Enums.Chapter.Birthright_Chapter26); AddBattlefield(0x1A, Enums.Chapter.Birthright_Chapter27); AddBattlefield(0x1B, Enums.Chapter.Birthright_Endgame); } public void AddConquestBattlefields() { AddBattlefield(0x00, Enums.Chapter.Chapter1); AddBattlefield(0x01, Enums.Chapter.Chapter2); AddBattlefield(0x02, Enums.Chapter.Chapter3); AddBattlefield(0x03, Enums.Chapter.Chapter4); AddBattlefield(0x04, Enums.Chapter.Chapter5); AddBattlefield(0x05, Enums.Chapter.Conquest_Chapter6); AddBattlefield(0x06, Enums.Chapter.Conquest_Chapter7); AddBattlefield(0x07, Enums.Chapter.Conquest_Chapter8); AddBattlefield(0x08, Enums.Chapter.Conquest_Chapter9); AddBattlefield(0x09, Enums.Chapter.Conquest_Chapter10); AddBattlefield(0x0A, Enums.Chapter.Conquest_Chapter11); AddBattlefield(0x0B, Enums.Chapter.Conquest_Chapter12); AddBattlefield(0x0C, Enums.Chapter.Conquest_Chapter13); AddBattlefield(0x0D, Enums.Chapter.Conquest_Chapter14); AddBattlefield(0x0E, Enums.Chapter.Conquest_Chapter15); AddBattlefield(0x0F, Enums.Chapter.Conquest_Chapter16); AddBattlefield(0x10, Enums.Chapter.Conquest_Chapter17); AddBattlefield(0x11, Enums.Chapter.Conquest_Chapter18); AddBattlefield(0x12, Enums.Chapter.Conquest_Chapter19); AddBattlefield(0x13, Enums.Chapter.Conquest_Chapter20); AddBattlefield(0x14, Enums.Chapter.Conquest_Chapter21); AddBattlefield(0x15, Enums.Chapter.Conquest_Chapter22); AddBattlefield(0x16, Enums.Chapter.Conquest_Chapter23); AddBattlefield(0x17, Enums.Chapter.Conquest_Chapter24); AddBattlefield(0x18, Enums.Chapter.Conquest_Chapter25); AddBattlefield(0x19, Enums.Chapter.Conquest_Chapter26); AddBattlefield(0x1A, Enums.Chapter.Conquest_Chapter27); AddBattlefield(0x1B, Enums.Chapter.Conquest_Endgame); AddBattlefield(0x1C, Enums.Chapter.Paralogue1); AddBattlefield(0x1D, Enums.Chapter.Paralogue2); AddBattlefield(0x1E, Enums.Chapter.Paralogue3); AddBattlefield(0x1F, Enums.Chapter.Paralogue4); AddBattlefield(0x20, Enums.Chapter.Paralogue5); AddBattlefield(0x21, Enums.Chapter.Paralogue6); AddBattlefield(0x22, Enums.Chapter.Paralogue15); AddBattlefield(0x23, Enums.Chapter.Paralogue16); AddBattlefield(0x24, Enums.Chapter.Paralogue17); AddBattlefield(0x25, Enums.Chapter.Paralogue18); AddBattlefield(0x26, Enums.Chapter.Paralogue19); AddBattlefield(0x27, Enums.Chapter.Paralogue20); AddBattlefield(0x28, Enums.Chapter.Paralogue21); AddBattlefield(0x29, Enums.Chapter.Paralogue22); AddBattlefield(0x2A, Enums.Chapter.Conquest_Invasion1); AddBattlefield(0x2B, Enums.Chapter.Conquest_Invasion2); AddBattlefield(0x2C, Enums.Chapter.Conquest_Invasion3); AddBattlefield(0x2D, Enums.Chapter.DragonsGate); AddBattlefield(0x2E, Enums.Chapter.HeroBattle_Marth); AddBattlefield(0x2F, Enums.Chapter.HeroBattle_Ike); AddBattlefield(0x30, Enums.Chapter.HeroBattle_Lucina); AddBattlefield(0x31, Enums.Chapter.HeroBattle_Robin); } public void AddRevelationBattlefields() { AddBattlefield(0x00, Enums.Chapter.Chapter1); AddBattlefield(0x01, Enums.Chapter.Chapter2); AddBattlefield(0x02, Enums.Chapter.Chapter3); AddBattlefield(0x03, Enums.Chapter.Chapter4); AddBattlefield(0x04, Enums.Chapter.Chapter5); AddBattlefield(0x05, Enums.Chapter.Revelation_Chapter6); AddBattlefield(0x06, Enums.Chapter.Revelation_Chapter7); AddBattlefield(0x07, Enums.Chapter.Revelation_Chapter8); AddBattlefield(0x08, Enums.Chapter.Revelation_Chapter9); AddBattlefield(0x09, Enums.Chapter.Revelation_Chapter10); AddBattlefield(0x0A, Enums.Chapter.Revelation_Chapter11); AddBattlefield(0x0B, Enums.Chapter.Revelation_Chapter12); AddBattlefield(0x0C, Enums.Chapter.Revelation_Chapter13); AddBattlefield(0x0D, Enums.Chapter.Revelation_Chapter14); AddBattlefield(0x0E, Enums.Chapter.Revelation_Chapter15); AddBattlefield(0x0F, Enums.Chapter.Revelation_Chapter16); AddBattlefield(0x10, Enums.Chapter.Revelation_Chapter17); AddBattlefield(0x11, Enums.Chapter.Revelation_Chapter18); AddBattlefield(0x12, Enums.Chapter.Revelation_Chapter19); AddBattlefield(0x13, Enums.Chapter.Revelation_Chapter20); AddBattlefield(0x14, Enums.Chapter.Revelation_Chapter21); AddBattlefield(0x15, Enums.Chapter.Revelation_Chapter22); AddBattlefield(0x16, Enums.Chapter.Revelation_Chapter23); AddBattlefield(0x17, Enums.Chapter.Revelation_Chapter24); AddBattlefield(0x18, Enums.Chapter.Revelation_Chapter25); AddBattlefield(0x19, Enums.Chapter.Revelation_Chapter26); AddBattlefield(0x1A, Enums.Chapter.Revelation_Chapter27); AddBattlefield(0x1B, Enums.Chapter.Revelation_Endgame); AddBattlefield(0x1C, Enums.Chapter.Paralogue1); AddBattlefield(0x1D, Enums.Chapter.Paralogue2); AddBattlefield(0x1E, Enums.Chapter.Paralogue3); AddBattlefield(0x1F, Enums.Chapter.Paralogue4); AddBattlefield(0x20, Enums.Chapter.Paralogue5); AddBattlefield(0x21, Enums.Chapter.Paralogue6); AddBattlefield(0x22, Enums.Chapter.Paralogue7); AddBattlefield(0x23, Enums.Chapter.Paralogue8); AddBattlefield(0x24, Enums.Chapter.Paralogue9); AddBattlefield(0x25, Enums.Chapter.Paralogue10); AddBattlefield(0x26, Enums.Chapter.Paralogue11); AddBattlefield(0x27, Enums.Chapter.Paralogue12); AddBattlefield(0x28, Enums.Chapter.Paralogue13); AddBattlefield(0x29, Enums.Chapter.Paralogue14); AddBattlefield(0x2A, Enums.Chapter.Paralogue15); AddBattlefield(0x2B, Enums.Chapter.Paralogue16); AddBattlefield(0x2C, Enums.Chapter.Paralogue17); AddBattlefield(0x2D, Enums.Chapter.Paralogue18); AddBattlefield(0x2E, Enums.Chapter.Paralogue19); AddBattlefield(0x2F, Enums.Chapter.Paralogue20); AddBattlefield(0x30, Enums.Chapter.Paralogue21); AddBattlefield(0x31, Enums.Chapter.Paralogue22); AddBattlefield(0x32, Enums.Chapter.Revelation_Invasion1); AddBattlefield(0x33, Enums.Chapter.Revelation_Invasion2); AddBattlefield(0x34, Enums.Chapter.Revelation_Invasion3); // Yes, these battlefieldIds are repeated in Revelation AddBattlefield(0x2D, Enums.Chapter.DragonsGate); AddBattlefield(0x2E, Enums.Chapter.HeroBattle_Marth); AddBattlefield(0x2F, Enums.Chapter.HeroBattle_Ike); AddBattlefield(0x30, Enums.Chapter.HeroBattle_Lucina); AddBattlefield(0x31, Enums.Chapter.HeroBattle_Robin); } private void RemoveRouteSpecificStoryBattlefields() { RemoveBattlefield(Enums.Chapter.Birthright_Chapter6); RemoveBattlefield(Enums.Chapter.Birthright_Chapter7); RemoveBattlefield(Enums.Chapter.Birthright_Chapter8); RemoveBattlefield(Enums.Chapter.Birthright_Chapter9); RemoveBattlefield(Enums.Chapter.Birthright_Chapter10); RemoveBattlefield(Enums.Chapter.Birthright_Chapter11); RemoveBattlefield(Enums.Chapter.Birthright_Chapter12); RemoveBattlefield(Enums.Chapter.Birthright_Chapter13); RemoveBattlefield(Enums.Chapter.Birthright_Chapter14); RemoveBattlefield(Enums.Chapter.Birthright_Chapter15); RemoveBattlefield(Enums.Chapter.Birthright_Chapter16); RemoveBattlefield(Enums.Chapter.Birthright_Chapter17); RemoveBattlefield(Enums.Chapter.Birthright_Chapter18); RemoveBattlefield(Enums.Chapter.Birthright_Chapter19); RemoveBattlefield(Enums.Chapter.Birthright_Chapter20); RemoveBattlefield(Enums.Chapter.Birthright_Chapter21); RemoveBattlefield(Enums.Chapter.Birthright_Chapter22); RemoveBattlefield(Enums.Chapter.Birthright_Chapter23); RemoveBattlefield(Enums.Chapter.Birthright_Chapter24); RemoveBattlefield(Enums.Chapter.Birthright_Chapter25); RemoveBattlefield(Enums.Chapter.Birthright_Chapter26); RemoveBattlefield(Enums.Chapter.Birthright_Chapter27); RemoveBattlefield(Enums.Chapter.Birthright_Endgame); RemoveBattlefield(Enums.Chapter.Conquest_Chapter6); RemoveBattlefield(Enums.Chapter.Conquest_Chapter7); RemoveBattlefield(Enums.Chapter.Conquest_Chapter8); RemoveBattlefield(Enums.Chapter.Conquest_Chapter9); RemoveBattlefield(Enums.Chapter.Conquest_Chapter10); RemoveBattlefield(Enums.Chapter.Conquest_Chapter11); RemoveBattlefield(Enums.Chapter.Conquest_Chapter12); RemoveBattlefield(Enums.Chapter.Conquest_Chapter13); RemoveBattlefield(Enums.Chapter.Conquest_Chapter14); RemoveBattlefield(Enums.Chapter.Conquest_Chapter15); RemoveBattlefield(Enums.Chapter.Conquest_Chapter16); RemoveBattlefield(Enums.Chapter.Conquest_Chapter17); RemoveBattlefield(Enums.Chapter.Conquest_Chapter18); RemoveBattlefield(Enums.Chapter.Conquest_Chapter19); RemoveBattlefield(Enums.Chapter.Conquest_Chapter20); RemoveBattlefield(Enums.Chapter.Conquest_Chapter21); RemoveBattlefield(Enums.Chapter.Conquest_Chapter22); RemoveBattlefield(Enums.Chapter.Conquest_Chapter23); RemoveBattlefield(Enums.Chapter.Conquest_Chapter24); RemoveBattlefield(Enums.Chapter.Conquest_Chapter25); RemoveBattlefield(Enums.Chapter.Conquest_Chapter26); RemoveBattlefield(Enums.Chapter.Conquest_Chapter27); RemoveBattlefield(Enums.Chapter.Conquest_Endgame); RemoveBattlefield(Enums.Chapter.Revelation_Chapter6); RemoveBattlefield(Enums.Chapter.Revelation_Chapter7); RemoveBattlefield(Enums.Chapter.Revelation_Chapter8); RemoveBattlefield(Enums.Chapter.Revelation_Chapter9); RemoveBattlefield(Enums.Chapter.Revelation_Chapter10); RemoveBattlefield(Enums.Chapter.Revelation_Chapter11); RemoveBattlefield(Enums.Chapter.Revelation_Chapter12); RemoveBattlefield(Enums.Chapter.Revelation_Chapter13); RemoveBattlefield(Enums.Chapter.Revelation_Chapter14); RemoveBattlefield(Enums.Chapter.Revelation_Chapter15); RemoveBattlefield(Enums.Chapter.Revelation_Chapter16); RemoveBattlefield(Enums.Chapter.Revelation_Chapter17); RemoveBattlefield(Enums.Chapter.Revelation_Chapter18); RemoveBattlefield(Enums.Chapter.Revelation_Chapter19); RemoveBattlefield(Enums.Chapter.Revelation_Chapter20); RemoveBattlefield(Enums.Chapter.Revelation_Chapter21); RemoveBattlefield(Enums.Chapter.Revelation_Chapter22); RemoveBattlefield(Enums.Chapter.Revelation_Chapter23); RemoveBattlefield(Enums.Chapter.Revelation_Chapter24); RemoveBattlefield(Enums.Chapter.Revelation_Chapter25); RemoveBattlefield(Enums.Chapter.Revelation_Chapter26); RemoveBattlefield(Enums.Chapter.Revelation_Chapter27); RemoveBattlefield(Enums.Chapter.Revelation_Endgame); } private void RemoveBattlefield(Enums.Chapter chapterId) { var battlefield = _chapterSave.BattlefieldRegion.Battlefields.Where(x => x.ChapterID == chapterId).FirstOrDefault(); if (battlefield != null) _chapterSave.BattlefieldRegion.Battlefields.Remove(battlefield); } private void AddBattlefield(byte battlefieldId, Enums.Chapter chapterId) { var raw = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF }; var battlefield = new Battlefield(raw); battlefield.BattlefieldID = battlefieldId; battlefield.ChapterID = chapterId; _chapterSave.BattlefieldRegion.Battlefields.Add(battlefield); } } }
412
0.553443
1
0.553443
game-dev
MEDIA
0.964841
game-dev
0.901958
1
0.901958
LIKO-12/LIKO-12
14,925
src/OS/DiskOS/Editors/init.lua
--This file is responsible about the editors shown after pressing escape-- local edit = {} --=Contributing Guide=-- --[[ Creating an editor: 1. Create a new file at Editors folder 2. Make a new table at the top of the file and add it as an return value in the file ex: local ce = {}; return ce 3. Edit self.editors in edit:initialize and change the name of a slot to the name of .lua file of your editor (without adding the .lua) 4. Edit self.saveid in edit:initialize and change the value of a slot to a save id for your editor, leave -1 if it doesn't save. * The editor api is passed as an argument to the editor file, to access it add this to the top of your file: local eapi = (...) * The only usefull function in the editor api is eapi:drawUI() which clears the whole screen and draws the top and bottom bars of every editor Besure to call this at editor:entered() * editor:entered() is called when the user switches to your editor The first argument passed tk this callback is the previos editor table, be warned it could be a nil when yur editor is the first to be chosed ! The rest arguments are the return values of oldeditor:leaved() Be sure to call eapi:drawUI() here to clear the screen * editor:leaved() is called when the user is switching to an other editor than your The first argument is the table of the new editor You can return values that are passed to editor:entered() [see above] * editor:export() is called when the editors are saving the data to a disk, you must pass a string of the editor data that may be loaded later at editor:import see down V * editor:import(data) is called when the editors are loading from a disk, you will be passed the data string the editor passed in editor:export it won't be called if there is no data to load. * You don't have to do the while loop in your editor (see written editors) The editor api automatically handles the pullEvent() for you When an event happens editor:"event name" is called with the arguments of the event, ex: function editor:mousepressed(x,y, button, is touch) end function editor:update(dt) end * editor.keymap = {} here you can assign your key binds: editor.keymap["backspace"] = function(self,isrepeat) end The key name can be any love2d key constant or and scancode You can combine it with ctrl, alt or shift, ex: editor.keymap["ctrl-c"] * Note when reading existing editors: The may use some api functions defined at DiskOS/System/api.lua Good luck ! ==Contributors to this file== (Add your name when contributing to this file) - Rami Sabbagh (RamiLego4Game) ]] local swidth, sheight = screenSize() --WIP new editors system function edit:initialize() self.flavor = 9 --Orange self.flavorBack = 4 --Brown self.background = 5 --Dark Grey self.active = 4 --Active editor self.editors = {"music","sfx","tile","sprite","code"; music=1,sfx=2,tile=3,sprite=4,code=5} self.saveid = {-1,"sfx","tilemap","spritesheet","luacode"; sfx=2,tilemap=3,spritesheet=4,luacode=5} self.chunks = {} --Editors Code Chunks self.leditors = {} --Loaded editors (Executed chunks) self.icons = imagedata(5*8,2*8) self.icons:paste(_SystemSheet.img:data(),0,0, (24-#self.editors)*8,0, #self.editors*8,8) self.icons:paste(_SystemSheet.img:data(),0,8, (24-#self.editors)*8,0, #self.editors*8,8) self.icons:map(function(x,y,c) if y < 8 then if c == 0 then return self.flavor else return self.flavorBack end; else if c == 0 then return self.flavorBack else return self.flavor end; end end) self.icons = self.icons:image() self.iconsBGQuad = self.icons:quad(0,0,self.icons:width(),8) self.iconsQuads = {} for i=1,#self.editors do table.insert(self.iconsQuads,self.icons:quad(self.icons:width()-i*8,8, 8,8)) end local editors = {"soon","sfx","tile","sprite","code","soon"} --List of built-in editors to create chunks of for k, v in ipairs(editors) do --Load chunks local chunk, err = fs.load(_SystemDrive..":/Editors/"..v..".lua") if not chunk then error(err or "Error loading: "..tostring(v)) end table.insert(self.chunks,k,chunk) end self:clearData() self.modeGrid = {swidth-(#self.editors*8),0,#self.editors*8,8,#self.editors,1} --The editor selection grid self.modeGridFlag = false self.modeGridHover = false self.apiVersion = _APIVer --The used API end function edit:addEditor(code, name, saveid, icon) --Verification if type(code) ~= "string" and type(code) ~= "function" then return error("The editor code must be a string or a chunk, provided: "..type(code)) end if type(name) ~= "string" then return error("Editor name must be a string, provided: "..type(name)) end if type(saveid) ~= "number" and type(saveid) ~= "string" then return error("The saveid must be -1 or a string, provided: "..type(saveid)) end if type(saveid) == "number" and saveid ~= -1 then return error("The saveid can be -1 or a string, provided: "..saveid) end if type(icon) ~= "table" then return error("Icon must be provided, got "..type(icon).." instead") end if not (icon.typeOf and icon.type) then return error("Invalid Icon") end if icon:type() == "GPU.image" then icon = icon:data() end if icon:type() ~= "GPU.imageData" then return error("Icon must be a GPU image or imagedata !, provided: "..icon:type()) end --Chunk creation local chunk, err = code, "Unknown Error" if type(code) == "string" then chunk = false chunk, err = loadstring(code) end if not chunk then return error("Failed to load the chunk: "..tostring(err)) end --Execute the chunk local ok, editor = pcall(chunk,self) if not ok then return error("Failed to execute the chunk: "..tostring(editor)) end --Proccess the icon local bgicon = imagedata(8,8):paste(icon) local fgicon = imagedata(8,8):paste(icon) bgicon:map(function(x,y,c) if c == 0 then return self.flavor else return self.flavorBack end end) fgicon:map(function(x,y,c) if c == 0 then return self.flavorBack else return self.flavor end end) local newicons = imagedata(self.icons:width()+8,16) newicons:paste(self.icons:data(),8,0) newicons:paste(bgicon,0,0):paste(fgicon,0,8) self.icons = newicons:image() self.iconsBGQuad = self.icons:quad(0,0,self.icons:width(),8) for k,quad in ipairs(self.iconsQuads) do local oldx,oldy = quad:getViewport() self.iconsQuads[k] = self.icons:quad(oldx+8,oldy,8,8) end table.insert(self.iconsQuads,self.icons:quad(0,8,8,8)) --Register the editor table.insert(self.editors,name) self.editors[name] = #self.editors table.insert(self.saveid,saveid) self.saveid[saveid] = #self.saveid table.insert(self.chunks,chunk) table.insert(self.leditors,editor) --Update the mode grid self.modeGrid = {swidth-(#self.editors*8),0,#self.editors*8,8,#self.editors,1} end function edit:clearData() --Will restart the editors simply self.leditors = {} for k,v in ipairs(self.chunks) do local editor = v(self) self.leditors[k] = editor end end function edit:drawBottomBar() rect(0,sheight-8,swidth,8,false,self.flavor) end function edit:drawTopBar() rect(0,0,swidth,8,false,self.flavor) SpriteGroup(55, 0,0, 4,1, 1,1, false, _SystemSheet) --The LIKO12 Logo self.icons:draw((swidth-#self.editors*8),0, 0, 1,1, self.iconsBGQuad) self.icons:draw(swidth-self.active*8,0, 0, 1,1, self.iconsQuads[self.active]) end function edit:drawUI() clear(self.background) --Clear the screen self:drawTopBar() --Draw the top bar self:drawBottomBar() --Draw the bottom bar end function edit:switchEditor(neweditor) if neweditor ~= self.active and self.leditors[neweditor] then local oldeditor = self.active; self.active = neweditor if self.leditors[neweditor].entered then if self.leditors[oldeditor].leaved then self.leditors[neweditor]:entered(self.leditors[oldeditor],self.leditors[oldeditor]:leaved(self.leditors[neweditor])) else self.leditors[neweditor]:entered(self.leditors[oldeditor]) end else if self.leditors[oldeditor].leaved then self.leditors[oldeditor]:leaved(self.leditors[neweditor]) end end end end function edit:export() --Export editors data local edata = {} for k = #self.saveid, 1, -1 do local v = self.saveid[k] if v ~= -1 and self.leditors[k].export then local data = self.leditors[k]:export() if type(data) ~= "nil" then edata[v] = data end end end return edata end function edit:import(edata) for saveId, saveData in pairs(edata) do local editorId = self.saveid[saveId] if editorId and self.leditors[editorId].import then self.leditors[editorId]:import(saveData) end end end function edit:encode() --Encode editors data into binary local edata = {} for k = #self.saveid, 1, -1 do local v = self.saveid[k] if v ~= -1 and self.leditors[k].encode then local data = self.leditors[k]:encode() if type(data) ~= "nil" then edata[v] = data end end end return edata end function edit:decode(edata) --Decode editors data from binary for saveId, saveData in pairs(edata) do local editorId = self.saveid[saveId] if editorId and self.leditors[editorId].decode then self.leditors[editorId]:decode(saveData) end end end function edit:loop() --Starts the while loop cursor("normal") if self.leditors[self.active]["entered"] then self.leditors[self.active]:entered() end while true do local event, a, b, c, d, e, f = pullEvent() if event == "keypressed" then if a == "escape" then --Quit the loop and return to the terminal if self.leditors[self.active]["leaved"] then self.leditors[self.active]:leaved() end break else local key, sc = a, b if(isKDown("lalt", "ralt")) then key = "alt-" .. key sc = "alt-" .. sc end if(isKDown("lctrl", "rctrl")) then key = "ctrl-" .. key sc = "ctrl-" .. sc end if(isKDown("lshift", "rshift")) then key = "shift-" .. key sc = "shift-" .. sc end local term = require("terminal") local hotkey --Was it an hotkey ? pushMatrix() pushPalette() pushColor() if key == "ctrl-s" then local oldprint = print local oldinput = TextUtils.textInput local err print = function(msg) if color() == 8 and not err then err = msg end end TextUtils.textInput = function() return "y" end if not self.filePath then err = "Missing save name !" else local exitCode, exitErr = term.execute("save") if exitCode == 1 then err = "Failed: "..exitErr elseif exitCode == 2 or exitCode == 3 then err = "Failed, type save in terminal for info" elseif exitCode == 4 then err = "Save command not found !" end end if err and err:len() > 4 then _systemMessage(err,5,9,4) else _systemMessage("Saved successfully",1) end print = oldprint TextUtils.textInput = oldinput hotkey = true elseif key == "ctrl-l" then local oldprint = print local err print = function(msg) if color() == 9 and not err then err = msg end end if not self.filePath then err = "Missing save name !" else term.execute("load") end if err and err:len() > 4 then _systemMessage(err,5,9,4) else _systemMessage("Reloaded successfully",1) end print = oldprint hotkey = true elseif key == "ctrl-r" then term.ecommand("run") if self.leditors[self.active]["leaved"] then self.leditors[self.active]:leaved() end hotkey = true break end popMatrix() popPalette() popColor() if key == "alt-left" then if self.active == #self.editors then self:switchEditor(1) else self:switchEditor(self.active+1) end hotkey = true elseif key == "alt-right" then if self.active == 1 then self:switchEditor(#self.editors) else self:switchEditor(self.active-1) end hotkey = true end if self.leditors[self.active].keymap and not hotkey then local usedKey if self.leditors[self.active].keymap[key] then usedKey = key elseif self.leditors[self.active].keymap["sc_"..sc] then usedKey = "sc_"..sc end if usedKey then self.leditors[self.active].keymap[usedKey](self.leditors[self.active], c) self.leditors[self.active].lastKey = usedKey end end if self.leditors[self.active][event] and not hotkey then self.leditors[self.active][event](self.leditors[self.active],a,b,c,d,e,f) end end elseif event == "mousepressed" then local cx, cy = whereInGrid(a,b, self.modeGrid) if cx then self.modeGridFlag = true cursor("handpress") self:switchEditor(#self.editors-cx+1) else if self.leditors[self.active][event] then self.leditors[self.active][event](self.leditors[self.active],a,b,c,d,e,f) end end elseif event == "mousemoved" then local cx, cy = whereInGrid(a,b, self.modeGrid) if cx then if self.modeGridFlag then self:switchEditor(#self.editors-cx+1) else self.modeGridHover = true cursor("handrelease") end elseif not self.modeGridFlag then if self.modeGridHover then cursor("normal") self.modeGridHover = false end if self.leditors[self.active][event] then self.leditors[self.active][event](self.leditors[self.active],a,b,c,d,e,f) end else cursor("handpress") end elseif event == "mousereleased" then local cx, cy = whereInGrid(a,b, self.modeGrid) if cx then if self.modeGridFlag then self.modeGridHover = true self.modeGridFlag = false cursor("handrelease") self:switchEditor(#self.editors-cx+1) end else if self.modeGridFlag then self.modeGridHover = true self.modeGridFlag = false cursor("normal") end if self.leditors[self.active][event] then self.leditors[self.active][event](self.leditors[self.active],a,b,c,d,e,f) end end else if self.leditors[self.active][event] then self.leditors[self.active][event](self.leditors[self.active],a,b,c,d,e,f) end end end end edit:initialize() return edit
412
0.941053
1
0.941053
game-dev
MEDIA
0.568076
game-dev,desktop-app
0.980766
1
0.980766
oiuv/mud
3,044
kungfu/skill/tianzhu-jian/suo.c
#include <ansi.h> #include <combat.h> #define SUO "「" HIW "烟云锁身" NOR "」" inherit F_SSERVER; int perform(object me, object target) { string msg, wp, wp2; object weapon, weapon2; int ap, dp; if (userp(me) && ! me->query("can_perform/tianzhu-jian/suo")) return notify_fail("你所使用的外功中没有这种功能。\n"); if (! target) target = offensive_target(me); if (! target || ! me->is_fighting(target)) return notify_fail(SUO "只能对战斗中的对手使用。\n"); if (! objectp(weapon = me->query_temp("weapon")) || (string)weapon->query("skill_type") != "sword") return notify_fail("你使用的武器不对,难以施展" SUO "。\n"); if (target->is_busy()) return notify_fail(target->name() + "目前正自顾不暇,放胆攻击吧。\n"); if ((int)me->query_skill("tianzhu-jian", 1) < 120) return notify_fail("你天柱剑法不够娴熟,难以施展" SUO "。\n"); if (me->query_skill_mapped("sword") != "tianzhu-jian") return notify_fail("你没有激发天柱剑法,难以施展" SUO "。\n"); if (me->query_skill("dodge") < 150) return notify_fail("你的轻功修为不够,难以施展" SUO "。\n"); if ((int)me->query("neili") < 200) return notify_fail("你现在的真气不够,难以施展" SUO "。\n"); if (! living(target)) return notify_fail("对方都已经这样了,用不着这么费力吧?\n"); wp = weapon->name(); ap = me->query_skill("tianzhu-jian", 1); dp = target->query_skill("parry", 1); if (me->query("max_neili") > target->query("max_neili") * 3 / 2 && objectp(weapon2 = target->query_temp("weapon"))) { wp2 = weapon2->name(); msg = HIW "\n$N" HIW "剑法陡然变快,施展出「烟云锁身剑」,手中" + wp + HIW "幻作一道白芒,撩向$n" HIW "所持的" + wp2 + HIW "。" NOR; message_sort(msg, me, target); me->start_busy(2); me->add("neili", -200); if (random(ap) > dp / 2) { msg = HIR "$n" HIR "只见眼前白芒暴涨,登时右手一轻," + wp2 + HIR "竟脱手飞出。\n" NOR; target->start_busy(3); weapon2->move(environment(target)); } else { msg += CYN "可是$n" CYN "看破$N" CYN "剑法中的虚招,镇" "定自如,从容应对。\n" NOR; } } else { msg = HIC "\n$N" HIC "剑法陡然变快,施展出「" HIW "烟云锁身剑" HIC "」,手中" + wp + HIC "剑光夺目,欲将$n" HIC "笼罩在" "剑光之中。" NOR; me->start_busy(1); me->add("neili", -100); if (random(ap) > dp / 2) { msg += HIR "\n$n" HIR "惊慌不定,顿时乱了阵脚,竟被困于$N" HIR "的剑光当中。" NOR; target->start_busy(ap / 25 + 1); } else { msg += CYN "\n可是$n" CYN "看破$N" CYN "剑法中的虚招,镇" "定自如,从容应对。" NOR; } } message_combatd(msg, me, target); return 1; }
412
0.883113
1
0.883113
game-dev
MEDIA
0.881112
game-dev
0.869934
1
0.869934
HbmMods/Hbm-s-Nuclear-Tech-GIT
1,573
src/main/java/com/hbm/items/tool/ItemModBucket.java
package com.hbm.items.tool; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.init.Blocks; import net.minecraft.item.ItemBucket; import net.minecraft.world.World; public class ItemModBucket extends ItemBucket { protected int overrideFluidMeta = 0; protected Block containedFluid; public ItemModBucket(Block fluid) { super(fluid); this.containedFluid = fluid; } public ItemModBucket(Block fluid, int meta) { this(fluid); this.overrideFluidMeta = meta; } @Override public boolean tryPlaceContainedLiquid(World world, int x, int y, int z) { if(this.containedFluid == Blocks.air) { return false; } else { Material material = world.getBlock(x, y, z).getMaterial(); boolean flag = !material.isSolid(); if(!world.isAirBlock(x, y, z) && !flag) { return false; } else { if(world.provider.isHellWorld && this.containedFluid == Blocks.flowing_water) { world.playSoundEffect((double) ((float) x + 0.5F), (double) ((float) y + 0.5F), (double) ((float) z + 0.5F), "random.fizz", 0.5F, 2.6F + (world.rand.nextFloat() - world.rand.nextFloat()) * 0.8F); for(int l = 0; l < 8; ++l) { world.spawnParticle("largesmoke", (double) x + Math.random(), (double) y + Math.random(), (double) z + Math.random(), 0.0D, 0.0D, 0.0D); } } else { if(!world.isRemote && flag && !material.isLiquid()) { world.func_147480_a(x, y, z, true); } world.setBlock(x, y, z, this.containedFluid, overrideFluidMeta, 3); } return true; } } } }
412
0.748235
1
0.748235
game-dev
MEDIA
0.981405
game-dev
0.897546
1
0.897546
Krozark/SFML-book
7,699
extlibs/SFGUI/src/SFGUI/Table.cpp
#include <SFGUI/Table.hpp> #include <SFGUI/Context.hpp> #include <SFGUI/Engine.hpp> #include <set> #include <cassert> namespace sfg { Table::Ptr Table::Create() { return std::make_shared<Table>(); } sf::Vector2f Table::CalculateRequisition() { float gap( Context::Get().GetEngine().GetProperty<float>( "Gap", shared_from_this() ) ); sf::Vector2f size( 2 * gap, 2 * gap ); UpdateRequisitions(); // Count requisitions of columns and rows. for( const auto& column : m_columns ) { size.x += column.requisition; } for( const auto& row : m_rows ) { size.y += row.requisition; } return size; } void Table::Attach( Widget::Ptr widget, const sf::Rect<sf::Uint32>& rect, int x_options, int y_options, const sf::Vector2f& padding ) { assert( rect.width > 0 ); assert( rect.height > 0 ); // Store widget in a table cell object. priv::TableCell cell( widget, rect, x_options, y_options, padding ); m_cells.push_back( cell ); // Check if we need to enlarge rows/columns. if( rect.left + rect.width >= m_columns.size() ) { std::size_t old_size( m_columns.size() ); m_columns.resize( rect.left + rect.width ); // Set default spacings. for( std::size_t col_index = old_size; col_index < m_columns.size(); ++col_index ) { m_columns[col_index].spacing = m_general_spacings.x; } } if( rect.top + rect.height >= m_rows.size() ) { std::size_t old_size( m_rows.size() ); m_rows.resize( rect.top + rect.height ); // Set default spacings. for( std::size_t row_index = old_size; row_index < m_rows.size(); ++row_index ) { m_rows[row_index].spacing = m_general_spacings.y; } } // Add widget to container. Add( widget ); // Request new size. RequestResize(); } void Table::HandleSizeChange() { AllocateChildren(); } void Table::UpdateRequisitions() { // Reset requisitions and expand flags, at first. for( auto& column : m_columns ) { column.requisition = 0.f; column.allocation = 0.f; column.expand = false; } for( auto& row : m_rows ) { row.requisition = 0.f; row.allocation = 0.f; row.expand = false; } // Iterate over children and add requisitions to columns and rows. for( const auto& cell : m_cells ) { auto col_requisition = cell.child->GetRequisition().x / static_cast<float>( cell.rect.width ) + 2 * cell.padding.x; auto col_bound = cell.rect.left + cell.rect.width; for( sf::Uint32 col_idx = cell.rect.left; col_idx < col_bound; ++col_idx ) { m_columns[col_idx].requisition = std::max( m_columns[col_idx].requisition, col_requisition + (col_idx + 1 < m_columns.size() ? m_columns[col_idx].spacing : 0) // Add spacing if not last column. ); // Set expand flag. if( (cell.x_options & EXPAND) == EXPAND ) { m_columns[col_idx].expand = true; } } auto row_requisition = cell.child->GetRequisition().y / static_cast<float>( cell.rect.height ) + 2 * cell.padding.y; auto row_bound = cell.rect.top + cell.rect.height; for( sf::Uint32 row_idx = cell.rect.top; row_idx < row_bound; ++row_idx ) { m_rows[row_idx].requisition = std::max( m_rows[row_idx].requisition, row_requisition + (row_idx + 1 < m_rows.size() ? m_rows[row_idx].spacing : 0) // Add spacing if not last row. ); // Set expand flag. if( (cell.y_options & EXPAND) == EXPAND ) { m_rows[row_idx].expand = true; } } } AllocateChildren(); } void Table::AllocateChildren() { auto gap = Context::Get().GetEngine().GetProperty<float>( "Gap", shared_from_this() ); // Calculate column allocations. auto total_width = GetAllocation().width - 2 * gap; std::size_t num_expand = 0; // First step is counting number of expandable columns and setting allocation // to requisition. for( auto& column : m_columns ) { if( column.expand ) { ++num_expand; } column.allocation = column.requisition; total_width -= column.allocation; } // Next step is distribution of remaining width (i.e. extra width given by // parent) to expandable columns. Also calculate column positions. auto extra_width = (num_expand > 0 ? total_width / static_cast<float>( num_expand ) : 0 ); for( std::size_t col_idx = 0; col_idx < m_columns.size(); ++col_idx ) { auto& col = m_columns[col_idx]; if( col.expand ) { col.allocation += extra_width; } if( col_idx == 0 ) { col.position = 0; } else { col.position = m_columns[col_idx - 1].position + m_columns[col_idx - 1].allocation; } } // Calculate row allocations. auto total_height = 2 * gap + GetAllocation().height; num_expand = 0; // First step is counting number of expandable rows and setting allocation // to requisition. for( auto& row : m_rows ) { if( row.expand ) { ++num_expand; } row.allocation = row.requisition; total_height -= row.allocation; } // Next step is distribution of remaining height (i.e. extra height given by // parent) to expandable rows. Also calculate rows positions. auto extra_height = (num_expand > 0 ? total_height / static_cast<float>( num_expand ) : 0 ); for( std::size_t row_idx = 0; row_idx < m_rows.size(); ++row_idx ) { auto& row = m_rows[row_idx]; if( row.expand ) { row.allocation += extra_height; } if( row_idx == 0 ) { row.position = 0; } else { row.position = m_rows[row_idx - 1].position + m_rows[row_idx - 1].allocation; } } // Last step: Allocate children. std::size_t bound = 0; for( const auto& cell : m_cells ) { sf::FloatRect allocation( m_columns[cell.rect.left].position, m_rows[cell.rect.top].position, 0, 0 ); bound = cell.rect.left + cell.rect.width; for( std::size_t col_idx = cell.rect.left; col_idx < bound; ++col_idx ) { allocation.width += m_columns[col_idx].allocation; if( col_idx + 1 == bound && col_idx + 1 < m_columns.size() ) { allocation.width -= m_columns[col_idx].spacing; } } bound = cell.rect.top + cell.rect.height; for( std::size_t row_idx = cell.rect.top; row_idx < bound; ++row_idx ) { allocation.height += m_rows[row_idx].allocation; if( row_idx + 1 == bound && row_idx + 1 < m_rows.size() ) { allocation.height -= m_rows[row_idx].spacing; } } // Limit size if FILL is not set. if( (cell.x_options & FILL) != FILL ) { allocation.width = std::min( allocation.width, cell.child->GetRequisition().x ); } if( (cell.y_options & FILL) != FILL ) { allocation.height = std::min( allocation.height, cell.child->GetRequisition().y ); } cell.child->SetAllocation( allocation ); } } void Table::SetColumnSpacings( float spacing ) { for( auto& column : m_columns ) { column.spacing = spacing; } m_general_spacings.x = spacing; UpdateRequisitions(); RequestResize(); } void Table::SetRowSpacings( float spacing ) { for( auto& row : m_rows ) { row.spacing = spacing; } m_general_spacings.y = spacing; UpdateRequisitions(); RequestResize(); } void Table::SetColumnSpacing( std::size_t index, float spacing ) { if( index >= m_columns.size() ) { return; } m_columns[index].spacing = spacing; UpdateRequisitions(); RequestResize(); } void Table::SetRowSpacing( std::size_t index, float spacing ) { if( index >= m_rows.size() ) { return; } m_rows[index].spacing = spacing; UpdateRequisitions(); RequestResize(); } const std::string& Table::GetName() const { static const std::string name( "Table" ); return name; } void Table::HandleRequisitionChange() { AllocateChildren(); } void Table::HandleRemove( Widget::Ptr child ) { TableCellList::iterator cell_iter( m_cells.begin() ); TableCellList::iterator cell_iter_end( m_cells.end() ); for( ; cell_iter != cell_iter_end; ++cell_iter ) { if( cell_iter->child == child ) { m_cells.erase( cell_iter ); return; } } } }
412
0.970862
1
0.970862
game-dev
MEDIA
0.345267
game-dev
0.987622
1
0.987622
eccentricdevotion/TARDIS
5,591
src/main/java/me/eccentric_nz/tardisweepingangels/monsters/daleks/DalekEquipment.java
/* * Copyright (C) 2025 eccentric_nz * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.eccentric_nz.tardisweepingangels.monsters.daleks; import me.eccentric_nz.TARDIS.TARDIS; import me.eccentric_nz.TARDIS.TARDISConstants; import me.eccentric_nz.TARDIS.custommodels.keys.DalekVariant; import me.eccentric_nz.tardisweepingangels.TARDISWeepingAngels; import me.eccentric_nz.tardisweepingangels.utils.Monster; import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.NamespacedKey; import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.LivingEntity; import org.bukkit.inventory.EntityEquipment; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.persistence.PersistentDataType; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; public class DalekEquipment { public static void set(LivingEntity le, boolean disguise) { le.getPersistentDataContainer().set(TARDISWeepingAngels.DALEK, PersistentDataType.INTEGER, Monster.DALEK.ordinal()); ItemStack helmet = ItemStack.of(Material.SLIME_BALL, 1); ItemMeta headMeta = helmet.getItemMeta(); headMeta.displayName(Component.text("Dalek Head")); headMeta.setItemModel(getRandomModel()); helmet.setItemMeta(headMeta); EntityEquipment ee = le.getEquipment(); ee.setHelmet(helmet); ee.setChestplate(null); ee.setLeggings(null); ee.setBoots(null); Bukkit.getScheduler().scheduleSyncDelayedTask(TARDIS.plugin, () -> { PotionEffect invisibility = new PotionEffect(PotionEffectType.INVISIBILITY, Integer.MAX_VALUE, 1, true, false); le.addPotionEffect(invisibility); PotionEffect resistance = new PotionEffect(PotionEffectType.FIRE_RESISTANCE, 360000, 3, true, false); le.addPotionEffect(resistance); }); if (!disguise) { ee.setHelmetDropChance(0); ItemStack bow = ItemStack.of(Material.BOW, 1); ItemMeta bim = bow.getItemMeta(); bim.setItemModel(DalekVariant.DALEK_BOW.getKey()); bow.setItemMeta(bim); ee.setItemInMainHand(bow); ee.setItemInMainHandDropChance(0); Bukkit.getScheduler().scheduleSyncDelayedTask(TARDIS.plugin, () -> { PotionEffect resistance = new PotionEffect(PotionEffectType.RESISTANCE, 360000, 1, true, false); le.addPotionEffect(resistance); AttributeInstance attribute = le.getAttribute(Attribute.MAX_HEALTH); attribute.setBaseValue(30.0d); le.setHealth(30.0d); le.setCanPickupItems(false); le.setRemoveWhenFarAway(false); le.setPersistent(true); }); } } private static NamespacedKey getRandomModel() { if (TARDISConstants.RANDOM.nextBoolean()) { return DalekVariant.DALEK_BRASS.getKey(); } else { switch (TARDISConstants.RANDOM.nextInt(1, 17)) { case 1 -> { return DalekVariant.DALEK_WHITE.getKey(); } case 2 -> { return DalekVariant.DALEK_ORANGE.getKey(); } case 3 -> { return DalekVariant.DALEK_MAGENTA.getKey(); } case 4 -> { return DalekVariant.DALEK_LIGHT_BLUE.getKey(); } case 5 -> { return DalekVariant.DALEK_YELLOW.getKey(); } case 6 -> { return DalekVariant.DALEK_LIME.getKey(); } case 7 -> { return DalekVariant.DALEK_PINK.getKey(); } case 8 -> { return DalekVariant.DALEK_GRAY.getKey(); } case 9 -> { return DalekVariant.DALEK_LIGHT_GRAY.getKey(); } case 10 -> { return DalekVariant.DALEK_CYAN.getKey(); } case 11 -> { return DalekVariant.DALEK_BLUE.getKey(); } case 12 -> { return DalekVariant.DALEK_PURPLE.getKey(); } case 13 -> { return DalekVariant.DALEK_GREEN.getKey(); } case 14 -> { return DalekVariant.DALEK_BROWN.getKey(); } case 15 -> { return DalekVariant.DALEK_RED.getKey(); } case 16 -> { return DalekVariant.DALEK_BLACK.getKey(); } } } return DalekVariant.DALEK_BRASS.getKey(); } }
412
0.751768
1
0.751768
game-dev
MEDIA
0.780362
game-dev
0.954059
1
0.954059
markol/machines
1,642
include/libdev/machgui/dbhandlr.hpp
/* * D B H A N D L R . H P P * (c) Charybdis Limited, 1998. All Rights Reserved */ /* MachGuiDatabaseHandler Provides an interface for the functionality needed between the player database and machlog. */ #ifndef _MACHGUI_DBHANDLR_HPP #define _MACHGUI_DBHANDLR_HPP #include "base/base.hpp" #include "machlog/dbhandlr.hpp" class MachGuiDatabaseHandler : public MachLogDatabaseHandler // Canonical form revoked { public: MachGuiDatabaseHandler(); ~MachGuiDatabaseHandler(); ///////////////////////////////////////////// // Inherited from Machlog // Return a production unit list for the machines surviving for the specified arc at the // end of the named scenario (for current player) virtual const Units& survivingUnits( MachPhys::Race race, const string& scenarioName ) const; //true if the named flag was set by the current player during the named scenario virtual bool isFlagSet( const string& flag, const string& scenarioName ) const; //The number of sub-tasks if any defined in the current scenario virtual uint nTasksInCurrentScenario() const; //True iff the index'th task of the current task is available from the start virtual bool taskStartsAvailable( uint index ) const; ///////////////////////////////////////////// void CLASS_INVARIANT; private: friend ostream& operator <<( ostream& o, const MachGuiDatabaseHandler& t ); MachGuiDatabaseHandler( const MachGuiDatabaseHandler& ); MachGuiDatabaseHandler& operator =( const MachGuiDatabaseHandler& ); }; #endif /* End DBHANDLR.HPP *************************************************/
412
0.971773
1
0.971773
game-dev
MEDIA
0.519106
game-dev
0.68643
1
0.68643
WolfyScript/viewportl
4,116
spigot/src/main/kotlin/com/wolfyscript/viewportl/spigot/gui/inventoryui/interaction/InventoryUIListener.kt
/* * viewportl - multiplatform GUI framework to easily create reactive GUIs * Copyright (C) 2024 WolfyScript * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.wolfyscript.viewportl.spigot.gui.inventoryui.interaction import com.google.common.collect.Multimap import com.google.common.collect.Multimaps import com.wolfyscript.viewportl.common.gui.reactivity.ReactiveGraph import com.wolfyscript.viewportl.gui.GuiHolder import com.wolfyscript.viewportl.gui.ViewRuntime import com.wolfyscript.viewportl.spigot.gui.inventoryui.BukkitInventoryGuiHolder import org.bukkit.event.EventHandler import org.bukkit.event.EventPriority import org.bukkit.event.Listener import org.bukkit.event.inventory.InventoryClickEvent import org.bukkit.event.inventory.InventoryCloseEvent import org.bukkit.event.inventory.InventoryDragEvent import org.bukkit.inventory.InventoryHolder import org.bukkit.inventory.ItemStack class InventoryUIListener(val runtime: ViewRuntime<*, SpigotInvUIInteractionHandler>) : Listener { private fun withHolder(holder: InventoryHolder?, fn: GuiHolder.() -> Unit) { if (holder is BukkitInventoryGuiHolder && holder.guiHolder.viewManager == runtime) { fn(holder.guiHolder) } } @EventHandler(priority = EventPriority.HIGHEST) fun onInvClick(event: InventoryClickEvent) { withHolder(event.inventory.holder) { val valueHandler = ValueHandler() runtime.interactionHandler.onClick(event, valueHandler) event.isCancelled = true runtime.viewportl.scafall.scheduler.syncTask(runtime.viewportl.scafall.corePlugin) { (runtime.reactiveSource as ReactiveGraph).runEffects() } } } @EventHandler(priority = EventPriority.HIGH) fun onItemDrag(event: InventoryDragEvent) { withHolder(event.inventory.holder) { if (event.rawSlots.stream() .anyMatch { rawSlot -> event.view.getInventory(rawSlot) != event.view.topInventory } ) { event.isCancelled = true return@withHolder } if (runtime.window == null) return@withHolder val valueHandler = ValueHandler() runtime.interactionHandler.onDrag(event, valueHandler) if (!event.isCancelled) { runtime.viewportl.scafall.scheduler.syncTask(runtime.viewportl.scafall.corePlugin) { for (rawSlot in event.rawSlots) { if (rawSlot < event.inventory.size) { valueHandler.callSlotValueUpdate(rawSlot, event.inventory.getItem(rawSlot)) } } } } runtime.viewportl.scafall.scheduler.syncTask(runtime.viewportl.scafall.corePlugin) { (runtime.reactiveSource as ReactiveGraph).runEffects() } } } @EventHandler(priority = EventPriority.HIGH) fun onClose(event: InventoryCloseEvent) { withHolder(event.inventory.holder) { runtime.window?.apply { close() } } } } data class ValueHandler( val listeners: Multimap<Int, (ItemStack?) -> Unit> = Multimaps.newListMultimap(mutableMapOf()) { mutableListOf() } ) { fun callSlotValueUpdate(slot: Int, item: ItemStack?) { listeners[slot].forEach { it(item) } } } data class Slot( val index: Int )
412
0.87397
1
0.87397
game-dev
MEDIA
0.91284
game-dev
0.936433
1
0.936433
cmss13-devs/cmss13
1,924
code/datums/components/deevolve_cooldown.dm
#define XENO_DEEVOLVE_COOLDOWN 5 MINUTES /** * A component that should be on all xenos that should be prevented from de-evolution manipulation. */ /datum/component/deevolve_cooldown /// The xeno that we are bound to var/mob/living/carbon/xenomorph/parent_xeno /// Assoc list of caste define to timerid of recent de-evolves this xeno has performed that are still on cooldown var/list/deevolves_on_cooldown = list() /datum/component/deevolve_cooldown/Initialize(mob/living/carbon/xenomorph/old_xeno) parent_xeno = parent if(!istype(parent_xeno)) return COMPONENT_INCOMPATIBLE var/datum/component/deevolve_cooldown/old_component = old_xeno?.GetComponent(/datum/component/deevolve_cooldown) if(old_component) deevolves_on_cooldown = old_component.deevolves_on_cooldown /datum/component/deevolve_cooldown/RegisterWithParent() RegisterSignal(parent_xeno, COMSIG_XENO_DEEVOLVE, PROC_REF(on_deevolve)) RegisterSignal(parent_xeno, COMSIG_XENO_TRY_EVOLVE, PROC_REF(on_try_evolve)) /datum/component/deevolve_cooldown/UnregisterFromParent() UnregisterSignal(parent_xeno, list(COMSIG_XENO_DEEVOLVE, COMSIG_XENO_TRY_EVOLVE)) /// Signal handler for COMSIG_XENO_DEEVOLVE to add the current xeno as a de-evolution /datum/component/deevolve_cooldown/proc/on_deevolve() deevolves_on_cooldown[parent_xeno.caste_type] = addtimer(VARSET_LIST_REMOVE_CALLBACK(deevolves_on_cooldown, "[parent_xeno.caste_type]"), XENO_DEEVOLVE_COOLDOWN, TIMER_STOPPABLE) return /// Signal handler for COMSIG_XENO_TRY_EVOLVE to determine is the evolution is allowed /datum/component/deevolve_cooldown/proc/on_try_evolve(mob/living/carbon/xenomorph/old_xeno, castepick) var/on_cooldown_timer = deevolves_on_cooldown[castepick] if(on_cooldown_timer) to_chat(old_xeno, SPAN_WARNING("We cannot evolve into this caste again yet! ([DisplayTimeText(timeleft(on_cooldown_timer), 1)] remaining)")) return COMPONENT_OVERRIDE_EVOLVE return FALSE
412
0.98429
1
0.98429
game-dev
MEDIA
0.745312
game-dev
0.967508
1
0.967508
MeteorClientPlus/MeteorPlus
4,221
src/main/java/nekiplay/meteorplus/features/modules/movement/fly/FlyPlus.java
package nekiplay.meteorplus.features.modules.movement.fly; import meteordevelopment.meteorclient.events.entity.player.CanWalkOnFluidEvent; import meteordevelopment.meteorclient.events.entity.player.PlayerMoveEvent; import meteordevelopment.meteorclient.events.entity.player.SendMovementPacketsEvent; import meteordevelopment.meteorclient.events.packets.PacketEvent; import meteordevelopment.meteorclient.events.world.CollisionShapeEvent; import meteordevelopment.meteorclient.events.world.TickEvent; import meteordevelopment.meteorclient.gui.GuiTheme; import meteordevelopment.meteorclient.gui.widgets.WWidget; import meteordevelopment.meteorclient.settings.*; import meteordevelopment.meteorclient.systems.modules.Categories; import meteordevelopment.meteorclient.systems.modules.Module; import meteordevelopment.orbit.EventHandler; import nekiplay.meteorplus.features.modules.movement.fly.modes.*; public class FlyPlus extends Module { private final SettingGroup sgGeneral = settings.getDefaultGroup(); public FlyPlus() { super(Categories.Movement, "flight+", "Bypass fly"); onFlyModeChanged(flyMode.get()); } public final Setting<FlyModes> flyMode = sgGeneral.add(new EnumSetting.Builder<FlyModes>() .name("mode") .description("The method of applying fly.") .defaultValue(FlyModes.Matrix_Exploit) .onModuleActivated(spiderModesSetting -> onFlyModeChanged(spiderModesSetting.get())) .onChanged(this::onFlyModeChanged) .build() ); public final Setting<Double> speed_1 = sgGeneral.add(new DoubleSetting.Builder() .name("speed-№1") .description("Fly speed.") .defaultValue(1.25) .max(2500) .sliderRange(0, 2500) .visible(() -> flyMode.get() == FlyModes.Matrix_Exploit) .build() ); public final Setting<Double> speed2 = sgGeneral.add(new DoubleSetting.Builder() .name("speed-№2") .description("Fly speed.") .defaultValue(0.3) .max(5) .sliderRange(0, 5) .visible(() -> flyMode.get() == FlyModes.Matrix_Exploit_2) .build() ); public final Setting<Boolean> canClip = sgGeneral.add(new BoolSetting.Builder() .name("can-clip") .description("Max fly ticks.") .visible(() -> flyMode.get() == FlyModes.Vulcan_Clip) .build() ); public final Setting<Boolean> showInfo = sgGeneral.add(new BoolSetting.Builder() .name("show-info") .description("Displays information about whether this mode is running on the server.") .visible(() -> flyMode.get() == FlyModes.Vulcan_Clip) .build() ); @Override public WWidget getWidget(GuiTheme theme) { WWidget widget = super.getWidget(theme); if (flyMode.get() == FlyModes.Vulcan_Clip) { return theme.label("This mode work only on 1.89 servers"); } return widget; } private FlyMode currentMode; @Override public void onActivate() { currentMode.onActivate(); } @Override public void onDeactivate() { currentMode.onDeactivate(); } @EventHandler private void onPreTick(TickEvent.Pre event) { currentMode.onTickEventPre(event); } @EventHandler private void onPostTick(TickEvent.Post event) { currentMode.onTickEventPost(event); } @EventHandler public void onSendPacket(PacketEvent.Send event) { currentMode.onSendPacket(event); } @EventHandler public void onSentPacket(PacketEvent.Sent event) { currentMode.onSentPacket(event); } @EventHandler public void onRecivePacket(PacketEvent.Receive event) { currentMode.onRecivePacket(event); } @EventHandler public void onCanWalkOnFluid(CanWalkOnFluidEvent event) { currentMode.onCanWalkOnFluid(event); } @EventHandler public void onCollisionShape(CollisionShapeEvent event) { currentMode.onCollisionShape(event); } @EventHandler private void onPlayerMoveEvent(PlayerMoveEvent event) { currentMode.onPlayerMoveEvent(event); } @EventHandler private void onPlayerMoveSendPre(SendMovementPacketsEvent.Pre event) { currentMode.onPlayerMoveSendPre(event); } private void onFlyModeChanged(FlyModes mode) { switch (mode) { case Matrix_Exploit_2 -> currentMode = new MatrixExploit2(); case Matrix_Exploit -> currentMode = new MatrixExploit(); case Vulcan_Clip -> { if (showInfo.get()) { info("Vulcan fly work on 1.8.9 servers"); } currentMode = new VulcanClip(); } } } }
412
0.781659
1
0.781659
game-dev
MEDIA
0.912967
game-dev
0.794103
1
0.794103
micro-manager/mmCoreAndDevices
10,923
camera_triggering_API_v2.md
# A proposed new API for camera triggering Based on the [GenICam specification](https://www.emva.org/wp-content/uploads/GenICam_SFNC_2_2.pdf), with modifications as needed for consistency with the existing API `internal` triggers mean no signal is sent for the corresponding event (the same triggers being "off" in GenICam) `external` triggers mean a TTL pulse is sent to the camera `software` triggers mean an API function is called **Development discussions:** [Chapter 1](https://github.com/micro-manager/mmCoreAndDevices/issues/84) [Chapter 2](https://github.com/micro-manager/mmCoreAndDevices/issues/226) **Previous API proposal versions:** [v1](https://github.com/micro-manager/mmCoreAndDevices/blob/4ce6d521a3875c0ecdd691fba5751b6a43bb0cd1/camera_triggering_API.md) ## Changes to [MM::Camera](https://valelab4.ucsf.edu/~MM/doc/MMDevice/html/class_m_m_1_1_camera.html) ```c++ //////////////////////////////////////////// // Micro-Manager Camera API proposal (v2) //////////////////////////////////////////// bool isTriggerAPIImplemented(); ////////////////////////////// // Triggers ////////////////////////////// // trigger state constants ////////////////////////////// // TriggerSelector const int TriggerSelectorAcquisitionStart = 0; const int TriggerSelectorAcquisitionEnd = 1; const int TriggerSelectorAcquisitionActive = 2; const int TriggerSelectorFrameBurstStart = 3; const int TriggerSelectorFrameBurstEnd = 4; const int TriggerSelectorFrameBurstActive = 5; const int TriggerSelectorFrameStart = 6; const int TriggerSelectorFrameEnd = 7; const int TriggerSelectorFrameActive = 8; const int TriggerSelectorExposureStart = 9; const int TriggerSelectorExposureEnd = 10; const int TriggerSelectorExposureActive = 11; // TriggerMode const int TriggerModeOn = 0; const int TriggerModeOff = 1; // TriggerSource // "internal" -- From the cameras internal timer // "external" -- TTL pulse // "software" -- a call from "TriggerSoftware" function const int TriggerSourceInternal = 0; const int TriggerSourceExternal = 1; const int TriggerSourceSoftware = 2; // TriggerActivation const int TriggerActivationAnyEdge = 0; const int TriggerActivationRisingEdge = 1; const int TriggerActivationFallingEdge = 2; const int TriggerActivationLevelLow = 3; const int TriggerActivationLevelHigh = 4; // TriggerOverlap // Off: No trigger overlap is permitted. // ReadOut: Trigger is accepted immediately after the exposure period. // PreviousFrame: Trigger is accepted (latched) at any time during the capture of the previous frame. const int TriggerOverlapOff = 0; const int TriggerOverlapReadout = 1; const int TriggerOverlapPreviosFrame = 2; // trigger functions ////////////////////////////// //Check which of the possible trigger types are available int hasTrigger(int triggerSelector); // These should return an error code if the type is not valid // They are not meant to do any work. int setTriggerState(int triggerSelector, int triggerMode, int triggerSource); int setTriggerState(int triggerSelector, int triggerMode, int triggerSource, int triggerDelay, int triggerActivation, int triggerOverlap); int getTriggerState(int &triggerSelector, int &triggerMode, int &triggerSource); int getTriggerState(int &triggerSelector, int &triggerMode, int &triggerSource, int &triggerDelay, int &triggerActivation, int &triggerOverlap); // Send of software of the supplied type int TriggerSoftware(int triggerSelector); ////////////////////////////// // Acquisitions ////////////////////////////// // Some terminology form GenICam // // AcquisitionMode // SingleFrame: One frame is captured. // MultiFrame: The number of frames specified by AcquisitionFrameCount is captured. // Continuous: Frames are captured continuously until stopped with the AcquisitionStop command. // // AcquisitionFrameCount // Number of frames to acquire in MultiFrame Acquisition mode. // // AcquisitionBurstFrameCount // Number of frames to acquire for each FrameBurstStart trigger. // This feature is used only if the FrameBurstStart trigger is enabled and // the FrameBurstEnd trigger is disabled. Note that the total number of frames // captured is also conditioned by AcquisitionFrameCount if AcquisitionMode is // MultiFrame and ignored if AcquisitionMode is Single. // // AcquisitionFrameRate // Controls the acquisition rate (in Hertz) at which the frames are captured. // TriggerMode must be Off for the Frame trigger. // Acquisition functions ////////////////////////////// // Arms the device before an AcquisitionStart command. This optional command validates all // the current features for consistency and prepares the device for a fast start of the Acquisition. // If not used explicitly, this command will be automatically executed at the first // AcquisitionStart but will not be repeated for the subsequent ones unless a feature is changed in the device. // TODO: the above logic needs to be implemented in core? // Don't acqMode because it can be inferred from frameCount // if frameCount is: 1 --> acqMode is single // > 1 --> acqMode is MultiFrame // -1 --> acqMode is continuous int AcquisitionArm(int frameCount, double acquisitionFrameRate, int burstFrameCount); int AcquisitionArm(int frameCount, int burstFrameCount); int AcquisitionArm(int frameCount, double acquisitionFrameRate); int AcquisitionArm(int frameCount); // Starts the Acquisition of the device. The number of frames captured is specified by AcquisitionMode. // Note that unless the AcquisitionArm was executed since the last feature change, // the AcquisitionStart command must validate all the current features for consistency before starting the Acquisition. int AcquisitionStart(); // Stops the Acquisition of the device at the end of the current Frame. It is mainly // used when AcquisitionMode is Continuous but can be used in any acquisition mode. // If the camera is waiting for a trigger, the pending Frame will be cancelled. // If no Acquisition is in progress, the command is ignored. int AcquisitionStop(); //Aborts the Acquisition immediately. This will end the capture without completing // the current Frame or waiting on a trigger. If no Acquisition is in progress, the command is ignored. int AcquisitionAbort(); // Maybe: for querying acquisition status // AcquisitionTriggerWait: Device is currently waiting for a trigger for the capture of one or many frames. // AcquisitionActive: Device is currently doing an acquisition of one or many frames. // AcquisitionTransfer: Device is currently transferring an acquisition of one or many frames. // FrameTriggerWait: Device is currently waiting for a frame start trigger. // FrameActive: Device is currently doing the capture of a frame. // ExposureActive: Device is doing the exposure of a frame. enum AcquisitionStatusType = {AcquisitionTriggerWait, AcquisitionActive, AcquisitionTransfer, FrameTriggerWait, FrameActive, ExposureActive} bool readAcquisitionStatus(AcquisitionStatusType a); // Rolling shutter/Lightsheet mode double GetRollingShutterLineOffset(); void SetRollingShutterLineOffset(double offset_us) throw (CMMError); int GetRollingShutterActiveLines(); void SetRollingShutterActiveLines(int numLines) throw (CMMError); ``` ## Changes to [Core (Callback) API](https://valelab4.ucsf.edu/~MM/doc/MMDevice/html/class_m_m_1_1_core.html) ```c++ // Called by camera when trigger changes OnCameraTriggerChanged (const Device *caller, int triggerSelector, int triggerMode, int triggerSource); OnCameraTriggerChanged (const Device *caller, int triggerSelector, int triggerMode, int triggerSource, int triggerDelay, int triggerActivation, int triggerOverlap); // Callbacks for camera events. This generalizes the prepareForAcq and acqFinished // AcquisitionTrigger: Device just received a trigger for the Acquisition of one or many Frames. // AcquisitionStart: Device just started the Acquisition of one or many Frames. // AcquisitionEnd: Device just completed the Acquisition of one or many Frames. // AcquisitionTransferStart: Device just started the transfer of one or many Frames. // AcquisitionTransferEnd: Device just completed the transfer of one or many Frames. // AcquisitionError: Device just detected an error during the active Acquisition. // FrameTrigger: Device just received a trigger to start the capture of one Frame. // FrameStart: Device just started the capture of one Frame. // FrameEnd: Device just completed the capture of one Frame. // FrameBurstStart: Device just started the capture of a burst of Frames. // FrameBurstEnd: Device just completed the capture of a burst of Frames. // FrameTransferStart: Device just started the transfer of one Frame. // FrameTransferEnd: Device just completed the transfer of one Frame. // ExposureStart: Device just started the exposure of one Frame (or Line). // ExposureEnd: Device just completed the exposure of one Frame (or Line). const int CameraEventAcquisitionTrigger = 0; const int CameraEventAcquisitionStart = 1; const int CameraEventAcquisitionEnd = 2; const int CameraEventAcquisitionTransferStart = 3; const int CameraEventAcquisitionTransferEnd = 4; const int CameraEventAcquisitionError = 5; const int CameraEventFrameTrigger = 6; const int CameraEventFrameStart = 7; const int CameraEventFrameEnd = 8; const int CameraEventFrameBurstStart = 9; const int CameraEventFrameBurstEnd = 10; const int CameraEventFrameTransferStart = 11; const int CameraEventFrameTransferEnd = 12; const int CameraEventExposureStart = 13; const int CameraEventExposureEnd = 14; // Camera calls this function on the core to notify of events // TODO: this may be coming from a camera internal thread, // so it may make sense to put restrictions on what the core // can do with these callbacks (i.e. nothing processor intensive) cameraEventCallback(const Device *caller, int EventType) ``` ## New calls in [MMCore](https://valelab4.ucsf.edu/~MM/doc/MMCore/html/class_c_m_m_core.html) A set of API calls in MMCore will provide access to this high-level API. Following MM convention, these will be essentially a 1to1 access of camera API methods. TODO... ## Backwards compatibility The old (camera) API for now will be optional on new devices, to be removed later in the future (maybe) The old (core) API will be implemented in terms of the new camera API when it is present, or fall back on the old camera API when its not ## Data access The current MMCore provides two routes for accessing image data, one for Snaps and one for Sequences. The newer API will eventually be used with a unified, single image storage mechanism. Thus, the new APIs will always insert images into the circular buffer. For backwards compatibility, when `core.SnapImage` is called, the image will be copied into a seperate buffer so that it can be retrieved in the expected way for old API users.
412
0.926361
1
0.926361
game-dev
MEDIA
0.604549
game-dev
0.944922
1
0.944922
eaglerforge/EaglerForge-old
1,326
patches/minecraft/net/minecraft/util/Session.edit.java
# Eagler Context Redacted Diff # Copyright (c) 2024 lax1dude. All rights reserved. # Version: 1.0 # Author: lax1dude > CHANGE 2 : 7 @ 2 : 7 ~ import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; ~ import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; ~ import net.lax1dude.eaglercraft.v1_8.mojang.authlib.GameProfile; ~ import net.lax1dude.eaglercraft.v1_8.profile.EaglerProfile; ~ import net.minecraft.entity.player.EntityPlayer; > CHANGE 2 : 3 @ 2 : 6 ~ private GameProfile profile; > CHANGE 1 : 2 @ 1 : 7 ~ private static final EaglercraftUUID offlineUUID; > CHANGE 1 : 3 @ 1 : 3 ~ public Session() { ~ reset(); > CHANGE 2 : 4 @ 2 : 4 ~ public GameProfile getProfile() { ~ return profile; > CHANGE 2 : 4 @ 2 : 4 ~ public void update(String serverUsername, EaglercraftUUID uuid) { ~ profile = new GameProfile(uuid, serverUsername); > CHANGE 2 : 4 @ 2 : 4 ~ public void reset() { ~ update(EaglerProfile.getName(), offlineUUID); > CHANGE 2 : 4 @ 2 : 9 ~ public void setLAN() { ~ update(EaglerProfile.getName(), EntityPlayer.getOfflineUUID(EaglerProfile.getName())); > CHANGE 2 : 6 @ 2 : 4 ~ static { ~ byte[] bytes = new byte[16]; ~ (new EaglercraftRandom()).nextBytes(bytes); ~ offlineUUID = new EaglercraftUUID(bytes); > DELETE 2 @ 2 : 23 > EOF
412
0.905573
1
0.905573
game-dev
MEDIA
0.628716
game-dev
0.513385
1
0.513385
monocasual/giada
2,640
src/gui/elems/actionEditor/pianoRoll.h
/* ----------------------------------------------------------------------------- * * Giada - Your Hardcore Loopmachine * * ----------------------------------------------------------------------------- * * Copyright (C) 2010-2025 Giovanni A. Zuliani | Monocasual Laboratories * * This file is part of Giada - Your Hardcore Loopmachine. * * Giada - Your Hardcore Loopmachine 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. * * Giada - Your Hardcore Loopmachine 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 Giada - Your Hardcore Loopmachine. If not, see * <http://www.gnu.org/licenses/>. * * -------------------------------------------------------------------------- */ #ifndef GE_PIANO_ROLL_H #define GE_PIANO_ROLL_H #include "src/gui/elems/actionEditor/baseActionEditor.h" #include <FL/fl_draw.H> #include <functional> namespace giada::m { struct Action; } namespace giada::v { class gePianoRoll : public geBaseActionEditor { public: enum class Notes { G = 1, FS = 2, F = 3, E = 4, DS = 5, D = 6, CS = 7, C = 8, B = 9, AS = 10, A = 11, GS = 0 }; static const int MAX_KEYS = 127; static const int MAX_OCTAVES = 9; static const int KEYS = 12; static const Pixel CELL_H = 20; static const Pixel CELL_W = 40; gePianoRoll(Pixel x, Pixel y, gdBaseActionEditor* b); void draw() override; void rebuild(c::actionEditor::Data& d) override; private: void onAddAction() override; void onDeleteAction() override; void onMoveAction() override; void onResizeAction() override; void onRefreshAction() override; /* drawOffscreenGrid Generates a complex drawing in memory first and copy it to the screen at a later point in time. Fl_Offscreen m_offscreenGrid holds the necessary data. Creates another offscreen surface of CELL_W pixels wide containing the piano roll grid, then tiled during the ::draw() call. */ void drawOffscreenGrid(); Pixel snapToY(Pixel p) const; int yToNote(Pixel y) const; Pixel noteToY(int n) const; Pixel getPianoItemW(Pixel x, const m::Action& a1, const m::Action& a2) const; Fl_Offscreen m_offscreenGrid; // lines, x-repeat }; } // namespace giada::v #endif
412
0.671189
1
0.671189
game-dev
MEDIA
0.678351
game-dev,graphics-rendering
0.514096
1
0.514096
Open-Source-Free-Realms/Sanctuary
2,512
src/Sanctuary.Game/ZoneManager.cs
using System; using System.Collections.Concurrent; using System.Diagnostics.CodeAnalysis; using Microsoft.Extensions.Logging; using Sanctuary.Game.Entities; using Sanctuary.Game.Resources.Definitions.Zones; using Sanctuary.Game.Zones; namespace Sanctuary.Game; public class ZoneManager : IZoneManager { private readonly ILogger _logger; private readonly IResourceManager _resourceManager; private readonly IServiceProvider _serviceProvider; private static int _uniqueId = 1; private readonly ConcurrentDictionary<int, IZone> _zones = new(); private const int StartingZoneDefinitionId = 1; public StartingZone StartingZone { get; private set; } = null!; public ZoneManager( ILoggerFactory loggerFactory, IResourceManager resourceManager, IServiceProvider serviceProvider) { _logger = loggerFactory.CreateLogger<ZoneManager>(); _resourceManager = resourceManager; _serviceProvider = serviceProvider; } public bool Load() { if (!TryCreateStartingZone(StartingZoneDefinitionId, out var startingZone)) return false; StartingZone = startingZone; return true; } public bool TryGetPlayer(ulong guid, [MaybeNullWhen(false)] out Player player) { player = default; foreach (var zone in _zones) { if (zone.Value.TryGetPlayer(guid, out player)) return true; } return false; } public bool TryGetPlayer(string name, [MaybeNullWhen(false)] out Player player) { player = default; foreach (var zone in _zones) { foreach (var zonePlayer in zone.Value.Players) { if (zonePlayer.Name.FullName == name) { player = zonePlayer; return true; } } } return false; } private bool TryCreateStartingZone(int definitionId, [MaybeNullWhen(false)] out StartingZone zone) { zone = default; if (!_resourceManager.Zones.TryGetValue(definitionId, out var zoneDefinition)) return false; if (zoneDefinition is not StartingZoneDefinition startingZoneDefinition) return false; zone = new StartingZone(startingZoneDefinition, _serviceProvider) { Id = _uniqueId++ }; // zone.OnStart(); return _zones.TryAdd(zone.Id, zone); } }
412
0.768945
1
0.768945
game-dev
MEDIA
0.628734
game-dev
0.797482
1
0.797482
Planimeter/game-engine-2d
1,639
game/shared/entities/prop_worldgate_spawn.lua
--=========== Copyright © 2019, Planimeter, All rights reserved. ===========-- -- -- Purpose: prop_worldgate_spawn -- --==========================================================================-- entities.require( "entity" ) require( "game" ) if ( _CLIENT ) then require( "engine.client.chat" ) end class "prop_worldgate_spawn" ( "entity" ) function prop_worldgate_spawn:prop_worldgate_spawn() entity.entity( self ) if ( _CLIENT ) then local tileSize = game.tileSize self:setLocalPosition( vector( -tileSize, 0 ) ) end self:setNetworkVar( "name", "World Gate" ) if ( _CLIENT ) then local filename = "images/entities/prop_worldgate_spawn.png" local sprite = love.graphics.newImage( filename ) sprite:setFilter( "nearest", "nearest" ) self:setSprite( sprite ) end end if ( _CLIENT ) then function prop_worldgate_spawn:getOptions() return { { name = "Examine", value = function() self:examine() end } } end function prop_worldgate_spawn:examine() chat.addText( "Rather tall and ominous." ) end end function prop_worldgate_spawn:spawn() entity.spawn( self ) local tileSize = game.tileSize local min = vector() local max = vector( tileSize, -tileSize ) self:initializePhysics() self:setCollisionBounds( min, max ) end function prop_worldgate_spawn:tick( timestep ) local position = self:getPosition() local players = player.getAll() for _, player in ipairs( players ) do if ( player:getPosition() == position ) then player:moveTo( position + vector( 0, game.tileSize ) ) end end end entities.linkToClassname( prop_worldgate_spawn, "prop_worldgate_spawn" )
412
0.791876
1
0.791876
game-dev
MEDIA
0.990904
game-dev
0.735845
1
0.735845
spelunky-fyi/overlunky
4,008
src/game_api/script/usertypes/prng_lua.cpp
#include "prng_lua.hpp" #include <algorithm> // for max #include <cstdint> // for int64_t #include <new> // for operator new #include <optional> // for optional #include <sol/sol.hpp> // for global_table, proxy_key_t, state, overload, call #include <string> // for allocator, operator== #include <tuple> // for get #include <type_traits> // for move, declval #include <utility> // for min, max, get #include "heap_base.hpp" // for HeapBase #include "prng.hpp" // for PRNG, PRNG::ENTITY_VARIATION, PRNG::EXTRA_SPAWNS namespace NPRNG { void register_usertypes(sol::state& lua) { auto random = sol::overload(static_cast<float (PRNG::*)()>(&PRNG::random), static_cast<std::optional<std::int64_t> (PRNG::*)(std::int64_t)>(&PRNG::random), static_cast<std::int64_t (PRNG::*)(std::int64_t, std::int64_t)>(&PRNG::random)); /// Seed the game prng. lua["seed_prng"] = [](int64_t seed) { HeapBase::get().prng()->seed(seed); }; /// PRNG (short for Pseudo-Random-Number-Generator) holds 10 128bit wide buffers of memory that are mutated on every generation of a random number. /// The game uses specific buffers for specific scenarios, for example the third buffer is used every time particles are spawned to determine a random velocity. /// The used buffer is determined by [PRNG_CLASS](#PRNG_CLASS). If you want to make a mod that does not affect level generation but still uses the prng then you want to stay away from specific buffers. /// If you don't care what part of the game you affect just use [prng](#prng)`.random`. lua.new_usertype<PRNG>( "PRNG", "seed", &PRNG::seed, "random_float", &PRNG::random_float, "random_chance", &PRNG::random_chance, "random_index", &PRNG::random_index, "random_int", &PRNG::random_int, "random", random, "get_pair", &PRNG::get_pair, "set_pair", &PRNG::set_pair); /// The global prng state, calling any function on it will advance the prng state, thus desynchronizing clients if it does not happen on both clients. lua["prng"] = HeapBase::get_main().prng(); /// Get the thread-local version of prng lua["get_local_prng"] = []() -> PRNG* { return HeapBase::get().prng(); }; /// Determines what class of prng is used, which in turn determines which parts of the game's future prng is affected. See more info at [PRNG](#PRNG) /// For example when choosing `PRNG_CLASS.PROCEDURAL_SPAWNS` to generate a random number, random Tiamat spawns will not be affected. /// Any integer in the range [0, 9] is a valid class, some are however not documented because of missing information. lua.create_named_table("PRNG_CLASS", "PROCEDURAL_SPAWNS", PRNG::PROCEDURAL_SPAWNS, "PARTICLES", PRNG::PARTICLES, "ENTITY_VARIATION", PRNG::ENTITY_VARIATION, "EXTRA_SPAWNS", PRNG::EXTRA_SPAWNS, "LEVEL_DECO", PRNG::LEVEL_DECO, "LIQUID", PRNG::LIQUID, "AI", PRNG::EXTRA_SPAWNS, "LEVEL_GEN", PRNG::PROCEDURAL_SPAWNS, "FX", PRNG::FX, "CHAR_AI", PRNG::CHAR_AI); /* PRNG_CLASS // PROCEDURAL_SPAWNS // Anything level gen related really, including but not limited to path, room and enemy placement. // LEVEL_GEN // Anything level gen related really, including but not limited to path, room and enemy placement. // PARTICLES // Direction and angle of torch flames etc, but also includes other things not related to particles at all... // ENTITY_VARIATION // Some entities that have many texture to choose from on spawn // FX // Some effects, like water splashes, background stars and teleport shadow // LIQUID // Liquid movement // LEVEL_DECO // I have no idea what this name means, cause this seems to advance every 3 or so frames even with zero entities in a level // AI // Monster AI decisions // CHAR_AI // Character AI decisions */ } } // namespace NPRNG
412
0.942557
1
0.942557
game-dev
MEDIA
0.868483
game-dev
0.951415
1
0.951415
Ajordat/alteredbuilder
20,342
alteredbuilder/decks/deck_utils.py
from collections import defaultdict from http import HTTPStatus import re from django.conf import settings from django.contrib.auth.models import User from django.db import IntegrityError, transaction from django.db.models import Exists, F, IntegerField, OuterRef, Q, Subquery from django.db.models.query import QuerySet from django.utils.translation import activate, gettext_lazy as _ import requests from api.utils import locale_agnostic from config.utils import get_altered_api_locale, get_user_agent from decks.game_modes import ( DraftGameMode, GameMode, StandardGameMode, update_deck_legality, ) from decks.models import ( Card, CardInDeck, CardPrice, Deck, FavoriteCard, LovePoint, Subtype, ) from decks.exceptions import AlteredAPIError, CardAlreadyExists, MalformedDeckException # Altered's API endpoint ALTERED_TCG_API_URL = "https://api.altered.gg/cards" HEADERS = {"User-Agent": get_user_agent("UniqueCardImporter")} # The API currently returns a private image link for unique cards in these languages IMAGE_ERROR_LOCALES = ["es", "it", "de"] OPERATOR_TO_HTML = { ":": ":", "=": " =", "<": " &lt;", "<=": " &le;", ">": " &gt;", ">=": " &ge;", } TRIGGER_TRANSLATION = { "etb": "{J}", "hand": "{H}", "reserve": "{R}", "discard": "{D}", "exhaust": "{T}", "passive": "{I}", } @transaction.atomic def create_new_deck(user: User, deck_form: dict) -> Deck: """Method to validate the clean data from a DecklistForm and create it if all input is valid. Args: user (User): The Deck's owner. deck_form (dict): Clean data from a DecklistForm. Raises: MalformedDeckException: If the decklist is invalid. Returns: Deck: The resulting object. """ decklist = deck_form["decklist"] deck = Deck.objects.create( name=deck_form["name"], owner=user, is_public=deck_form["is_public"], description=deck_form["description"], ) has_hero = False for line in decklist.splitlines(): # For each line, it is needed to: # * Validate its format # * Search the card reference on the database # - If it's a Hero, assign it to the Deck's Hero # - Otherwise append it to the list of cards try: count, reference = line.split() count = int(count) except ValueError: # The form validator only checks if there's at least one # line with the correct format raise MalformedDeckException( # Translators: This is logged when the provided text decklist has an invalid format _("Failed to unpack '%(line)s'") % {"line": line} ) try: card = Card.objects.get(reference=reference) except Card.DoesNotExist: try: card = import_unique_card(reference) FavoriteCard.objects.get_or_create(user=user, card=card) print(f"Created card '{reference}'") except AlteredAPIError: # The Card's reference needs to exist on the database raise MalformedDeckException( _("Card '%(reference)s' wasn't found and couldn't be imported") % {"reference": reference} ) if card.type == Card.Type.HERO: if not has_hero: deck.hero = card has_hero = True else: # The Deck model requires to have exactly one Hero per Deck raise MalformedDeckException( _("Multiple heroes present in the decklist") ) else: if CardInDeck.objects.filter(deck=deck, card=card).exists(): # If the card is already linked to the deck, increase its quantity cid = CardInDeck.objects.get(deck=deck, card=card) cid.quantity = F("quantity") + count cid.save(update_fields=["quantity"]) else: # Link the Card with the Deck CardInDeck.objects.create(deck=deck, card=card, quantity=count) update_deck_legality(deck) deck.save() return deck def get_deck_details(deck: Deck) -> dict: cid_queryset: QuerySet[CardInDeck] = deck.cardindeck_set decklist = ( cid_queryset.select_related("card") .prefetch_related("card__prices") .annotate( last_price=Subquery( CardPrice.objects.filter(card=OuterRef("card__pk")) .order_by("-date") .values("price")[:1], output_field=IntegerField(), ) ) .order_by("card__reference") .all() ) hand_counter = defaultdict(int) recall_counter = defaultdict(int) rarity_counter = defaultdict(int) power_counter = defaultdict(int) # This dictionary will hold all metadata based on the card's type by using the # type as a key type_stats = { Card.Type.CHARACTER: [[], 0], Card.Type.SPELL: [[], 0], Card.Type.LANDMARK_PERMANENT: [[], 0], Card.Type.EXPEDITION_PERMANENT: [[], 0], } for cid in decklist: # Append the card to its own type card list type_stats[cid.card.type][0].append((cid.quantity, cid.card, cid.last_price)) # Count the card count of the card's type type_stats[cid.card.type][1] += cid.quantity # Count the amount of cards with the same hand cost hand_counter[cid.card.stats["main_cost"]] += cid.quantity # Count the amount of cards with the same recall cost recall_counter[cid.card.stats["recall_cost"]] += cid.quantity # Count the amount of cards with the same rarity rarity_counter[cid.card.rarity] += cid.quantity power_counter["forest"] += cid.card.stats.get("forest_power", 0) * cid.quantity power_counter["mountain"] += ( cid.card.stats.get("mountain_power", 0) * cid.quantity ) power_counter["ocean"] += cid.card.stats.get("ocean_power", 0) * cid.quantity decklist_text = f"1 {deck.hero.reference}\n" if deck.hero else "" decklist_text += "\n".join( [f"{cid.quantity} {cid.card.reference}" for cid in decklist] ) return { "decklist": decklist_text, "character_list": sorted( type_stats[Card.Type.CHARACTER][0], key=sort_by_mana_cost ), "spell_list": sorted(type_stats[Card.Type.SPELL][0], key=sort_by_mana_cost), "permanent_list": sorted( type_stats[Card.Type.LANDMARK_PERMANENT][0] + type_stats[Card.Type.EXPEDITION_PERMANENT][0], key=sort_by_mana_cost, ), "stats": { "type_distribution": { "characters": type_stats[Card.Type.CHARACTER][1], "spells": type_stats[Card.Type.SPELL][1], "permanents": type_stats[Card.Type.LANDMARK_PERMANENT][1] + type_stats[Card.Type.EXPEDITION_PERMANENT][1], }, "total_count": type_stats[Card.Type.CHARACTER][1] + type_stats[Card.Type.SPELL][1] + type_stats[Card.Type.LANDMARK_PERMANENT][1] + type_stats[Card.Type.EXPEDITION_PERMANENT][1], "mana_distribution": { "hand": hand_counter, "recall": recall_counter, }, "rarity_distribution": { "common": rarity_counter[Card.Rarity.COMMON], "rare": rarity_counter[Card.Rarity.RARE], "unique": rarity_counter[Card.Rarity.UNIQUE], }, "region_distribution": power_counter, }, "legality": { "standard": { "is_legal": deck.is_standard_legal, "errors": GameMode.ErrorCode.from_list_to_user( deck.standard_legality_errors, StandardGameMode ), }, "draft": { "is_legal": deck.is_draft_legal, "errors": GameMode.ErrorCode.from_list_to_user( deck.draft_legality_errors, DraftGameMode ), }, }, } def sort_by_mana_cost(row): return row[1].stats["main_cost"], row[1].stats["recall_cost"] @transaction.atomic def patch_deck(deck: Deck, name: str, changes: dict[str, int]) -> None: deck.name = name for card_reference, quantity in changes.items(): try: card = Card.objects.get(reference=card_reference) if card.type == Card.Type.HERO: if quantity > 0: deck.hero = card elif quantity == 0 and deck.hero == card: deck.hero = None else: cid = CardInDeck.objects.get(card=card, deck=deck) if quantity > 0: cid.quantity = quantity cid.save() else: cid.delete() except Card.DoesNotExist: continue except CardInDeck.DoesNotExist: if quantity > 0: CardInDeck.objects.create(card=card, deck=deck, quantity=quantity) def remove_card_from_deck(deck: Deck, reference: str) -> None: card = Card.objects.get(reference=reference) if card.type == Card.Type.HERO and deck.hero.reference == card.reference: # If it's the Deck's hero, remove the reference deck.hero = None else: # Retrieve the CiD and delete it cid = CardInDeck.objects.get(deck=deck, card=card) cid.delete() def parse_card_query_syntax( qs: QuerySet[Card], query: str ) -> tuple[QuerySet[Card], list[(str, str, str)], bool]: filters = Q() tags = [] ref_regex = r"ref:(?P<reference>\w+)" if matches := re.finditer(ref_regex, query, re.ASCII): for re_match in matches: reference = re_match.group("reference") tags.append((_("reference"), ":", reference)) return qs.filter(reference=reference), tags, True hc_regex = r"hc(?P<hc_op>:|=|>|>=|<|<=)(?P<hc>\d+)" if matches := re.finditer(hc_regex, query, re.ASCII): for re_match in matches: op = re_match.group("hc_op") value = int(re_match.group("hc")) match op: case "=" | ":": filters &= Q(stats__main_cost=value) case "<": filters &= Q(stats__main_cost__lt=value) case "<=": filters &= Q(stats__main_cost__lte=value) case ">": filters &= Q(stats__main_cost__gt=value) case ">=": filters &= Q(stats__main_cost__gte=value) tags.append((_("hand cost"), OPERATOR_TO_HTML[op], str(value))) query = re.sub(hc_regex, "", query) rc_regex = r"rc(?P<rc_op>:|=|>|>=|<|<=)(?P<rc>\d+)" if matches := re.finditer(rc_regex, query, re.ASCII): for re_match in matches: op = re_match.group("rc_op") value = int(re_match.group("rc")) match op: case "=" | ":": filters &= Q(stats__recall_cost=value) case "<": filters &= Q(stats__recall_cost__lt=value) case "<=": filters &= Q(stats__recall_cost__lte=value) case ">": filters &= Q(stats__recall_cost__gt=value) case ">=": filters &= Q(stats__recall_cost__gte=value) tags.append((_("reserve cost"), OPERATOR_TO_HTML[op], str(value))) query = re.sub(rc_regex, "", query) x_regex = r"x:(?P<effect>\w+)" if matches := re.finditer(x_regex, query): for re_match in matches: value = re_match.group("effect") filters &= Q(main_effect__icontains=value) | Q(echo_effect__icontains=value) tags.append((_("ability"), ":", value)) query = re.sub(x_regex, "", query) st_regex = r"st:(?P<subtype>\w+)" if matches := re.finditer(st_regex, query): for re_match in matches: value = re_match.group("subtype") qs = qs.filter( Exists( Subtype.objects.filter(card=OuterRef("pk"), name__icontains=value) ) ) tags.append((_("subtype"), ":", value)) query = re.sub(st_regex, "", query) t_regex = r"t:(?P<trigger>\w+)" if matches := re.finditer(t_regex, query): for re_match in matches: try: trigger = re_match.group("trigger") value = TRIGGER_TRANSLATION[trigger] if trigger in ["discard", "passive"]: filters &= Q(echo_effect__contains=value) else: filters &= Q(main_effect__contains=value) tags.append((_("trigger"), ":", trigger)) except KeyError: continue query = re.sub(t_regex, "", query) query = query.strip() if query: tags.append((_("query"), ":", query)) return qs.filter(filters & Q(name__icontains=query)), tags, False else: return qs.filter(filters), tags, False @locale_agnostic def import_unique_card(reference: str) -> Card: # pragma: no cover # Check if the card already exists in the database if Card.objects.filter(reference=reference).exists(): raise CardAlreadyExists # Fetch the card data from the official API api_url = f"{ALTERED_TCG_API_URL}/{reference}/" response = requests.get(api_url, headers=HEADERS) if response.status_code != HTTPStatus.OK: match response.status_code: case HTTPStatus.UNAUTHORIZED: msg = f"The card {reference} is not public" case HTTPStatus.NOT_FOUND: msg = f"The card {reference} does not exist" case _: msg = "Couldn't access the Altered API" raise AlteredAPIError(msg, status_code=response.status_code) card_data = response.json() family = "_".join(reference.split("_")[:-2]) try: og_card = Card.objects.filter( reference__startswith=family, rarity=Card.Rarity.COMMON ).get() except Card.DoesNotExist: raise AlteredAPIError( f"The card family '{family}' does not exist in the database", status_code=HTTPStatus.NOT_FOUND, ) card_dict = { "reference": reference, "name": og_card.name, "faction": card_data["mainFaction"]["reference"], "type": Card.Type.CHARACTER, "rarity": Card.Rarity.UNIQUE, "image_url": card_data["imagePath"], "set": og_card.set, "stats": { "main_cost": int(card_data["elements"]["MAIN_COST"]), "recall_cost": int(card_data["elements"]["RECALL_COST"]), "forest_power": int(card_data["elements"]["FOREST_POWER"]), "mountain_power": int(card_data["elements"]["MOUNTAIN_POWER"]), "ocean_power": int(card_data["elements"]["OCEAN_POWER"]), }, } if "MAIN_EFFECT" in card_data["elements"]: card_dict["main_effect"] = card_data["elements"]["MAIN_EFFECT"] if "ECHO_EFFECT" in card_data["elements"]: card_dict["echo_effect"] = card_data["elements"]["ECHO_EFFECT"] card = Card(**card_dict) for language, _ in settings.LANGUAGES: # noqa: F402 if language == settings.LANGUAGE_CODE: continue activate(language) locale_code = get_altered_api_locale(language) headers = {"Accept-Language": locale_code} response = requests.get(api_url, headers=headers) card_data = response.json() card.name = og_card.name if "MAIN_EFFECT" in card_data["elements"]: card.main_effect = card_data["elements"]["MAIN_EFFECT"] if "ECHO_EFFECT" in card_data["elements"]: card.echo_effect = card_data["elements"]["ECHO_EFFECT"] if language not in IMAGE_ERROR_LOCALES: if "imagePath" in card_data: card.image_url = card_data["imagePath"] elif "allImagePath" in card_data: card.image_url = card_data["allImagePath"].get(locale_code) try: with transaction.atomic(): card.save() card.subtypes.add(*og_card.subtypes.all()) except IntegrityError as e: if 'duplicate key value violates unique constraint "decks_card_pkey"' in str(e): # This can happen if the user attempts to import a deck and submits # another import with the same unique card while it hasn't been fully # imported. # I could use `get_or_create` but that would imply dealing with the # i18n attributes of the Card table and I don't want to. print("Duplicate primary key detected. Skip the commit into the db.") return Card.objects.get(reference=card.reference) else: raise return card def filter_by_query(qs: QuerySet[Deck], query: str) -> QuerySet[Deck]: filters = Q() tags = [] if query: t_regex = r"u:(?P<username>[\w\.-@]+)" if matches := re.finditer(t_regex, query): for re_match in matches: username = re_match.group("username") filters &= Q(owner__username__iexact=username) tags.append((_("user"), ":", username)) query = re.sub(t_regex, "", query) h_regex = r"h:(?P<hero>\w+)" if matches := re.finditer(h_regex, query): for re_match in matches: hero = re_match.group("hero") filters &= Q(hero__name__icontains=hero) tags.append((_("hero"), ":", hero)) query = re.sub(h_regex, "", query) ref_regex = r"ref:(?P<reference>\w+)" if matches := re.finditer(ref_regex, query): for re_match in matches: reference = re_match.group("reference") filters &= Q(cards__reference=reference) tags.append((_("reference"), ":", reference)) query = re.sub(ref_regex, "", query) query = query.strip() if query: tags.append((_("query"), ":", query)) qs = qs.filter(filters & Q(name__icontains=query)) else: qs = qs.filter(filters) return qs, tags if tags else None def filter_by_faction(qs: QuerySet[Deck], factions: str) -> QuerySet[Deck]: if factions: try: factions = [Card.Faction(faction) for faction in factions.split(",")] qs = qs.filter(hero__faction__in=factions) except ValueError: pass return qs def filter_by_legality(qs: QuerySet[Deck], legality: str) -> QuerySet[Deck]: if legality: legality = legality.split(",") if "standard" in legality: qs = qs.filter(is_standard_legal=True) elif "draft" in legality: qs = qs.filter(is_draft_legal=True) if "exalts" in legality: qs = qs.filter(is_exalts_legal=True) if "doubles" in legality: qs = qs.filter(is_doubles_legal=True) return qs def filter_by_tags(qs: QuerySet[Deck], tags: str) -> QuerySet[Deck]: if tags: qs = qs.filter(tags__name__in=tags.split(",")).distinct() return qs def filter_by_other(qs: QuerySet[Deck], other_filters: str, user) -> QuerySet[Deck]: if other_filters: other_filters = other_filters.split(",") if "loved" in other_filters: try: lp = LovePoint.objects.filter(user=user) qs = qs.filter(id__in=lp.values_list("deck_id", flat=True)) except TypeError: pass if "description" in other_filters: qs = qs.exclude(description="") return qs def card_code_from_reference(reference: str) -> str: return "_".join(reference.split("_")[3:6]) def family_code_from_reference(reference: str) -> str: return "_".join(reference.split("_")[3:5])
412
0.946699
1
0.946699
game-dev
MEDIA
0.54361
game-dev
0.934825
1
0.934825
oot-pc-port/oot-pc-port
10,505
asm/non_matchings/overlays/actors/ovl_En_Po_Field/func_80AD4A68.s
glabel func_80AD4A68 /* 00F68 80AD4A68 27BDFFD0 */ addiu $sp, $sp, 0xFFD0 ## $sp = FFFFFFD0 /* 00F6C 80AD4A6C AFBF0024 */ sw $ra, 0x0024($sp) /* 00F70 80AD4A70 AFB00020 */ sw $s0, 0x0020($sp) /* 00F74 80AD4A74 AFA50034 */ sw $a1, 0x0034($sp) /* 00F78 80AD4A78 8CAF1C44 */ lw $t7, 0x1C44($a1) ## 00001C44 /* 00F7C 80AD4A7C 24190010 */ addiu $t9, $zero, 0x0010 ## $t9 = 00000010 /* 00F80 80AD4A80 00808025 */ or $s0, $a0, $zero ## $s0 = 00000000 /* 00F84 80AD4A84 AFAF002C */ sw $t7, 0x002C($sp) /* 00F88 80AD4A88 90980194 */ lbu $t8, 0x0194($a0) ## 00000194 /* 00F8C 80AD4A8C 2484014C */ addiu $a0, $a0, 0x014C ## $a0 = 0000014C /* 00F90 80AD4A90 03381823 */ subu $v1, $t9, $t8 /* 00F94 80AD4A94 0C02927F */ jal SkelAnime_FrameUpdateMatrix /* 00F98 80AD4A98 AFA30028 */ sw $v1, 0x0028($sp) /* 00F9C 80AD4A9C 86020196 */ lh $v0, 0x0196($s0) ## 00000196 /* 00FA0 80AD4AA0 8FA30028 */ lw $v1, 0x0028($sp) /* 00FA4 80AD4AA4 10400002 */ beq $v0, $zero, .L80AD4AB0 /* 00FA8 80AD4AA8 2448FFFF */ addiu $t0, $v0, 0xFFFF ## $t0 = FFFFFFFF /* 00FAC 80AD4AAC A6080196 */ sh $t0, 0x0196($s0) ## 00000196 .L80AD4AB0: /* 00FB0 80AD4AB0 04620004 */ bltzl $v1, .L80AD4AC4 /* 00FB4 80AD4AB4 00031023 */ subu $v0, $zero, $v1 /* 00FB8 80AD4AB8 10000002 */ beq $zero, $zero, .L80AD4AC4 /* 00FBC 80AD4ABC 00601025 */ or $v0, $v1, $zero ## $v0 = 00000000 /* 00FC0 80AD4AC0 00031023 */ subu $v0, $zero, $v1 .L80AD4AC4: /* 00FC4 80AD4AC4 28410010 */ slti $at, $v0, 0x0010 /* 00FC8 80AD4AC8 50200013 */ beql $at, $zero, .L80AD4B18 /* 00FCC 80AD4ACC 2604021C */ addiu $a0, $s0, 0x021C ## $a0 = 0000021C /* 00FD0 80AD4AD0 92040194 */ lbu $a0, 0x0194($s0) ## 00000194 /* 00FD4 80AD4AD4 000422C0 */ sll $a0, $a0, 11 /* 00FD8 80AD4AD8 00042400 */ sll $a0, $a0, 16 /* 00FDC 80AD4ADC 0C01DE1C */ jal Math_Sins ## sins? /* 00FE0 80AD4AE0 00042403 */ sra $a0, $a0, 16 /* 00FE4 80AD4AE4 86090032 */ lh $t1, 0x0032($s0) ## 00000032 /* 00FE8 80AD4AE8 3C014400 */ lui $at, 0x4400 ## $at = 44000000 /* 00FEC 80AD4AEC 44814000 */ mtc1 $at, $f8 ## $f8 = 512.00 /* 00FF0 80AD4AF0 44892000 */ mtc1 $t1, $f4 ## $f4 = 0.00 /* 00FF4 80AD4AF4 46000005 */ abs.s $f0, $f0 /* 00FF8 80AD4AF8 46004282 */ mul.s $f10, $f8, $f0 /* 00FFC 80AD4AFC 468021A0 */ cvt.s.w $f6, $f4 /* 01000 80AD4B00 460A3400 */ add.s $f16, $f6, $f10 /* 01004 80AD4B04 4600848D */ trunc.w.s $f18, $f16 /* 01008 80AD4B08 440B9000 */ mfc1 $t3, $f18 /* 0100C 80AD4B0C 00000000 */ nop /* 01010 80AD4B10 A60B0032 */ sh $t3, 0x0032($s0) ## 00000032 /* 01014 80AD4B14 2604021C */ addiu $a0, $s0, 0x021C ## $a0 = 0000021C .L80AD4B18: /* 01018 80AD4B18 3C054334 */ lui $a1, 0x4334 ## $a1 = 43340000 /* 0101C 80AD4B1C 3C063F00 */ lui $a2, 0x3F00 ## $a2 = 3F000000 /* 01020 80AD4B20 0C01E107 */ jal Math_SmoothScaleMaxF /* 01024 80AD4B24 3C074120 */ lui $a3, 0x4120 ## $a3 = 41200000 /* 01028 80AD4B28 8FAC002C */ lw $t4, 0x002C($sp) /* 0102C 80AD4B2C 3C063E4C */ lui $a2, 0x3E4C ## $a2 = 3E4C0000 /* 01030 80AD4B30 34C6CCCD */ ori $a2, $a2, 0xCCCD ## $a2 = 3E4CCCCD /* 01034 80AD4B34 26040008 */ addiu $a0, $s0, 0x0008 ## $a0 = 00000008 /* 01038 80AD4B38 3C0740C0 */ lui $a3, 0x40C0 ## $a3 = 40C00000 /* 0103C 80AD4B3C 0C01E107 */ jal Math_SmoothScaleMaxF /* 01040 80AD4B40 8D850024 */ lw $a1, 0x0024($t4) ## 00000024 /* 01044 80AD4B44 8FAD002C */ lw $t5, 0x002C($sp) /* 01048 80AD4B48 3C063E4C */ lui $a2, 0x3E4C ## $a2 = 3E4C0000 /* 0104C 80AD4B4C 34C6CCCD */ ori $a2, $a2, 0xCCCD ## $a2 = 3E4CCCCD /* 01050 80AD4B50 26040010 */ addiu $a0, $s0, 0x0010 ## $a0 = 00000010 /* 01054 80AD4B54 3C0740C0 */ lui $a3, 0x40C0 ## $a3 = 40C00000 /* 01058 80AD4B58 0C01E107 */ jal Math_SmoothScaleMaxF /* 0105C 80AD4B5C 8DA5002C */ lw $a1, 0x002C($t5) ## 0000002C /* 01060 80AD4B60 86050032 */ lh $a1, 0x0032($s0) ## 00000032 /* 01064 80AD4B64 240E0200 */ addiu $t6, $zero, 0x0200 ## $t6 = 00000200 /* 01068 80AD4B68 AFAE0010 */ sw $t6, 0x0010($sp) /* 0106C 80AD4B6C 260400B6 */ addiu $a0, $s0, 0x00B6 ## $a0 = 000000B6 /* 01070 80AD4B70 24060001 */ addiu $a2, $zero, 0x0001 ## $a2 = 00000001 /* 01074 80AD4B74 0C01E1A7 */ jal Math_SmoothScaleMaxMinS /* 01078 80AD4B78 24070800 */ addiu $a3, $zero, 0x0800 ## $a3 = 00000800 /* 0107C 80AD4B7C 8FAF002C */ lw $t7, 0x002C($sp) /* 01080 80AD4B80 C6040008 */ lwc1 $f4, 0x0008($s0) ## 00000008 /* 01084 80AD4B84 3C0142C8 */ lui $at, 0x42C8 ## $at = 42C80000 /* 01088 80AD4B88 C5E00024 */ lwc1 $f0, 0x0024($t7) ## 00000024 /* 0108C 80AD4B8C 44816000 */ mtc1 $at, $f12 ## $f12 = 100.00 /* 01090 80AD4B90 3C01C2C8 */ lui $at, 0xC2C8 ## $at = C2C80000 /* 01094 80AD4B94 46002081 */ sub.s $f2, $f4, $f0 /* 01098 80AD4B98 4602603C */ c.lt.s $f12, $f2 /* 0109C 80AD4B9C 00000000 */ nop /* 010A0 80AD4BA0 45020007 */ bc1fl .L80AD4BC0 /* 010A4 80AD4BA4 44817000 */ mtc1 $at, $f14 ## $f14 = -100.00 /* 010A8 80AD4BA8 460C0200 */ add.s $f8, $f0, $f12 /* 010AC 80AD4BAC 3C01C2C8 */ lui $at, 0xC2C8 ## $at = C2C80000 /* 010B0 80AD4BB0 44817000 */ mtc1 $at, $f14 ## $f14 = -100.00 /* 010B4 80AD4BB4 10000009 */ beq $zero, $zero, .L80AD4BDC /* 010B8 80AD4BB8 E6080008 */ swc1 $f8, 0x0008($s0) ## 00000008 /* 010BC 80AD4BBC 44817000 */ mtc1 $at, $f14 ## $f14 = -100.00 .L80AD4BC0: /* 010C0 80AD4BC0 00000000 */ nop /* 010C4 80AD4BC4 460E103C */ c.lt.s $f2, $f14 /* 010C8 80AD4BC8 00000000 */ nop /* 010CC 80AD4BCC 45020004 */ bc1fl .L80AD4BE0 /* 010D0 80AD4BD0 8FB9002C */ lw $t9, 0x002C($sp) /* 010D4 80AD4BD4 460E0180 */ add.s $f6, $f0, $f14 /* 010D8 80AD4BD8 E6060008 */ swc1 $f6, 0x0008($s0) ## 00000008 .L80AD4BDC: /* 010DC 80AD4BDC 8FB9002C */ lw $t9, 0x002C($sp) .L80AD4BE0: /* 010E0 80AD4BE0 C60A0010 */ lwc1 $f10, 0x0010($s0) ## 00000010 /* 010E4 80AD4BE4 C720002C */ lwc1 $f0, 0x002C($t9) ## 0000002C /* 010E8 80AD4BE8 46005081 */ sub.s $f2, $f10, $f0 /* 010EC 80AD4BEC 4602603C */ c.lt.s $f12, $f2 /* 010F0 80AD4BF0 00000000 */ nop /* 010F4 80AD4BF4 45020005 */ bc1fl .L80AD4C0C /* 010F8 80AD4BF8 460E103C */ c.lt.s $f2, $f14 /* 010FC 80AD4BFC 460C0400 */ add.s $f16, $f0, $f12 /* 01100 80AD4C00 10000007 */ beq $zero, $zero, .L80AD4C20 /* 01104 80AD4C04 E6100010 */ swc1 $f16, 0x0010($s0) ## 00000010 /* 01108 80AD4C08 460E103C */ c.lt.s $f2, $f14 .L80AD4C0C: /* 0110C 80AD4C0C 00000000 */ nop /* 01110 80AD4C10 45000003 */ bc1f .L80AD4C20 /* 01114 80AD4C14 00000000 */ nop /* 01118 80AD4C18 460E0480 */ add.s $f18, $f0, $f14 /* 0111C 80AD4C1C E6120010 */ swc1 $f18, 0x0010($s0) ## 00000010 .L80AD4C20: /* 01120 80AD4C20 0C01DE1C */ jal Math_Sins ## sins? /* 01124 80AD4C24 86040032 */ lh $a0, 0x0032($s0) ## 00000032 /* 01128 80AD4C28 C608021C */ lwc1 $f8, 0x021C($s0) ## 0000021C /* 0112C 80AD4C2C C6040008 */ lwc1 $f4, 0x0008($s0) ## 00000008 /* 01130 80AD4C30 86040032 */ lh $a0, 0x0032($s0) ## 00000032 /* 01134 80AD4C34 46080182 */ mul.s $f6, $f0, $f8 /* 01138 80AD4C38 46062281 */ sub.s $f10, $f4, $f6 /* 0113C 80AD4C3C 0C01DE0D */ jal Math_Coss ## coss? /* 01140 80AD4C40 E60A0024 */ swc1 $f10, 0x0024($s0) ## 00000024 /* 01144 80AD4C44 C612021C */ lwc1 $f18, 0x021C($s0) ## 0000021C /* 01148 80AD4C48 C6100010 */ lwc1 $f16, 0x0010($s0) ## 00000010 /* 0114C 80AD4C4C 86180196 */ lh $t8, 0x0196($s0) ## 00000196 /* 01150 80AD4C50 46120202 */ mul.s $f8, $f0, $f18 /* 01154 80AD4C54 46088101 */ sub.s $f4, $f16, $f8 /* 01158 80AD4C58 17000005 */ bne $t8, $zero, .L80AD4C70 /* 0115C 80AD4C5C E604002C */ swc1 $f4, 0x002C($s0) ## 0000002C /* 01160 80AD4C60 0C2B5064 */ jal func_80AD4190 /* 01164 80AD4C64 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000 /* 01168 80AD4C68 10000004 */ beq $zero, $zero, .L80AD4C7C /* 0116C 80AD4C6C 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000 .L80AD4C70: /* 01170 80AD4C70 0C2B5743 */ jal func_80AD5D0C /* 01174 80AD4C74 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000 /* 01178 80AD4C78 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000 .L80AD4C7C: /* 0117C 80AD4C7C 0C2B511C */ jal func_80AD4470 /* 01180 80AD4C80 8FA50034 */ lw $a1, 0x0034($sp) /* 01184 80AD4C84 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000 /* 01188 80AD4C88 0C00BE5D */ jal func_8002F974 /* 0118C 80AD4C8C 24053071 */ addiu $a1, $zero, 0x3071 ## $a1 = 00003071 /* 01190 80AD4C90 8FBF0024 */ lw $ra, 0x0024($sp) /* 01194 80AD4C94 8FB00020 */ lw $s0, 0x0020($sp) /* 01198 80AD4C98 27BD0030 */ addiu $sp, $sp, 0x0030 ## $sp = 00000000 /* 0119C 80AD4C9C 03E00008 */ jr $ra /* 011A0 80AD4CA0 00000000 */ nop
412
0.771162
1
0.771162
game-dev
MEDIA
0.885417
game-dev
0.820441
1
0.820441
bibendovsky/ltjs
1,734
game/objectdll/objectshared/singleplayermissionmgr.cpp
// ----------------------------------------------------------------------- // // // MODULE : SinglePlayerMissionMgr.cpp // // PURPOSE : Implementation of class to handle deathmatch missions // // (c) 2002 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #include "stdafx.h" #include "singleplayermissionmgr.h" #include "musicmgr.h" #include "playerobj.h" #include "msgids.h" #include "missionbutemgr.h" // --------------------------------------------------------------------------- // // // ROUTINE: CSinglePlayerMissionMgr::StartGame // // PURPOSE: Default start game. // // --------------------------------------------------------------------------- // bool CSinglePlayerMissionMgr::StartGame( ILTMessage_Read& msg ) { if( !g_pMissionButeMgr->Init( MISSION_DEFAULT_FILE )) return false; if( !CServerMissionMgr::StartGame( msg )) return false; g_pMusicMgr->Enable( ); return true; } // --------------------------------------------------------------------------- // // // ROUTINE: CSinglePlayerMissionMgr::EndGame // // PURPOSE: End the game. // // --------------------------------------------------------------------------- // bool CSinglePlayerMissionMgr::EndGame( ) { // Call base. if( !CServerMissionMgr::EndGame( )) return false; // Tell the players to prepare to exit a level. CPlayerObj::PlayerObjList::const_iterator iter = CPlayerObj::GetPlayerObjList( ).begin( ); while( iter != CPlayerObj::GetPlayerObjList( ).end( )) { CPlayerObj* pPlayerObj = *iter; pPlayerObj->HandlePreExit(); iter++; } // Tell the client the game is over. SendEmptyClientMsg( MID_END_GAME, NULL, MESSAGE_GUARANTEED ); return true; }
412
0.729149
1
0.729149
game-dev
MEDIA
0.687278
game-dev,networking
0.830357
1
0.830357
ProjectIgnis/CardScripts
3,376
official/c111280.lua
--黒魔導強化 --Dark Magic Expanded local s,id=GetID() function s.initial_effect(c) --Apply various effects, depending on the number of "Dark Magicians" and "Dark Magician Girls" in GY local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_ATKCHANGE) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP) e1:SetHintTiming(TIMING_DAMAGE_STEP) e1:SetCondition(s.condition) e1:SetTarget(s.target) e1:SetOperation(s.activate) c:RegisterEffect(e1) end s.listed_names={CARD_DARK_MAGICIAN,CARD_DARK_MAGICIAN_GIRL} function s.cfilter(c) return c:IsFaceup() and c:IsCode(CARD_DARK_MAGICIAN,CARD_DARK_MAGICIAN_GIRL) end function s.condition(e,tp,eg,ep,ev,re,r,rp) local ct=Duel.GetMatchingGroupCount(s.cfilter,tp,LOCATION_ONFIELD|LOCATION_GRAVE,LOCATION_ONFIELD|LOCATION_GRAVE,nil) return ct>0 and aux.StatChangeDamageStepCondition() end function s.filter(c) return c:IsFaceup() and c:IsRace(RACE_SPELLCASTER) and c:IsAttribute(ATTRIBUTE_DARK) end function s.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then local ct=Duel.GetMatchingGroupCount(s.cfilter,tp,LOCATION_ONFIELD|LOCATION_GRAVE,LOCATION_ONFIELD|LOCATION_GRAVE,nil) if ct<=1 then return Duel.IsExistingMatchingCard(s.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end return true end end function s.activate(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetMatchingGroup(s.cfilter,tp,LOCATION_ONFIELD|LOCATION_GRAVE,LOCATION_ONFIELD|LOCATION_GRAVE,nil) local ct=#g if ct>=1 then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP) local g=Duel.SelectMatchingCard(tp,s.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil) local tc=g:GetFirst() if tc then Duel.HintSelection(g) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetReset(RESETS_STANDARD_PHASE_END) e1:SetValue(1000) tc:RegisterEffect(e1) end end if ct>=2 then local e2=Effect.CreateEffect(e:GetHandler()) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e2:SetCode(EVENT_CHAINING) e2:SetOperation(s.chainop) e2:SetReset(RESET_PHASE|PHASE_END) Duel.RegisterEffect(e2,tp) local e3=Effect.CreateEffect(e:GetHandler()) e3:SetType(EFFECT_TYPE_FIELD) e3:SetCode(EFFECT_INDESTRUCTABLE_EFFECT) e3:SetProperty(EFFECT_FLAG_SET_AVAILABLE) e3:SetTargetRange(LOCATION_ONFIELD,0) e3:SetTarget(s.indtg) e3:SetValue(aux.indoval) e3:SetReset(RESET_PHASE|PHASE_END) Duel.RegisterEffect(e3,tp) aux.RegisterClientHint(e:GetHandler(),nil,tp,1,1,aux.Stringid(id,1),nil) end if ct>=3 then local g=Duel.GetMatchingGroup(s.filter,tp,LOCATION_MZONE,0,nil) local tc=g:GetFirst() for tc in aux.Next(g) do --Your DARK spellcasters monsters are unaffected by opponent's card effects local e4=Effect.CreateEffect(e:GetHandler()) e4:SetDescription(3110) e4:SetProperty(EFFECT_FLAG_CLIENT_HINT) e4:SetType(EFFECT_TYPE_SINGLE) e4:SetCode(EFFECT_IMMUNE_EFFECT) e4:SetValue(s.efilter) e4:SetReset(RESETS_STANDARD_PHASE_END) e4:SetOwnerPlayer(tp) tc:RegisterEffect(e4) end end end function s.chainop(e,tp,eg,ep,ev,re,r,rp) if re:IsSpellTrapEffect() and ep==tp then Duel.SetChainLimit(s.chainlm) end end function s.chainlm(e,rp,tp) return tp==rp end function s.indtg(e,c) return c:IsSpellTrap() end function s.efilter(e,re) return e:GetOwnerPlayer()~=re:GetOwnerPlayer() end
412
0.931589
1
0.931589
game-dev
MEDIA
0.991974
game-dev
0.977428
1
0.977428
StinkySteak/unity-network-library-benchmark-on-bad-network-condition
13,546
Mirror/Assets/Mirror/Core/SyncSet.cs
using System; using System.Collections; using System.Collections.Generic; namespace Mirror { public class SyncSet<T> : SyncObject, ISet<T> { /// <summary>This is called after the item is added. T is the new item.</summary> public Action<T> OnAdd; /// <summary>This is called after the item is removed. T is the OLD item</summary> public Action<T> OnRemove; /// <summary> /// This is called for all changes to the Set. /// <para>For OP_ADD, T is the NEW value of the entry.</para> /// <para>For OP_REMOVE, T is the OLD value of the entry.</para> /// <para>For OP_CLEAR, T is default.</para> /// </summary> public Action<Operation, T> OnChange; /// <summary>This is called BEFORE the data is cleared</summary> public Action OnClear; // Deprecated 2024-03-22 [Obsolete("Use individual Actions, which pass OLD value where appropriate, instead.")] public Action<Operation, T> Callback; protected readonly ISet<T> objects; public int Count => objects.Count; public bool IsReadOnly => !IsWritable(); public enum Operation : byte { OP_ADD, OP_REMOVE, OP_CLEAR } struct Change { internal Operation operation; internal T item; } // list of changes. // -> insert/delete/clear is only ONE change // -> changing the same slot 10x caues 10 changes. // -> note that this grows until next sync(!) // TODO Dictionary<key, change> to avoid ever growing changes / redundant changes! readonly List<Change> changes = new List<Change>(); // how many changes we need to ignore // this is needed because when we initialize the list, // we might later receive changes that have already been applied // so we need to skip them int changesAhead; public SyncSet(ISet<T> objects) { this.objects = objects; } public override void Reset() { changes.Clear(); changesAhead = 0; objects.Clear(); } // throw away all the changes // this should be called after a successful sync public override void ClearChanges() => changes.Clear(); void AddOperation(Operation op, T oldItem, T newItem, bool checkAccess) { if (checkAccess && IsReadOnly) throw new InvalidOperationException("SyncSets can only be modified by the owner."); Change change = default; switch (op) { case Operation.OP_ADD: change = new Change { operation = op, item = newItem }; break; case Operation.OP_REMOVE: change = new Change { operation = op, item = oldItem }; break; case Operation.OP_CLEAR: change = new Change { operation = op, item = default }; break; } if (IsRecording()) { changes.Add(change); OnDirty?.Invoke(); } switch (op) { case Operation.OP_ADD: OnAdd?.Invoke(newItem); OnChange?.Invoke(op, newItem); #pragma warning disable CS0618 // Type or member is obsolete Callback?.Invoke(op, newItem); #pragma warning restore CS0618 // Type or member is obsolete break; case Operation.OP_REMOVE: OnRemove?.Invoke(oldItem); OnChange?.Invoke(op, oldItem); #pragma warning disable CS0618 // Type or member is obsolete Callback?.Invoke(op, oldItem); #pragma warning restore CS0618 // Type or member is obsolete break; case Operation.OP_CLEAR: OnClear?.Invoke(); OnChange?.Invoke(op, default); #pragma warning disable CS0618 // Type or member is obsolete Callback?.Invoke(op, default); #pragma warning restore CS0618 // Type or member is obsolete break; } } void AddOperation(Operation op, bool checkAccess) => AddOperation(op, default, default, checkAccess); public override void OnSerializeAll(NetworkWriter writer) { // if init, write the full list content writer.WriteUInt((uint)objects.Count); foreach (T obj in objects) writer.Write(obj); // all changes have been applied already // thus the client will need to skip all the pending changes // or they would be applied again. // So we write how many changes are pending writer.WriteUInt((uint)changes.Count); } public override void OnSerializeDelta(NetworkWriter writer) { // write all the queued up changes writer.WriteUInt((uint)changes.Count); for (int i = 0; i < changes.Count; i++) { Change change = changes[i]; writer.WriteByte((byte)change.operation); switch (change.operation) { case Operation.OP_ADD: writer.Write(change.item); break; case Operation.OP_REMOVE: writer.Write(change.item); break; case Operation.OP_CLEAR: break; } } } public override void OnDeserializeAll(NetworkReader reader) { // if init, write the full list content int count = (int)reader.ReadUInt(); objects.Clear(); changes.Clear(); for (int i = 0; i < count; i++) { T obj = reader.Read<T>(); objects.Add(obj); } // We will need to skip all these changes // the next time the list is synchronized // because they have already been applied changesAhead = (int)reader.ReadUInt(); } public override void OnDeserializeDelta(NetworkReader reader) { int changesCount = (int)reader.ReadUInt(); for (int i = 0; i < changesCount; i++) { Operation operation = (Operation)reader.ReadByte(); // apply the operation only if it is a new change // that we have not applied yet bool apply = changesAhead == 0; T oldItem = default; T newItem = default; switch (operation) { case Operation.OP_ADD: newItem = reader.Read<T>(); if (apply) { objects.Add(newItem); // add dirty + changes. // ClientToServer needs to set dirty in server OnDeserialize. // no access check: server OnDeserialize can always // write, even for ClientToServer (for broadcasting). AddOperation(Operation.OP_ADD, default, newItem, false); } break; case Operation.OP_REMOVE: oldItem = reader.Read<T>(); if (apply) { objects.Remove(oldItem); // add dirty + changes. // ClientToServer needs to set dirty in server OnDeserialize. // no access check: server OnDeserialize can always // write, even for ClientToServer (for broadcasting). AddOperation(Operation.OP_REMOVE, oldItem, default, false); } break; case Operation.OP_CLEAR: if (apply) { // add dirty + changes. // ClientToServer needs to set dirty in server OnDeserialize. // no access check: server OnDeserialize can always // write, even for ClientToServer (for broadcasting). AddOperation(Operation.OP_CLEAR, false); // clear after invoking the callback so users can iterate the set // and take appropriate action on the items before they are wiped. objects.Clear(); } break; } if (!apply) { // we just skipped this change changesAhead--; } } } public bool Add(T item) { if (objects.Add(item)) { AddOperation(Operation.OP_ADD, default, item, true); return true; } return false; } void ICollection<T>.Add(T item) { if (objects.Add(item)) AddOperation(Operation.OP_ADD, default, item, true); } public void Clear() { AddOperation(Operation.OP_CLEAR, true); // clear after invoking the callback so users can iterate the set // and take appropriate action on the items before they are wiped. objects.Clear(); } public bool Contains(T item) => objects.Contains(item); public void CopyTo(T[] array, int index) => objects.CopyTo(array, index); public bool Remove(T item) { if (objects.Remove(item)) { AddOperation(Operation.OP_REMOVE, item, default, true); return true; } return false; } public IEnumerator<T> GetEnumerator() => objects.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public void ExceptWith(IEnumerable<T> other) { if (other == this) { Clear(); return; } // remove every element in other from this foreach (T element in other) Remove(element); } public void IntersectWith(IEnumerable<T> other) { if (other is ISet<T> otherSet) IntersectWithSet(otherSet); else { HashSet<T> otherAsSet = new HashSet<T>(other); IntersectWithSet(otherAsSet); } } void IntersectWithSet(ISet<T> otherSet) { List<T> elements = new List<T>(objects); foreach (T element in elements) if (!otherSet.Contains(element)) Remove(element); } public bool IsProperSubsetOf(IEnumerable<T> other) => objects.IsProperSubsetOf(other); public bool IsProperSupersetOf(IEnumerable<T> other) => objects.IsProperSupersetOf(other); public bool IsSubsetOf(IEnumerable<T> other) => objects.IsSubsetOf(other); public bool IsSupersetOf(IEnumerable<T> other) => objects.IsSupersetOf(other); public bool Overlaps(IEnumerable<T> other) => objects.Overlaps(other); public bool SetEquals(IEnumerable<T> other) => objects.SetEquals(other); // custom implementation so we can do our own Clear/Add/Remove for delta public void SymmetricExceptWith(IEnumerable<T> other) { if (other == this) Clear(); else foreach (T element in other) if (!Remove(element)) Add(element); } // custom implementation so we can do our own Clear/Add/Remove for delta public void UnionWith(IEnumerable<T> other) { if (other != this) foreach (T element in other) Add(element); } } public class SyncHashSet<T> : SyncSet<T> { public SyncHashSet() : this(EqualityComparer<T>.Default) { } public SyncHashSet(IEqualityComparer<T> comparer) : base(new HashSet<T>(comparer ?? EqualityComparer<T>.Default)) { } // allocation free enumerator public new HashSet<T>.Enumerator GetEnumerator() => ((HashSet<T>)objects).GetEnumerator(); } public class SyncSortedSet<T> : SyncSet<T> { public SyncSortedSet() : this(Comparer<T>.Default) { } public SyncSortedSet(IComparer<T> comparer) : base(new SortedSet<T>(comparer ?? Comparer<T>.Default)) { } // allocation free enumerator public new SortedSet<T>.Enumerator GetEnumerator() => ((SortedSet<T>)objects).GetEnumerator(); } }
412
0.932435
1
0.932435
game-dev
MEDIA
0.211931
game-dev
0.957445
1
0.957445
PotRooms/StarResonanceData
5,505
lua/rednode/face_red.lua
local FaceRed = {} local FaceUnlockCostData = {} function FaceRed.changeItem(item) if not item then return end for type, info in pairs(FaceUnlockCostData) do for i = 1, #info do local faceId = info[i].faceId local unlock = info[i].unlock for j = 1, #unlock do if unlock[j][1] == item.configId then if FaceRed.CheckFaceCanUnlock(unlock) then FaceRed.addFaceRed(type, faceId) end break end end end end Z.EventMgr:Dispatch(Z.ConstValue.Face.FaceOptionCanUnlock) end function FaceRed.InitFaceUnlockCostData() FaceUnlockCostData = {} local faceTableData = Z.TableMgr.GetTable("FaceTableMgr").GetDatas() for faceId, info in pairs(faceTableData) do if #info.Unlock > 0 and FaceRed.IsShowFaceRedType(info.Type) and not FaceRed.checkFaceIsUnlock(faceId) and FaceRed.checkIsCanUse(info) then if not FaceUnlockCostData[info.Type] then FaceUnlockCostData[info.Type] = {} end if FaceRed.CheckFaceCanUnlock(info.Unlock) then FaceRed.addFaceRed(info.Type, faceId) end table.insert(FaceUnlockCostData[info.Type], { faceId = faceId, unlock = info.Unlock }) end end Z.RedPointMgr.RefreshRedNodeState(E.RedType.FaceEditor) end function FaceRed.checkFaceIsUnlock(faceId) return Z.ContainerMgr.CharSerialize.roleFace.unlockItemMap[faceId] end function FaceRed.checkIsCanUse(faceTableRow) if faceTableRow.IsHide == 1 then return false end local faceData = Z.DataMgr.Get("face_data") if faceTableRow.Sex ~= faceData:GetPlayerGender() and faceTableRow.Sex ~= 0 then return false end if 0 < faceTableRow.FaceShapeId then local faceShapeId = faceData:GetFaceOptionValue(Z.PbEnum("EFaceDataType", "FaceShapeID")) if faceShapeId ~= faceTableRow.FaceShapeId then return false end end for _, bodySize in pairs(faceTableRow.Model) do if bodySize == 0 or bodySize == faceData:GetPlayerBodySize() then return true end end return false end function FaceRed.UpdateFaceUnlockCostData(faceId) local faceRow = Z.TableMgr.GetTable("FaceTableMgr").GetRow(faceId, true) if faceRow and FaceUnlockCostData[faceRow.Type] then for i = #FaceUnlockCostData[faceRow.Type], 1, -1 do if FaceUnlockCostData[faceRow.Type][i].faceId == faceId then table.remove(FaceUnlockCostData[faceRow.Type], i) FaceRed.removeFaceRed(faceRow.Type, faceId) return end end end end function FaceRed.CheckFaceCanUnlock(unlock) local itemVm = Z.VMMgr.GetVM("items") local isCanUnlock = true for i = 1, #unlock do local ownNum = itemVm.GetItemTotalCount(unlock[i][1]) if ownNum < unlock[i][2] then isCanUnlock = false break end end return isCanUnlock end function FaceRed.IsShowFaceRedType(type) return type == Z.PbEnum("EFaceDataType", "HairID") or type == Z.PbEnum("EFaceDataType", "FrontHairID") or type == Z.PbEnum("EFaceDataType", "BackHairID") or type == Z.PbEnum("EFaceDataType", "DullHairID") end function FaceRed.addFaceRed(type, faceId) local redNodeName = string.zconcat("FaceUnlockRed", faceId) if type == Z.PbEnum("EFaceDataType", "HairID") then Z.RedPointMgr.AddChildNodeData(E.RedType.FaceEditorHairWhole, E.RedType.FaceEditorHairWhole, redNodeName) elseif type == Z.PbEnum("EFaceDataType", "FrontHairID") then Z.RedPointMgr.AddChildNodeData(E.RedType.FaceEditorHairCustomFront, E.RedType.FaceEditorHairCustomFront, redNodeName) elseif type == Z.PbEnum("EFaceDataType", "BackHairID") then Z.RedPointMgr.AddChildNodeData(E.RedType.FaceEditorHairCustomBack, E.RedType.FaceEditorHairCustomBack, redNodeName) elseif type == Z.PbEnum("EFaceDataType", "DullHairID") then Z.RedPointMgr.AddChildNodeData(E.RedType.FaceEditorHairCustomDull, E.RedType.FaceEditorHairCustomDull, redNodeName) end Z.RedPointMgr.UpdateNodeCount(redNodeName, 1) end function FaceRed.removeFaceRed(type, faceId) local redNodeName = string.zconcat("FaceUnlockRed", faceId) Z.RedPointMgr.UpdateNodeCount(redNodeName, 0) if type == Z.PbEnum("EFaceDataType", "HairID") then Z.RedPointMgr.RemoveChildNodeData(E.RedType.FaceEditorHairWhole, redNodeName) Z.RedPointMgr.RefreshRedNodeState(E.RedType.FaceEditorHairWhole) elseif type == Z.PbEnum("EFaceDataType", "FrontHairID") then Z.RedPointMgr.RemoveChildNodeData(E.RedType.FaceEditorHairCustomFront, redNodeName) Z.RedPointMgr.RefreshRedNodeState(E.RedType.FaceEditorHairCustomFront) elseif type == Z.PbEnum("EFaceDataType", "BackHairID") then Z.RedPointMgr.RemoveChildNodeData(E.RedType.FaceEditorHairCustomBack, redNodeName) Z.RedPointMgr.RefreshRedNodeState(E.RedType.FaceEditorHairCustomBack) elseif type == Z.PbEnum("EFaceDataType", "DullHairID") then Z.RedPointMgr.RemoveChildNodeData(E.RedType.FaceEditorHairCustomDull, redNodeName) Z.RedPointMgr.RefreshRedNodeState(E.RedType.FaceEditorHairCustomDull) end end function FaceRed.Init() Z.EventMgr:Add(Z.ConstValue.Backpack.AddItem, FaceRed.changeItem) Z.EventMgr:Add(Z.ConstValue.Backpack.DelItem, FaceRed.changeItem) Z.EventMgr:Add(Z.ConstValue.Backpack.ItemCountChange, FaceRed.changeItem) end function FaceRed.UnInit() Z.EventMgr:Remove(Z.ConstValue.Backpack.AddItem, FaceRed.changeItem) Z.EventMgr:Remove(Z.ConstValue.Backpack.DelItem, FaceRed.changeItem) Z.EventMgr:Remove(Z.ConstValue.Backpack.ItemCountChange, FaceRed.changeItem) end return FaceRed
412
0.83746
1
0.83746
game-dev
MEDIA
0.312102
game-dev
0.963804
1
0.963804
oculus-samples/voicesdk-samples-whisperer
1,394
Assets/Whisperer/Scenes/Level 4/Level_4_Manager.cs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ using UnityEngine; namespace Whisperer { public class Level_4_Manager : LevelManager { [SerializeField] private Material _plantsMaterial; protected override void Start() { base.Start(); _speakGestureWatcher.AllowSpeak = !_levelLogicEnabled; if (_levelLogicEnabled) { _allListenableScripts.ForEach(l => l.SetListeningActive(false)); _allListenableScripts.ForEach(l => l.IsActionable = false); } _plantsMaterial.SetFloat("_Alive_Dead_Lerp", 0); UXManager.Instance.SetDisplayEnabled("SettingsMenu", false); } public override void StartLevel() { _hands.SetRay(); FindObjectOfType<CameraColorOverlay>().SetTargetColor(Color.black); if (!_inTransition) { AudioManager.Instance.AuxFader.PlayReverse(5); AudioManager.Instance.MusicFader.Play(0); AudioManager.Instance.PlayMusic("EndMusic"); } } protected override void LevelLoadComplete() { base.LevelLoadComplete(); } } }
412
0.916426
1
0.916426
game-dev
MEDIA
0.897919
game-dev
0.988972
1
0.988972
Asher-Ul-Haque/Just_Forge_2D
5,425
src/main/java/Just_Forge_2D/EditorSystem/Windows/MenuBar.java
package Just_Forge_2D.EditorSystem.Windows; import Just_Forge_2D.AssetPool.AssetPool; import Just_Forge_2D.AssetPool.AssetPoolSerializer; import Just_Forge_2D.EditorSystem.Forge; import Just_Forge_2D.EditorSystem.Icons; import Just_Forge_2D.EditorSystem.ImGUIManager; import Just_Forge_2D.EventSystem.EventManager; import Just_Forge_2D.EventSystem.Events.Event; import Just_Forge_2D.EventSystem.Events.EventTypes; import Just_Forge_2D.GameSystem.GameCodeLoader; import Just_Forge_2D.GameSystem.GameManager; import Just_Forge_2D.GameSystem.ProjectManager; import Just_Forge_2D.SceneSystem.SceneSystemManager; import Just_Forge_2D.Utils.Logger; import Just_Forge_2D.Utils.Settings; import Just_Forge_2D.WindowSystem.GameWindow; import imgui.ImGui; import org.lwjgl.util.tinyfd.TinyFileDialogs; public class MenuBar { public static void render() { ImGui.beginMainMenuBar(); if (ImGui.beginMenu(Icons.Gamepad + " Project")) { if (ImGui.menuItem(Icons.Code + " Recompile Game")) { GameManager.buildUserCode(); } if (ImGui.menuItem(Icons.Redo + " Reload Assets")) { AssetPool.reloadAssets(); } if (ImGui.menuItem(Icons.FolderOpen + " Open in Browser")) { ProjectManager.openProjectInBrowser(); } if (ImGui.menuItem(Icons.WindowClose + " Close")) { AssetPoolSerializer.saveAssetPool(Forge.projectDir + "/.forge/Pool.justForgeFile"); AssetPool.clearSpriteSheetPool(); AssetPool.clearShaderPool(); AssetPool.clearSoundPool(); AssetPool.clearTexturePool(); SceneSystemManager.save(GameWindow.getCurrentScene()); GameCodeLoader.terminate(); GameCodeLoader.closeEye(); EventManager.notify(null, new Event(EventTypes.ForgeStop)); Forge.setCurrentState(Forge.state.isSplashScreen); GameWindow.get().restore(); GameWindow.get().resetTitleBar(); SplashScreen.restart(); SplashScreen.initialize(); } ImGui.endMenu(); } ImGui.separator(); if (ImGui.beginMenu(Icons.Film + " Scene")) { if (ImGui.menuItem(Icons.Save + " Save", "")) { EventManager.notify(null, new Event(EventTypes.SaveLevel)); } if (ImGui.menuItem(Icons.Save+ " Save As", "")) { String savePath = TinyFileDialogs.tinyfd_saveFileDialog("Choose Save Location", Forge.projectDir + Settings.DEFAULT_SAVE_DIR(),null,null); if (savePath != null) { if (!savePath.endsWith(".justForgeFile")) savePath += ".justForgeFile"; GameWindow.getCurrentScene().setSavePath(savePath); EventManager.notify(null, new Event(EventTypes.SaveLevel)); } } if (ImGui.menuItem(Icons.FileImport + " Load", "")) { EventManager.notify(null, new Event(EventTypes.LoadLevel)); } if (ImGui.menuItem(Icons.FileImport + " Load From", "")) { String savePath = TinyFileDialogs.tinyfd_openFileDialog("Choose Save Location", Forge.projectDir + Settings.DEFAULT_SAVE_DIR(),null,null, false); if (savePath != null) { if (!savePath.endsWith(".justForgeFile")) { Logger.FORGE_LOG_ERROR("Couldn't open save file. Must be a .justForgeFile"); } else { GameWindow.getCurrentScene().setSavePath(savePath); EventManager.notify(null, new Event(EventTypes.LoadLevel)); } } } ImGui.endMenu(); } ImGui.separator(); if (ImGui.beginMenu(Icons.Bug + " Run")) { if (ImGui.menuItem(Icons.MugHot + " Build JAR")) { AssetPoolSerializer.saveAssetPool(Forge.projectDir + "/.forge/Pool.justForgeFile"); SceneSystemManager.save(GameWindow.getCurrentScene()); Settings.save(); GameManager.compileJar(); } if (ImGui.menuItem(Icons.Terminal + " Run JAR")) { GameManager.runCode(); } ImGui.endMenu(); } ImGui.separator(); if (ImGui.beginMenu(Icons.Eye + " View")) { for (int i = 0; i < ImGUIManager.getRenderable().size(); ++i) { if (ImGUIManager.getRenderableNames().get(i).startsWith("Keyboard")) continue; Boolean b = ImGUIManager.getRenderable().get(i); if (ImGui.checkbox(ImGUIManager.getRenderableNames().get(i), b)) b = !b; ImGUIManager.getRenderable().set(i, b); } ImGui.endMenu(); } ImGui.separator(); if (ImGui.beginMenu(Icons.Cog + " Settings")) { Settings.trigger(); ImGui.endMenu(); } ImGui.separator(); ImGui.endMainMenuBar(); } }
412
0.957109
1
0.957109
game-dev
MEDIA
0.916977
game-dev
0.989283
1
0.989283
dilmerv/OculusQuestHandTrackingPhysicsURP
2,436
Assets/Oculus/Avatar/Samples/SocialStarter/Assets/Scripts/PlayerController.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using Oculus.Platform; using Oculus.Platform.Models; public class PlayerController : SocialPlatformManager { // Secondary camera to debug and view the whole scene from above public Camera spyCamera; // The OVRCameraRig for the main player so we can disable it private GameObject cameraRig; private bool showUI = true; public override void Awake() { base.Awake(); cameraRig = localPlayerHead.gameObject; } // Use this for initialization public override void Start() { base.Start(); spyCamera.enabled = false; } // Update is called once per frame public override void Update() { base.Update(); checkInput(); } // Check for input from the touch controllers void checkInput() { if (UnityEngine.Application.platform == RuntimePlatform.Android) { // GearVR Controller // Bring up friend invite list if (OVRInput.GetDown(OVRInput.Button.Back)) { Rooms.LaunchInvitableUserFlow(roomManager.roomID); } // Toggle Camera if (OVRInput.GetDown(OVRInput.Button.PrimaryTouchpad)) { ToggleCamera(); } // Toggle Help UI if (OVRInput.GetDown(OVRInput.Button.PrimaryIndexTrigger)) { ToggleUI(); } } else { // PC Touch // Bring up friend invite list if (OVRInput.GetDown(OVRInput.Button.Three)) { Rooms.LaunchInvitableUserFlow (roomManager.roomID); } // Toggle Camera if (OVRInput.GetDown(OVRInput.Button.Four)) { ToggleCamera(); } // Toggle Help UI if (OVRInput.GetDown(OVRInput.Button.PrimaryThumbstick)) { ToggleUI(); } } } void ToggleCamera() { spyCamera.enabled = !spyCamera.enabled; localAvatar.ShowThirdPerson = !localAvatar.ShowThirdPerson; cameraRig.SetActive(!cameraRig.activeSelf); } void ToggleUI() { showUI = !showUI; helpPanel.SetActive(showUI); localAvatar.ShowLeftController(showUI); } }
412
0.957583
1
0.957583
game-dev
MEDIA
0.419295
game-dev
0.946629
1
0.946629
OregonCore/OregonCore
4,683
src/scripts/EasternKingdoms/Stratholme/boss_order_of_silver_hand.cpp
/* * This file is part of the OregonCore 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 <https://www.gnu.org/licenses/>. */ /* ScriptData SDName: Boss_Silver_Hand_Bosses SD%Complete: 40 SDComment: Basic script to have support for Horde paladin epic mount (quest 9737). All 5 members of Order of the Silver Hand running this script (least for now) SDCategory: Stratholme EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "stratholme.h" /*##### # Additional: # Although this is a working solution, the correct would be in addition to check if Aurius is dead. # Once player extinguish the eternal flame (cast spell 31497->start event 11206) Aurius should become hostile. # Once Aurius is defeated, he should be the one summoning the ghosts. #####*/ #define SH_GREGOR 17910 #define SH_CATHELA 17911 #define SH_NEMAS 17912 #define SH_AELMAR 17913 #define SH_VICAR 17914 #define SH_QUEST_CREDIT 17915 #define SPELL_HOLY_LIGHT 25263 #define SPELL_DIVINE_SHIELD 13874 struct boss_silver_hand_bossesAI : public ScriptedAI { boss_silver_hand_bossesAI(Creature* c) : ScriptedAI(c) { pInstance = (ScriptedInstance*)c->GetInstanceData(); } ScriptedInstance* pInstance; uint32 HolyLight_Timer; uint32 DivineShield_Timer; void Reset() { HolyLight_Timer = 20000; DivineShield_Timer = 20000; if (pInstance) { switch (me->GetEntry()) { case SH_AELMAR: pInstance->SetData(TYPE_SH_AELMAR, 0); break; case SH_CATHELA: pInstance->SetData(TYPE_SH_CATHELA, 0); break; case SH_GREGOR: pInstance->SetData(TYPE_SH_GREGOR, 0); break; case SH_NEMAS: pInstance->SetData(TYPE_SH_NEMAS, 0); break; case SH_VICAR: pInstance->SetData(TYPE_SH_VICAR, 0); break; } } } void EnterCombat(Unit* /*who*/) { } void JustDied(Unit* Killer) { if (pInstance) { switch (me->GetEntry()) { case SH_AELMAR: pInstance->SetData(TYPE_SH_AELMAR, 2); break; case SH_CATHELA: pInstance->SetData(TYPE_SH_CATHELA, 2); break; case SH_GREGOR: pInstance->SetData(TYPE_SH_GREGOR, 2); break; case SH_NEMAS: pInstance->SetData(TYPE_SH_NEMAS, 2); break; case SH_VICAR: pInstance->SetData(TYPE_SH_VICAR, 2); break; } if (pInstance->GetData(TYPE_SH_QUEST) && Killer->GetTypeId() == TYPEID_PLAYER) CAST_PLR(Killer)->KilledMonsterCredit(SH_QUEST_CREDIT, me->GetGUID()); } } void UpdateAI(const uint32 diff) { //Return since we have no target if (!UpdateVictim()) return; if (HolyLight_Timer <= diff) { if (me->GetHealth() * 5 < me->GetMaxHealth()) { DoCast(me, SPELL_HOLY_LIGHT); HolyLight_Timer = 20000; } } else HolyLight_Timer -= diff; if (DivineShield_Timer <= diff) { if (me->GetHealth() * 20 < me->GetMaxHealth()) { DoCast(me, SPELL_DIVINE_SHIELD); DivineShield_Timer = 40000; } } else DivineShield_Timer -= diff; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_boss_silver_hand_bossesAI(Creature* pCreature) { return new boss_silver_hand_bossesAI (pCreature); } void AddSC_boss_order_of_silver_hand() { Script* newscript; newscript = new Script; newscript->Name = "boss_silver_hand_bosses"; newscript->GetAI = &GetAI_boss_silver_hand_bossesAI; newscript->RegisterSelf(); }
412
0.894708
1
0.894708
game-dev
MEDIA
0.837086
game-dev
0.99053
1
0.99053
RealismusModding/FS17_seasons
1,602
src/placeables/ssStorage.lua
---------------------------------------------------------------------------------------------------- -- STORAGE SCRIPT ---------------------------------------------------------------------------------------------------- -- Purpose: To change storage properties -- Authors: Rahkiin, reallogger, theSeb -- -- Copyright (c) Realismus Modding, 2017 ---------------------------------------------------------------------------------------------------- --FIXME: probably should not be in the placeable subdir but don't see a logical place for it right now. objects? misc? ssStorage = {} function ssStorage:preLoad() ssUtil.appendedFunction(Storage, "delete", ssStorage.storageDelete) ssUtil.appendedFunction(Storage, "update", ssStorage.storageUpdate) Storage.seasonLengthChanged = ssStorage.storageSeasonLengthChanged Storage.ssUpdateCosts = ssStorage.ssUpdateCosts end function ssStorage:loadMap() end function ssStorage:storageUpdate() if not self.ssLoadOnce then self.ssLoadOnce = true self.ssOriginalCost = self.costsPerFillLevelAndDay self:ssUpdateCosts() g_seasons.environment:addSeasonLengthChangeListener(self) end end function ssStorage:storageDelete() g_seasons.environment:removeSeasonLengthChangeListener(self) end function ssStorage:storageSeasonLengthChanged() self:ssUpdateCosts() end function ssStorage:ssUpdateCosts() local difficultyFac = 1 - (2 - g_currentMission.missionInfo.difficulty) * 0.1 self.costsPerFillLevelAndDay = self.ssOriginalCost / g_seasons.environment.daysInSeason * difficultyFac end
412
0.828015
1
0.828015
game-dev
MEDIA
0.117391
game-dev
0.875262
1
0.875262
Annoraaq/grid-engine
4,547
docs/p/installation/index.md
--- title: Installation parent: getting-started next: false --- # Installation > **_NOTE:_** For using GridEngine with TypeScript and Phaser.js check out [this example repository](https://github.com/Annoraaq/grid-engine-ts-example). ### NPM If you are using npm, you can install it via: ```bash $ npm i --save grid-engine ``` And then import it in your code: ```javascript import { GridEngine, GridEngineHeadless } from "grid-engine"; ``` ### Web If you are not using a package manager like npm, you can also include the minified web version (iife): ```html <!-- Download the .zip and copy GridEngine.min.js from dist directory --> <script src="GridEngine.min.js"></script> ``` ## Use as Phaser.js Plugin Add the plugin to your Phaser config: ```javascript const gameConfig = { // ... plugins: { scene: [ { key: "gridEngine", plugin: GridEngine, mapping: "gridEngine", }, ], }, // ... }; const game = new Phaser.Game(gameConfig); ``` Now you're all set to start using Grid Engine in your scenes! ```javascript function create() { // ... const gridEngineConfig = { characters: [ { id: "player", sprite: playerSprite, walkingAnimationMapping: 6, }, ], }; this.gridEngine.create( tilemap, // Phaser.Tilemaps.Tilemap gridEngineConfig, ); // ... } ``` ## Use Headless (Standalone) You have to provide a tilemap to the headless (standalone, no Phaser.js) version of Grid Engine. While the Phaser.js plugin receives a Phaser tilemap, the headless version needs one that implements the [Tilemap interface](https://annoraaq.github.io/grid-engine/api/interfaces/Tilemap.html). There is a simple implementation in Grid Engine that can be created from an array of integers (0 = non-blocking, 1 = blocking). You can also create your own implementation of the [Tilemap interface](https://annoraaq.github.io/grid-engine/api/interfaces/Tilemap.html) and pass it to Grid Engine. ```javascript import { GridEngineHeadless, ArrayTilemap } from "grid-engine"; const gridEngineHeadless = new GridEngineHeadless(); // A simple example tilemap created from an array. // 0 = non-blocking // 1 = blocking const tilemap = new ArrayTilemap({ someLayer: { data: [ [0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0], ], }, }); gridEngineHeadless.create(tilemap, { characters: [{ id: "player" }] }); ``` If you are using the web version (import via `<script>`), you can access `GridEngineHeadless` from the global variable `GridEngineImports`: ```javascript const gridEngineHeadless = new GridEngineImports.GridEngineHeadless(); // A simple example tilemap created from an array. // 0 = non-blocking // 1 = blocking const tilemap = new GridEngineImports.ArrayTilemap({ someLayer: { data: [ [0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0], ], }, }); gridEngineHeadless.create(tilemap, { characters: [{ id: "player" }] }); ``` ### Tiled Tilemaps for headless version (no Phaser) If you want to use the Tiled map editor for the headless Grid Engine version, you can use the [TiledTilemap](https://annoraaq.github.io/grid-engine/api/interfaces/Tilemap.html) implementation: > **_NOTE:_** Depending on your environment, the loading of the tilemap might look a bit different. On node.js you can use https://nodejs.dev/en/learn/reading-files-with-nodejs/ and `JSON.parse`. ```javascript import { GridEngineHeadless, TiledTilemap } from "grid-engine"; import * as someTilemap from "./path/to/tilemap.json"; const gridEngineHeadless = new GridEngineHeadless(); const tilemap = new TiledTilemap(someTilemap); gridEngineHeadless.create(tilemap, { characters: [{ id: "player" }] }); ``` ## Import Helpers Besides the GridEngine main class, you can also import several helpers. For example there is the `directionFromPos` helper function that gives you a `Direction` from a source to a target position. If you are importing the NPM module you can import it like: ```javascript import { GridEngine, // GridEngine Phaser Plugin main class GridEngineHeadless, // GridEngine headless main class directionFromPos, // One of the GridEngine helpers, // ... } from "grid-engine"; ``` If you are using the web version (import via `<script>`), all exported functions and classes besides `GridEngine` are stored in a global variable `GridEngineImports`. So you would use it as follows: ```javascript GridEngineImports.directionFromPos(/*...*/); ```
412
0.859095
1
0.859095
game-dev
MEDIA
0.688719
game-dev
0.757368
1
0.757368
runuo/runuo
2,722
Scripts/Mobiles/Monsters/Humanoid/Melee/ElfBrigand.cs
using System; using System.Collections; using Server.Items; using Server.ContextMenus; using Server.Misc; using Server.Network; namespace Server.Mobiles { // TODO: Needs some Spellweaving abilities public class ElfBrigand : BaseCreature { public override bool ClickTitle{ get{ return false; } } [Constructable] public ElfBrigand() : base( AIType.AI_Melee, FightMode.Closest, 10, 1, 0.2, 0.4 ) { SpeechHue = Utility.RandomDyedHue(); Title = "the brigand"; Race = Race.Elf; Hue = Race.RandomSkinHue(); if ( this.Female = Utility.RandomBool() ) { Body = 0x25E; Name = NameList.RandomName( "female elf brigand" ); switch ( Utility.Random( 2 ) ) { case 0: AddItem( new Skirt( Utility.RandomNondyedHue() ) ); break; case 1: AddItem( new Kilt( Utility.RandomNondyedHue() ) ); break; } } else { Body = 0x25D; Name = NameList.RandomName( "male elf brigand" ); AddItem( new ShortPants( Utility.RandomNondyedHue() ) ); } SetStr( 86, 100 ); SetDex( 81, 95 ); SetInt( 61, 75 ); SetDamage( 10, 23 ); SetSkill( SkillName.Fencing, 66.0, 97.5 ); SetSkill( SkillName.Macing, 65.0, 87.5 ); SetSkill( SkillName.MagicResist, 25.0, 47.5 ); SetSkill( SkillName.Swords, 65.0, 87.5 ); SetSkill( SkillName.Tactics, 65.0, 87.5 ); SetSkill( SkillName.Wrestling, 15.0, 37.5 ); Fame = 1000; Karma = -1000; switch ( Utility.Random( 4 ) ) { case 0: AddItem( new Boots() ); break; case 1: AddItem( new ThighBoots() ); break; case 2: AddItem( new Sandals() ); break; case 3: AddItem( new Shoes() ); break; } AddItem( new Shirt( Utility.RandomNondyedHue() ) ); switch ( Utility.Random( 7 ) ) { case 0: AddItem( new Longsword() ); break; case 1: AddItem( new Cutlass() ); break; case 2: AddItem( new Broadsword() ); break; case 3: AddItem( new Axe() ); break; case 4: AddItem( new Club() ); break; case 5: AddItem( new Dagger() ); break; case 6: AddItem( new Spear() ); break; } Utility.AssignRandomHair( this, true ); } public override void OnDeath( Container c ) { base.OnDeath( c ); if ( Utility.RandomDouble() < 0.9 ) c.DropItem( new SeveredElfEars() ); } public override void GenerateLoot() { AddLoot( LootPack.Average ); } public override bool AlwaysMurderer{ get{ return true; } } public ElfBrigand( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } }
412
0.932759
1
0.932759
game-dev
MEDIA
0.974212
game-dev
0.988438
1
0.988438
Angry-Pixel/The-Betweenlands
1,670
src/main/java/thebetweenlands/common/block/plant/BlockBogBeanFlower.java
package thebetweenlands.common.block.plant; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import thebetweenlands.common.registries.BlockRegistry; import thebetweenlands.util.AdvancedStateMap; public class BlockBogBeanFlower extends BlockStackablePlant { public BlockBogBeanFlower() { this.harvestAll = true; this.setMaxHeight(1); } @Override protected boolean isSamePlant(IBlockState blockState) { return super.isSamePlant(blockState) || blockState.getBlock() == BlockRegistry.BOG_BEAN_STALK; } @Override protected boolean canSustainBush(IBlockState state) { return state.getBlock() == BlockRegistry.BOG_BEAN_STALK; } @Override @SideOnly(Side.CLIENT) public Block.EnumOffsetType getOffsetType() { return Block.EnumOffsetType.NONE; } @Override public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack) { worldIn.setBlockState(pos, BlockRegistry.BOG_BEAN_STALK.getDefaultState()); worldIn.setBlockState(pos.up(), BlockRegistry.BOG_BEAN_FLOWER.getDefaultState()); } @Override public boolean canPlaceBlockAt(World worldIn, BlockPos pos) { return BlockRegistry.BOG_BEAN_STALK.canPlaceBlockAt(worldIn, pos); } @Override @SideOnly(Side.CLIENT) public void setStateMapper(AdvancedStateMap.Builder builder) { super.setStateMapper(builder); builder.ignore(IS_TOP, IS_BOTTOM); } }
412
0.808478
1
0.808478
game-dev
MEDIA
0.993789
game-dev
0.946491
1
0.946491
JiongXiaGu/LowpolyOcean
2,930
Assets/LowpolyOcean/Assets/Scripts/JiongXiaGu/LowpolyOcean/Editor/UnderOceanMaterialDataDrawer.cs
using JiongXiaGu.ShaderTools; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UnityEditor; namespace JiongXiaGu.LowpolyOcean { [CanEditMultipleObjects] [CustomEditor(typeof(UnderOceanMaterialData))] public class UnderOceanMaterialDataDrawer : Editor { private UnderOceanMaterialDataDrawer() { } private SerializedProperty script; private SerializedProperty modeObject; private SerializedObject modeSerializedObject; private SerializedProperty modeOptions; private SerializedProperty dataOptions; private SerializedPropertyDrawer modeDrawer; private SerializedPropertyDrawer dataDrawer; private void CreateModeOptions() { if (modeObject.objectReferenceValue != null) { modeSerializedObject = new SerializedObject(modeObject.objectReferenceValue); modeOptions = modeSerializedObject.FindProperty("mode"); modeDrawer = new SerializedPropertyDrawer(UnderOceanModeOptions.Accessor, modeOptions); } else { modeSerializedObject = null; modeOptions = null; modeDrawer = null; } } private void OnEnable() { script = serializedObject.FindProperty(EditorHelper.ScriptName); modeObject = serializedObject.FindProperty("modeObject"); CreateModeOptions(); dataOptions = serializedObject.FindProperty("data"); dataDrawer = new SerializedPropertyDrawer(UnderMaterialOptions.Accessor, dataOptions); } public override void OnInspectorGUI() { serializedObject.Update(); using (new EditorGUI.DisabledGroupScope(true)) { EditorGUILayout.PropertyField(script, true); } using (new EditorGUILayout.HorizontalScope()) { using (var changed = new EditorGUI.ChangeCheckScope()) { EditorGUILayout.PropertyField(modeObject, true); if (changed.changed) { CreateModeOptions(); } } } if (modeOptions != null) { modeSerializedObject.Update(); EditorGUILayout.PropertyField(modeOptions, true); modeSerializedObject.ApplyModifiedProperties(); } if (modeDrawer != null) { var mask = modeDrawer.Extract(); dataDrawer.OnGUI(mask); } else { dataDrawer.OnGUI(~0); } serializedObject.ApplyModifiedProperties(); } } }
412
0.807141
1
0.807141
game-dev
MEDIA
0.868194
game-dev
0.876721
1
0.876721
Apress/foundation-game-design-w-html5-javascript
13,065
Code - Published/chapter10/monsterMaze/src/monsterMaze.js
(function(){ //The canvas var canvas = document.querySelector("canvas"); var drawingSurface = canvas.getContext("2d"); //The game map var map = [ [5,5,5,5,5,5,5,5,5,5,5], [5,1,1,1,1,1,1,1,1,1,5], [5,1,2,2,2,1,2,1,2,1,5], [5,1,1,2,1,1,1,1,1,1,5], [5,1,1,1,1,2,1,1,2,1,5], [5,1,2,1,2,2,1,2,2,1,5], [5,1,1,1,1,1,2,1,1,1,5], [5,5,5,5,5,5,5,5,5,5,5] ]; //The game objects map //Note: make sure monsters are at an intersection so that //changeDirection will assign them their starting velocity var gameObjects = [ [0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,3,0], [0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,4,0,0,0,0,0], [0,0,3,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,3,0,0,0], [0,0,0,0,0,0,0,0,0,0,0] ]; //Map code var EMPTY = 0; var FLOOR = 1; var BOX = 2; var MONSTER = 3; var ALIEN = 4; var WALL = 5; //The size of each tile cell var SIZE = 64; //Sprites we need to access by name var alien = null; //The number of rows and columns var ROWS = map.length; var COLUMNS = map[0].length; //The number of columns on the tilesheet var tilesheetColumns = 3; //Arrays to store the game objects var sprites = []; var monsters = []; var boxes = []; var messages = []; var assetsToLoad = []; var assetsLoaded = 0; //Load the tilesheet image var image = new Image(); image.addEventListener("load", loadHandler, false); image.src = "../images/monsterMaze.png"; assetsToLoad.push(image); //Game variables //... Any game variables you need go here... //Game states var LOADING = 0; var BUILD_MAP = 1; var PLAYING = 2; var OVER = 3; var gameState = LOADING; //Arrow key codes var UP = 38; var DOWN = 40; var RIGHT = 39; var LEFT = 37; //Directions var moveUp = false; var moveDown = false; var moveRight = false; var moveLeft = false; //Add keyboard listeners window.addEventListener("keydown", function(event) { switch(event.keyCode) { case UP: moveUp = true; break; case DOWN: moveDown = true; break; case LEFT: moveLeft = true; break; case RIGHT: moveRight = true; break; } }, false); window.addEventListener("keyup", function(event) { switch(event.keyCode) { case UP: moveUp = false; break; case DOWN: moveDown = false; break; case LEFT: moveLeft = false; break; case RIGHT: moveRight = false; break; } }, false); //Start the game animation loop update(); function update() { //The animation loop requestAnimationFrame(update, canvas); //Change what the game is doing based on the game state switch(gameState) { case LOADING: console.log("loading..."); break; case BUILD_MAP: buildMap(map); buildMap(gameObjects); //createOtherObjects(); gameState = PLAYING; break; case PLAYING: playGame(); break; case OVER: endGame(); break; } //Render the game render(); } function loadHandler() { assetsLoaded++; if(assetsLoaded === assetsToLoad.length) { //Remove the load handlers image.removeEventListener("load", loadHandler, false); //Build the map gameState = BUILD_MAP; } } function buildMap(levelMap) { for(var row = 0; row < ROWS; row++) { for(var column = 0; column < COLUMNS; column++) { var currentTile = levelMap[row][column]; if(currentTile !== EMPTY) { //Find the tile's x and y position on the tile sheet var tilesheetX = Math.floor((currentTile - 1) % tilesheetColumns) * SIZE; var tilesheetY = Math.floor((currentTile - 1) / tilesheetColumns) * SIZE; switch (currentTile) { case FLOOR: var floor = Object.create(spriteObject); floor.sourceX = tilesheetX; floor.sourceY = tilesheetY; floor.x = column * SIZE; floor.y = row * SIZE; sprites.push(floor); break; case BOX: var box = Object.create(spriteObject); box.sourceX = tilesheetX; box.sourceY = tilesheetY; box.x = column * SIZE; box.y = row * SIZE; sprites.push(box); boxes.push(box); break; case WALL: var wall = Object.create(spriteObject); wall.sourceX = tilesheetX; wall.sourceY = tilesheetY; wall.x = column * SIZE; wall.y = row * SIZE; sprites.push(wall); break; case ALIEN: alien = Object.create(spriteObject); alien.sourceX = tilesheetX; alien.sourceY = tilesheetY; alien.x = column * SIZE; alien.y = row * SIZE; sprites.push(alien); break; case MONSTER: var monster = Object.create(monsterObject); monster.sourceX = tilesheetX; monster.sourceY = tilesheetY; monster.x = column * SIZE; monster.y = row * SIZE; //Make the monster choose a random start direction changeDirection(monster) monsters.push(monster); sprites.push(monster); break; } } } } } function createOtherObjects() { console.log("createOtherObjects"); } function changeDirection(monster) { //Clear any previous direction the monster has chosen monster.validDirections = []; //Alternative way of clearing an array: //monster.validDirections.length = 0; monster.direction = monster.NONE; //Find the monster's column and row in the array var monsterColumn = Math.floor(monster.x / SIZE); var monsterRow = Math.floor(monster.y / SIZE); //Find out what kinds of things are in the map cells //that surround the monster. If the cells contain a FLOOR cell, //push the corresponding direction into the validDirections array if(monsterRow > 0) { var thingAbove = map[monsterRow - 1][monsterColumn]; if(thingAbove === FLOOR) { monster.validDirections.push(monster.UP); } } if(monsterRow < ROWS - 1) { var thingBelow = map[monsterRow + 1][monsterColumn]; if(thingBelow === FLOOR) { monster.validDirections.push(monster.DOWN); } } if(monsterColumn > 0) { var thingToTheLeft = map[monsterRow][monsterColumn - 1]; if(thingToTheLeft === FLOOR) { monster.validDirections.push(monster.LEFT); } } if(monsterColumn < COLUMNS - 1) { var thingToTheRight = map[monsterRow][monsterColumn + 1]; if(thingToTheRight === FLOOR) { monster.validDirections.push(monster.RIGHT); } } //The monster's validDirections array now contains 0 to 4 directions that the //contain FLOOR cells. Which of those directions will the monster //choose to move in? //If a valid direction was found, Figure out if the monster is at an //maze passage intersection. if(monster.validDirections.length !== 0) { //Find out if the monster is at an intersection var upOrDownPassage = (monster.validDirections.indexOf(monster.UP) !== -1 || monster.validDirections.indexOf(monster.DOWN) !== -1); var leftOrRightPassage = (monster.validDirections.indexOf(monster.LEFT) !== -1 || monster.validDirections.indexOf(monster.RIGHT) !== -1); //Change the monster's direction if it's at an intersection or //in a cul-de-sac (dead-end) if(upOrDownPassage && leftOrRightPassage || monster.validDirections.length === 1) { //Optionally find the closest distance to the alien if(alien !== null && monster.hunt === true) { findClosestDirection(monster); } //Assign a random validDirection if the alien object doesn't exist in the game //or a validDirection wasn't found that brings the monster closer to the alien if(alien === null || monster.direction === monster.NONE) { var randomNumber = Math.floor(Math.random() * monster.validDirections.length); monster.direction = monster.validDirections[randomNumber]; } //Choose the monster's final direction switch(monster.direction) { case monster.RIGHT: monster.vx = monster.speed; monster.vy = 0; break; case monster.LEFT: monster.vx = -monster.speed; monster.vy = 0; break; case monster.UP: monster.vx = 0; monster.vy = -monster.speed; break; case monster.DOWN: monster.vx = 0; monster.vy = monster.speed; } //You can use this code below as an alternative to the switch statement /* var moveByDirection = [ [0, -1], [0, 1], [-1, 0], [1, 0] ] monster.vx = monster.speed * moveByDirection[monster.direction - 1][0]; monster.vy = monster.speed * moveByDirection[monster.direction - 1][1]; */ } } } function findClosestDirection(monster) { var closestDirection = undefined; //Find the distance between the monster and the alien var vx = alien.centerX() - monster.centerX(); var vy = alien.centerY() - monster.centerY(); //If the distance is greater on the x axis... if(Math.abs(vx) >= Math.abs(vy)) { //Try left and right if(vx <= 0) { closestDirection = monsterObject.LEFT; } else { closestDirection = monsterObject.RIGHT; } } //If the distance is greater on the y axis... else { //Try up and down if(vy <= 0) { closestDirection = monsterObject.UP; } else { closestDirection = monsterObject.DOWN; } } //Find out if the closestDirection is one of the validDirections for(var i = 0; i < monster.validDirections.length; i++) { if(closestDirection === monster.validDirections[i]) { //If it, assign the closestDirection to the monster's direction monster.direction = closestDirection; } } } function playGame() { //Up if(moveUp && !moveDown) { alien.vy = -4; } //Down if(moveDown && !moveUp) { alien.vy = 4; } //Left if(moveLeft && !moveRight) { alien.vx = -4; } //Right if(moveRight && !moveLeft) { alien.vx = 4; } //Set the alien's velocity to zero if none of the keys are being pressed if(!moveUp && !moveDown) { alien.vy = 0; } if(!moveLeft && !moveRight) { alien.vx = 0; } //Move the alien and keep it inside the screen boundaries alien.x = Math.max(64, Math.min(alien.x + alien.vx, canvas.width - alien.width - 64)); alien.y = Math.max(64, Math.min(alien.y + alien.vy, canvas.height - alien.height - 64)); //Check for collisions between the alien and the boxes for(var i = 0; i < boxes.length; i++) { blockRectangle(alien, boxes[i]); } //The monsters for(var i = 0; i < monsters.length; i++) { var monster = monsters[i]; //Move the monsters monster.x += monster.vx; monster.y += monster.vy; //Check whether the monster is at a tile corner if(Math.floor(monster.x) % SIZE === 0 && Math.floor(monster.y) % SIZE === 0) { //Change the monster's direction changeDirection(monster); } //Change the monster's state to SCARED if it's 128 pixels from the alien var vx = alien.centerX() - monster.centerX(); var vy = alien.centerY() - monster.centerY(); //Find the distance between the circles by calculating //the vector's magnitude (how long the vector is) var magnitude = Math.sqrt(vx * vx + vy * vy); if(magnitude < 192) { monster.state = monster.SCARED; } else { monster.state = monster.NORMAL; } //Update the monster to reflect state changes monster.update(); } } function endGame() { console.log("endGame"); } function render() { drawingSurface.clearRect(0, 0, canvas.width, canvas.height); //Display the sprites if(sprites.length !== 0) { for(var i = 0; i < sprites.length; i++) { var sprite = sprites[i]; if(sprite.visible) { drawingSurface.drawImage ( image, sprite.sourceX, sprite.sourceY, sprite.sourceWidth, sprite.sourceHeight, Math.floor(sprite.x), Math.floor(sprite.y), sprite.width, sprite.height ); } } } //Display the game messages if(messages.length !== 0) { for(var i = 0; i < messages.length; i++) { var message = messages[i]; if(message.visible) { drawingSurface.font = message.font; drawingSurface.fillStyle = message.fillStyle; drawingSurface.textBaseline = message.textBaseline; drawingSurface.fillText(message.text, message.x, message.y); } } } } }());
412
0.825598
1
0.825598
game-dev
MEDIA
0.962785
game-dev
0.984482
1
0.984482
PedroRok/CreateHypertubes
1,548
src/main/java/com/pedrorok/hypertube/mixin/core/PlayerMixin.java
package com.pedrorok.hypertube.mixin.core; import com.pedrorok.hypertube.core.camera.DetachedPlayerDirController; import com.pedrorok.hypertube.core.travel.TravelConstants; import net.minecraft.client.Minecraft; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.OnlyIn; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; /** * @author Rok, Pedro Lucas nmm. Created on 19/06/2025 * @project Create Hypertube */ @Mixin(Player.class) public class PlayerMixin { @Inject(method = "tick", at = @At("TAIL")) private void createHypertube$onTick(CallbackInfo ci) { LivingEntity entity = (LivingEntity) (Object) this; if (!entity.getPersistentData().getBoolean(TravelConstants.TRAVEL_TAG)) return; if (!(entity instanceof Player player) || !entity.level().isClientSide) return; createHypertube$tickInClient(player); } @Unique @OnlyIn(Dist.CLIENT) private void createHypertube$tickInClient(Player player) { if (!Minecraft.getInstance().player.getUUID().equals(player.getUUID())) { return; } player.setYRot(DetachedPlayerDirController.get().getYaw()); player.setXRot(DetachedPlayerDirController.get().getPitch()); } }
412
0.854792
1
0.854792
game-dev
MEDIA
0.884832
game-dev
0.881105
1
0.881105
0x0ade/CelesteNet
6,846
CelesteNet.Shared/DataTypes/Data.cs
using System; using System.Diagnostics.CodeAnalysis; namespace Celeste.Mod.CelesteNet.DataTypes { public abstract class DataType { public virtual DataFlags DataFlags => DataFlags.None; public virtual MetaType[] Meta { get; set; } = Dummy<MetaType>.EmptyArray; public virtual bool FilterHandle(DataContext ctx) => true; public virtual bool FilterSend(DataContext ctx) => true; public virtual MetaType[] GenerateMeta(DataContext ctx) => Meta; public virtual void FixupMeta(DataContext ctx) { } public virtual MetaUpdateContext UpdateMeta(DataContext ctx) => new(ctx, this); public virtual void ReadAll(CelesteNetBinaryReader reader) { Meta = ReadMeta(reader); FixupMeta(reader.Data); Read(reader); } public virtual void WriteAll(CelesteNetBinaryWriter writer) { Meta = GenerateMeta(writer.Data); WriteMeta(writer, Meta); Write(writer); } protected virtual MetaType[] ReadMeta(CelesteNetBinaryReader reader) { MetaType[] meta = new MetaType[reader.ReadByte()]; for (int i = 0; i < meta.Length; i++) meta[i] = reader.Data.ReadMeta(reader); return meta; } protected virtual void WriteMeta(CelesteNetBinaryWriter writer, MetaType[] meta) { writer.Write((byte) meta.Length); foreach (MetaType m in meta) writer.Data.WriteMeta(writer, m); } protected virtual void Read(CelesteNetBinaryReader reader) {} protected virtual void Write(CelesteNetBinaryWriter writer) {} public virtual bool Is<T>(DataContext ctx) where T : MetaType<T> { foreach (MetaType meta in Meta) if (meta is T) return true; return false; } public virtual T Get<T>(DataContext ctx) where T : MetaType<T> => TryGet(ctx, out T? value) ? value : throw new ArgumentException($"DataType {ctx.DataTypeToID[GetType()]} doesn't have MetaType {ctx.MetaTypeToID[typeof(T)]}."); public virtual T? GetOpt<T>(DataContext ctx) where T : MetaType<T> => TryGet(ctx, out T? value) ? value : null; public virtual bool TryGet<T>(DataContext ctx, [NotNullWhen(true)] out T? value) where T : MetaType<T> { foreach (MetaType meta in Meta) if (meta is T cast) { value = cast; return true; } value = null; return false; } public virtual void Set<T>(DataContext ctx, T? value) where T : MetaType<T> { MetaType[] metas = Meta; if (value == null) { for (int i = 0; i < metas.Length; i++) { MetaType meta = metas[i]; if (meta is T) { if (i != metas.Length - 1) Array.Copy(metas, i + 1, metas, i, metas.Length - i - 1); Array.Resize(ref metas, metas.Length - 1); Meta = metas; return; } } return; } for (int i = 0; i < metas.Length; i++) { MetaType meta = metas[i]; if (meta == value || meta is T) { metas[i] = value; Meta = metas; return; } } Array.Resize(ref metas, metas.Length + 1); metas[metas.Length - 1] = value; Meta = metas; } public virtual string GetTypeID(DataContext ctx) => ctx.DataTypeToID.TryGetValue(GetType(), out string? value) ? value : ""; public virtual string GetSource(DataContext ctx) => ctx.DataTypeToSource.TryGetValue(GetType(), out string? value) ? value : ""; public static byte PackBool(byte value, int index, bool set) { int mask = 1 << index; return set ? (byte) (value | mask) : (byte) (value & ~mask); } public static bool UnpackBool(byte value, int index) { int mask = 1 << index; return (value & mask) == mask; } public static byte PackBools(bool a = false, bool b = false, bool c = false, bool d = false, bool e = false, bool f = false, bool g = false, bool h = false) { byte value = 0; value = PackBool(value, 0, a); value = PackBool(value, 1, b); value = PackBool(value, 2, c); value = PackBool(value, 3, d); value = PackBool(value, 4, e); value = PackBool(value, 5, f); value = PackBool(value, 6, g); value = PackBool(value, 7, h); return value; } } public abstract class DataType<T> : DataType where T : DataType<T> { public static string DataID; public static string DataSource; static DataType() { DataID = typeof(T).Name; DataSource = typeof(T).Assembly.GetName().Name ?? DataID; } public T ReadT(CelesteNetBinaryReader reader) { Read(reader); return (T) this; } public T ReadAllT(CelesteNetBinaryReader reader) { ReadAll(reader); return (T) this; } public override string GetTypeID(DataContext ctx) => DataID; public override string GetSource(DataContext ctx) => DataSource; } public class MetaUpdateContext : IDisposable { public readonly DataContext Context; public readonly DataType Data; public MetaUpdateContext(DataContext ctx, DataType data) { Context = ctx; Data = data; Data.Meta = data.GenerateMeta(Context); } public void Dispose() { Data.FixupMeta(Context); } } // Used for compile time verification and to make getting the request type easier to obtain. public interface IDataRequestable { } public interface IDataRequestable<T> : IDataRequestable where T : DataType<T>, new() { } [Flags] public enum DataFlags : ushort { None = 0b0000000000000000, Unreliable = 0b0000000000000001, Taskable = 0b0001000000000000, Small = 0b0010000000000000, CoreType = 0b0000000000010000, NoStandardMeta = 0b0000000000100000, InteralSlimIndicator = 0b1000000000000000, InteralSlimBigID = 0b0100000000000000, RESERVED = 0b1100110000001110 } }
412
0.89372
1
0.89372
game-dev
MEDIA
0.581413
game-dev
0.862515
1
0.862515
MCTCP/TerrainControl
2,528
common/src/main/java/com/khorn/terraincontrol/customobjects/bo3/BlockFunction.java
package com.khorn.terraincontrol.customobjects.bo3; import com.khorn.terraincontrol.LocalMaterialData; import com.khorn.terraincontrol.LocalWorld; import com.khorn.terraincontrol.configuration.ConfigFunction; import com.khorn.terraincontrol.exception.InvalidConfigException; import com.khorn.terraincontrol.util.NamedBinaryTag; import java.util.List; import java.util.Random; /** * Represents a block in a BO3. */ public class BlockFunction extends BO3PlaceableFunction { public final LocalMaterialData material; public NamedBinaryTag metaDataTag; public String metaDataName; public BlockFunction(BO3Config config, List<String> args) throws InvalidConfigException { super(config); assureSize(4, args); // Those limits are arbitrary, LocalWorld.setBlock will limit it // correctly based on what chunks can be accessed x = readInt(args.get(0), -100, 100); y = readInt(args.get(1), -1000, 1000); z = readInt(args.get(2), -100, 100); material = readMaterial(args.get(3)); if (args.size() == 5) { metaDataTag = BO3Loader.loadMetadata(args.get(4), getHolder().directory); if (metaDataTag != null) { metaDataName = args.get(4); } } } public BlockFunction(BO3Config config, int x, int y, int z, LocalMaterialData material) { super(config); this.x = x; this.y = y; this.z = z; this.material = material; } @Override public String toString() { String start = "Block(" + x + ',' + y + ',' + z + ',' + material; if (metaDataName != null) { start += ',' + metaDataName; } return start + ')'; } @Override public BlockFunction rotate() { BlockFunction rotatedBlock = new BlockFunction(getHolder(), z, y, -x, material.rotate()); rotatedBlock.metaDataTag = metaDataTag; rotatedBlock.metaDataName = metaDataName; return rotatedBlock; } @Override public void spawn(LocalWorld world, Random random, int x, int y, int z) { world.setBlock(x, y, z, material, metaDataTag); } @Override public boolean isAnalogousTo(ConfigFunction<BO3Config> other) { if(!getClass().equals(other.getClass())) { return false; } BlockFunction block = (BlockFunction) other; return block.x == x && block.y == y && block.z == z; } }
412
0.896522
1
0.896522
game-dev
MEDIA
0.89689
game-dev
0.921397
1
0.921397
StranikS-Scan/WorldOfTanks-Decompiled
1,938
source/res/scripts/client/gui/impl/gen/view_models/views/lobby/pm_announce/tooltips/personal_missions_new_campaign_tooltip_view_model.py
# Python bytecode 2.7 (decompiled from Python 2.7) # Embedded file name: scripts/client/gui/impl/gen/view_models/views/lobby/pm_announce/tooltips/personal_missions_new_campaign_tooltip_view_model.py from enum import Enum from frameworks.wulf import Array from frameworks.wulf import ViewModel from gui.impl.gen.view_models.views.lobby.pm_announce.tooltips.personal_missions_old_campaign_tooltip_operations_model import PersonalMissionsOldCampaignTooltipOperationsModel from gui.impl.gen.view_models.views.lobby.pm_announce.tooltips.personal_missions_old_campaign_tooltip_rewards_model import PersonalMissionsOldCampaignTooltipRewardsModel class MissionStatus(Enum): ACTIVE = 'active' COMPLETED = 'completed' COMPLETEDPERFECT = 'completedPerfect' DISABLED = 'disabled' class PersonalMissionsNewCampaignTooltipViewModel(ViewModel): __slots__ = () def __init__(self, properties=3, commands=0): super(PersonalMissionsNewCampaignTooltipViewModel, self).__init__(properties=properties, commands=commands) def getMissionStatus(self): return MissionStatus(self._getString(0)) def setMissionStatus(self, value): self._setString(0, value.value) def getOperations(self): return self._getArray(1) def setOperations(self, value): self._setArray(1, value) @staticmethod def getOperationsType(): return PersonalMissionsOldCampaignTooltipOperationsModel def getRewards(self): return self._getArray(2) def setRewards(self, value): self._setArray(2, value) @staticmethod def getRewardsType(): return PersonalMissionsOldCampaignTooltipRewardsModel def _initialize(self): super(PersonalMissionsNewCampaignTooltipViewModel, self)._initialize() self._addStringProperty('missionStatus') self._addArrayProperty('operations', Array()) self._addArrayProperty('rewards', Array())
412
0.781971
1
0.781971
game-dev
MEDIA
0.559618
game-dev
0.96442
1
0.96442
ClusterVR/ClusterCreatorKit
1,314
Runtime/Preview/Item/ContactableItemRaycaster.cs
#if UNITY_EDITOR using System.Linq; using ClusterVR.CreatorKit.Constants; using ClusterVR.CreatorKit.Item; using UnityEngine; namespace ClusterVR.CreatorKit.Preview.Item { [AddComponentMenu("")] public sealed class ContactableItemRaycaster : MonoBehaviour { [SerializeField] Camera targetCamera; [SerializeField] ContactableItemFinder contactableItemFinder; const float RaycastMaxDistance = 20f; int raycastLayerMask; void Start() { raycastLayerMask = ~(LayerName.PostProcessingMask | LayerName.CameraOnlyMask); } public bool RaycastItem(Vector2 raycastPoint, out IContactableItem item, out Vector3 hitPoint) { item = default; hitPoint = default; var ray = targetCamera.ScreenPointToRay(raycastPoint); if (!Physics.Raycast(ray, out var hitInfo, RaycastMaxDistance, raycastLayerMask)) { return false; } item = hitInfo.collider.gameObject.GetComponentInParent<IContactableItem>(); if (item == null || !contactableItemFinder.ContactableItems.Contains(item)) { return false; } hitPoint = hitInfo.point; return true; } } } #endif
412
0.920233
1
0.920233
game-dev
MEDIA
0.91986
game-dev
0.905807
1
0.905807
EnhancedNetwork/TownofHost-Enhanced
9,421
Roles/(Ghosts)/Crewmate/Ghastly.cs
using AmongUs.GameOptions; using Hazel; using InnerNet; using TOHE.Roles.Core; using TOHE.Roles.Double; using UnityEngine; using static TOHE.Options; using static TOHE.Translator; using static TOHE.Utils; namespace TOHE.Roles._Ghosts_.Crewmate; internal class Ghastly : RoleBase { //===========================SETUP================================\\ public override CustomRoles Role => CustomRoles.Ghastly; private const int Id = 22060; public static bool HasEnabled => CustomRoleManager.HasEnabled(CustomRoles.Ghastly); public override CustomRoles ThisRoleBase => CustomRoles.GuardianAngel; public override Custom_RoleType ThisRoleType => Custom_RoleType.CrewmateGhosts; //==================================================================\\ private static OptionItem PossessCooldown; private static OptionItem MaxPossesions; private static OptionItem PossessDur; private static OptionItem GhastlySpeed; private static OptionItem GhastlyKillAllies; private (byte, byte) killertarget = (byte.MaxValue, byte.MaxValue); private readonly Dictionary<byte, long> LastTime = []; private bool KillerIsChosen = false; public override void SetupCustomOption() { SetupSingleRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Ghastly); PossessCooldown = FloatOptionItem.Create(Id + 10, "GhastlyPossessCD", new(2.5f, 120f, 2.5f), 35f, TabGroup.CrewmateRoles, false).SetParent(CustomRoleSpawnChances[CustomRoles.Ghastly]) .SetValueFormat(OptionFormat.Seconds); MaxPossesions = IntegerOptionItem.Create(Id + 11, "GhastlyMaxPossessions", new(1, 99, 1), 10, TabGroup.CrewmateRoles, false).SetParent(CustomRoleSpawnChances[CustomRoles.Ghastly]) .SetValueFormat(OptionFormat.Players); PossessDur = IntegerOptionItem.Create(Id + 12, "GhastlyPossessionDuration", new(5, 120, 5), 40, TabGroup.CrewmateRoles, false).SetParent(CustomRoleSpawnChances[CustomRoles.Ghastly]) .SetValueFormat(OptionFormat.Seconds); GhastlySpeed = FloatOptionItem.Create(Id + 13, "GhastlySpeed", new(1.5f, 5f, 0.5f), 2f, TabGroup.CrewmateRoles, false).SetParent(CustomRoleSpawnChances[CustomRoles.Ghastly]) .SetValueFormat(OptionFormat.Multiplier); GhastlyKillAllies = BooleanOptionItem.Create(Id + 14, "GhastlyKillAllies", false, TabGroup.CrewmateRoles, false) .SetParent(CustomRoleSpawnChances[CustomRoles.Ghastly]); } public override void Init() { KillerIsChosen = false; killertarget = (byte.MaxValue, byte.MaxValue); LastTime.Clear(); } public override void Add(byte playerId) { AbilityLimit = MaxPossesions.GetInt(); CustomRoleManager.OnFixedUpdateOthers.Add(OnFixUpdateOthers); CustomRoleManager.CheckDeadBodyOthers.Add(CheckDeadBody); } public void SendRPC() { var writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.PlayerId, (byte)CustomRPC.SyncRoleSkill, SendOption.Reliable, -1); writer.WriteNetObject(_Player); writer.Write(AbilityLimit); writer.Write(KillerIsChosen); writer.Write(killertarget.Item1); writer.Write(killertarget.Item2); AmongUsClient.Instance.FinishRpcImmediately(writer); } public override void ReceiveRPC(MessageReader reader, PlayerControl pc) { AbilityLimit = reader.ReadSingle(); KillerIsChosen = reader.ReadBoolean(); var item1 = reader.ReadByte(); var item2 = reader.ReadByte(); killertarget = (item1, item2); } public override void ApplyGameOptions(IGameOptions opt, byte playerId) { AURoleOptions.GuardianAngelCooldown = PossessCooldown.GetFloat(); AURoleOptions.ProtectionDurationSeconds = 0f; } public override bool OnCheckProtect(PlayerControl angel, PlayerControl target) { if (target.Is(CustomRoles.NiceMini) && Mini.Age < 18) { angel.Notify(ColorString(GetRoleColor(CustomRoles.Gangster), GetString("CantPosses"))); return true; } if (AbilityLimit <= 0) { SendRPC(); angel.Notify(GetString("GhastlyNoMorePossess")); return false; } var killer = killertarget.Item1; var Target = killertarget.Item2; if (!KillerIsChosen && !CheckConflicts(target)) { angel.Notify(GetString("GhastlyCannotPossessTarget")); return false; } if (!KillerIsChosen && target.PlayerId != killer) { TargetArrow.Remove(killer, Target); LastTime.Remove(killer); killer = target.PlayerId; Target = byte.MaxValue; KillerIsChosen = true; angel.Notify($"\n{GetString("GhastlyChooseTarget")}\n"); } else if (KillerIsChosen && Target == byte.MaxValue && target.PlayerId != killer) { Target = target.PlayerId; AbilityLimit--; LastTime.Add(killer, GetTimeStamp()); KillerIsChosen = false; GetPlayerById(killer)?.Notify(GetString("GhastlyYouvePosses")); angel.Notify($"\n<size=65%>〘{string.Format(GetString("GhastlyPossessedUser"), "</size>" + GetPlayerById(killer).GetRealName())}<size=65%> 〙</size>\n"); TargetArrow.Add(killer, Target); angel.RpcGuardAndKill(target); angel.RpcResetAbilityCooldown(); Logger.Info($" chosen {target.GetRealName()} for : {GetPlayerById(killer).GetRealName()}", "GhastlyTarget"); } else if (target.PlayerId == killer) { angel.Notify(GetString("GhastlyCannotPossessTarget")); } killertarget = (killer, Target); SendRPC(); return false; } private bool CheckConflicts(PlayerControl target) => target != null && (!GhastlyKillAllies.GetBool() || target.GetCountTypes() != _Player.GetCountTypes()); public override void OnFixedUpdate(PlayerControl player, bool lowLoad, long nowTime, int timerLowLoad) { if (lowLoad) return; var speed = Main.AllPlayerSpeed[player.PlayerId]; if (speed != GhastlySpeed.GetFloat()) { Main.AllPlayerSpeed[player.PlayerId] = GhastlySpeed.GetFloat(); player.MarkDirtySettings(); } } public void OnFixUpdateOthers(PlayerControl player, bool lowLoad, long nowTime) { if (!lowLoad && killertarget.Item1 == player.PlayerId && LastTime.TryGetValue(player.PlayerId, out var now) && now + PossessDur.GetInt() <= nowTime) { _Player?.Notify(string.Format($"\n{GetString("GhastlyExpired")}\n", player.GetRealName())); TargetArrow.Remove(killertarget.Item1, killertarget.Item2); LastTime.Remove(player.PlayerId); KillerIsChosen = false; killertarget = (byte.MaxValue, byte.MaxValue); SendRPC(); } } public override bool CheckMurderOnOthersTarget(PlayerControl killer, PlayerControl target) { var tuple = killertarget; if (tuple.Item1 == killer.PlayerId && tuple.Item2 != byte.MaxValue) { if (tuple.Item2 != target.PlayerId) { killer.Notify(GetString("GhastlyNotUrTarget")); return true; } else { _Player?.Notify(string.Format($"\n{GetString("GhastlyExpired")}\n", killer.GetRealName())); TargetArrow.Remove(killertarget.Item1, killertarget.Item2); LastTime.Remove(killer.PlayerId); KillerIsChosen = false; killertarget = (byte.MaxValue, byte.MaxValue); SendRPC(); } } return false; } public override string GetLowerTextOthers(PlayerControl seer, PlayerControl seen = null, bool isForMeeting = false, bool isForHud = false) { if (isForMeeting || (seer != seen && seer.IsAlive())) return string.Empty; var (killer, target) = killertarget; if (killer == seen.PlayerId && target != byte.MaxValue) { var arrows = TargetArrow.GetArrows(GetPlayerById(killer), target); var tar = target.GetPlayer().GetRealName(); if (tar == null) return string.Empty; var colorstring = ColorString(GetRoleColor(CustomRoles.Ghastly), "<alpha=#88>" + tar + arrows); return colorstring; } return string.Empty; } private void CheckDeadBody(PlayerControl killer, PlayerControl target, bool inMeeting) { if (inMeeting) return; var tuple = killertarget; if (target.PlayerId == tuple.Item1 || target.PlayerId == tuple.Item2) { _Player?.Notify(string.Format($"\n{GetString("GhastlyExpired")}\n", GetPlayerById(killertarget.Item1))); TargetArrow.Remove(killertarget.Item1, killertarget.Item2); LastTime.Remove(target.PlayerId); KillerIsChosen = false; killertarget = (byte.MaxValue, byte.MaxValue); SendRPC(); } } public override string GetProgressText(byte playerId, bool cooms) => ColorString(AbilityLimit > 0 ? GetRoleColor(CustomRoles.Ghastly).ShadeColor(0.25f) : Color.gray, $"({AbilityLimit})"); }
412
0.835496
1
0.835496
game-dev
MEDIA
0.695261
game-dev
0.912483
1
0.912483
50DKP/FF2-Official
5,095
addons/sourcemod/scripting/freak_fortress_2/special_noanims.sp
/* special_noanims: slot - unused. arg1 - 1=Custom Model Rotates (def.0) rage_new_weapon: slot - slot (def.0) arg1 - weapon's classname arg2 - weapon's index arg3 - weapon's attributes arg4 - weapon's slot (0 - primary. 1 - secondary. 2 - melee. 3 - pda. 4 - spy's watches) arg5 - weapon's ammo (set to 1 for clipless weapons, then set the actual ammo using clip) arg6 - force switch to this weapon arg7 - weapon's clip */ #pragma semicolon 1 #include <sourcemod> #include <tf2items> #include <tf2_stocks> #include <freak_fortress_2> #define PLUGIN_NAME "noanims and new weapon" #define PLUGIN_VERSION "2.0.0" public Plugin:myinfo= { name="Freak Fortress 2: special_noanims", author="RainBolt Dash, Wliu", description="FF2: New Weapon and No Animations abilities", version=PLUGIN_VERSION }; public OnPluginStart() { new version[3]; FF2_GetFF2Version(version); if(version[0]==1 && (version[1]<10 || (version[1]==10 && version[2]<3))) { SetFailState("This subplugin depends on at least FF2 v1.10.3"); } HookEvent("teamplay_round_start", OnRoundStart); FF2_RegisterSubplugin(PLUGIN_NAME); } public FF2_OnAbility(boss, const String:pluginName[], const String:abilityName[], slot, status) { if(!StrEqual(pluginName, PLUGIN_NAME, false)) { return; } if(StrEqual(abilityName, "equip weapon", false)) { Rage_New_Weapon(boss, abilityName); } } public Action:OnRoundStart(Handle:event, const String:name[], bool:dontBroadcast) { if(FF2_IsFF2Enabled()) { CreateTimer(0.41, Timer_Disable_Anims, TIMER_FLAG_NO_MAPCHANGE); CreateTimer(9.31, Timer_Disable_Anims, TIMER_FLAG_NO_MAPCHANGE); } return Plugin_Continue; } public Action:Timer_Disable_Anims(Handle:timer) { new client; for(new boss; (client=GetClientOfUserId(FF2_GetBossUserId(boss)))>0; boss++) { if(FF2_HasAbility(boss, PLUGIN_NAME, "no animations")) { SetEntProp(client, Prop_Send, "m_bUseClassAnimations", 0); SetEntProp(client, Prop_Send, "m_bCustomModelRotates", FF2_GetAbilityArgument(boss, PLUGIN_NAME, "no animations", "rotate model", 0)); } } return Plugin_Continue; } Rage_New_Weapon(boss, const String:abilityName[]) { new client=GetClientOfUserId(FF2_GetBossUserId(boss)); if(!client || !IsClientInGame(client) || !IsPlayerAlive(client)) { return; } decl String:classname[64], String:attributes[256]; FF2_GetAbilityArgumentString(boss, PLUGIN_NAME, abilityName, "classname", classname, sizeof(classname)); FF2_GetAbilityArgumentString(boss, PLUGIN_NAME, abilityName, "attributes", attributes, sizeof(attributes)); new slot=FF2_GetAbilityArgument(boss, PLUGIN_NAME, abilityName, "slot"); TF2_RemoveWeaponSlot(client, slot); new index=FF2_GetAbilityArgument(boss, PLUGIN_NAME, abilityName, "index"); new weapon=SpawnWeapon(client, classname, index, 101, 5, attributes); if(StrEqual(classname, "tf_weapon_builder") && index!=735) //PDA, normal sapper { SetEntProp(weapon, Prop_Send, "m_aBuildableObjectTypes", 1, _, 0); SetEntProp(weapon, Prop_Send, "m_aBuildableObjectTypes", 1, _, 1); SetEntProp(weapon, Prop_Send, "m_aBuildableObjectTypes", 1, _, 2); SetEntProp(weapon, Prop_Send, "m_aBuildableObjectTypes", 0, _, 3); } else if(StrEqual(classname, "tf_weapon_sapper") || index==735) //Sappers, normal sapper { SetEntProp(weapon, Prop_Send, "m_iObjectType", 3); SetEntProp(weapon, Prop_Data, "m_iSubType", 3); SetEntProp(weapon, Prop_Send, "m_aBuildableObjectTypes", 0, _, 0); SetEntProp(weapon, Prop_Send, "m_aBuildableObjectTypes", 0, _, 1); SetEntProp(weapon, Prop_Send, "m_aBuildableObjectTypes", 0, _, 2); SetEntProp(weapon, Prop_Send, "m_aBuildableObjectTypes", 1, _, 3); } if(FF2_GetAbilityArgument(boss, PLUGIN_NAME, abilityName, "set as active weapon")) { SetEntPropEnt(client, Prop_Send, "m_hActiveWeapon", weapon); } new ammo=FF2_GetAbilityArgument(boss, PLUGIN_NAME, abilityName, "ammo", 0); new clip=FF2_GetAbilityArgument(boss, PLUGIN_NAME, abilityName, "clip", 0); if(ammo || clip) { FF2_SetAmmo(client, weapon, ammo, clip); } } stock SpawnWeapon(client, String:name[], index, level, quality, String:attribute[]) { new Handle:weapon=TF2Items_CreateItem(OVERRIDE_ALL|FORCE_GENERATION); TF2Items_SetClassname(weapon, name); TF2Items_SetItemIndex(weapon, index); TF2Items_SetLevel(weapon, level); TF2Items_SetQuality(weapon, quality); new String:attributes[32][32]; new count=ExplodeString(attribute, ";", attributes, 32, 32); if(count%2!=0) { count--; } if(count>0) { TF2Items_SetNumAttributes(weapon, count/2); new i2=0; for(new i=0; i<count; i+=2) { new attrib=StringToInt(attributes[i]); if(!attrib) { LogError("Bad weapon attribute passed: %s ; %s", attributes[i], attributes[i+1]); return -1; } TF2Items_SetAttribute(weapon, i2, attrib, StringToFloat(attributes[i+1])); i2++; } } else { TF2Items_SetNumAttributes(weapon, 0); } if(weapon==INVALID_HANDLE) { return -1; } new entity=TF2Items_GiveNamedItem(client, weapon); CloseHandle(weapon); EquipPlayerWeapon(client, entity); return entity; }
412
0.943236
1
0.943236
game-dev
MEDIA
0.957427
game-dev
0.871495
1
0.871495
dotnet/Silk.NET
1,025
src/Windowing/Silk.NET.SDL/Enums/HintPriority.gen.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using Silk.NET.Core.Attributes; #pragma warning disable 1591 namespace Silk.NET.SDL { [NativeName("AnonymousName", "__AnonymousEnum_SDL_hints_L2718_C9")] [NativeName("Name", "SDL_HintPriority")] public enum HintPriority : int { [Obsolete("Deprecated in favour of \"Default\"")] [NativeName("Name", "SDL_HINT_DEFAULT")] HintDefault = 0x0, [Obsolete("Deprecated in favour of \"Normal\"")] [NativeName("Name", "SDL_HINT_NORMAL")] HintNormal = 0x1, [Obsolete("Deprecated in favour of \"Override\"")] [NativeName("Name", "SDL_HINT_OVERRIDE")] HintOverride = 0x2, [NativeName("Name", "SDL_HINT_DEFAULT")] Default = 0x0, [NativeName("Name", "SDL_HINT_NORMAL")] Normal = 0x1, [NativeName("Name", "SDL_HINT_OVERRIDE")] Override = 0x2, } }
412
0.747883
1
0.747883
game-dev
MEDIA
0.224087
game-dev
0.784288
1
0.784288
DigitalRune/DigitalRune
15,179
Source/DigitalRune.Game.UI/Controls/RangeControls/ScrollBar.cs
// DigitalRune Engine - Copyright (C) DigitalRune GmbH // This file is subject to the terms and conditions defined in // file 'LICENSE.TXT', which is part of this source code package. using System; using System.ComponentModel; using DigitalRune.Game.Input; using DigitalRune.Mathematics; using DigitalRune.Mathematics.Algebra; namespace DigitalRune.Game.UI.Controls { /// <summary> /// Represents a control that provides a scroll bar that has a sliding <see cref="Thumb"/> whose /// position corresponds to a value and buttons to change the value. /// </summary> /// <remarks> /// A <see cref="ScrollBar"/> has a sliding <see cref="Thumb"/>. <see cref="RangeBase.Value"/> /// defines the position of the thumb. <see cref="ViewportSize"/> defines the size of the thumb. /// The scroll bar also has two buttons that can be clicked to change the /// <see cref="RangeBase.Value"/>. The "empty" space between the thumb and the buttons can also /// be clicked (like a repeat button) to change the <see cref="RangeBase.Value"/>. /// </remarks> public class ScrollBar : RangeBase { // See also comments in Slider.cs! //-------------------------------------------------------------- #region Fields //-------------------------------------------------------------- private Button _decrementButton; private Button _incrementButton; private Thumb _thumb; // Used to detect if the left mouse button was pressed over the control - only then // virtual button repeats count. private bool _isPressed; #endregion //-------------------------------------------------------------- #region Properties & Events //-------------------------------------------------------------- #endregion //-------------------------------------------------------------- #region Game Object Properties & Events //-------------------------------------------------------------- /// <summary> /// The ID of the <see cref="Orientation"/> game object property. /// </summary> #if !NETFX_CORE && !XBOX && !PORTABLE [Browsable(false)] #endif public static readonly int OrientationPropertyId = CreateProperty( typeof(ScrollBar), "Orientation", GamePropertyCategories.Layout, null, Orientation.Vertical, UIPropertyOptions.AffectsMeasure); /// <summary> /// Gets or sets the orientation of the scroll bar. /// This is a game object property. /// </summary> /// <value>The orientation.</value> /// <remarks> /// Changing this property has no effect after the scroll bar was loaded. /// </remarks> public Orientation Orientation { get { return GetValue<Orientation>(OrientationPropertyId); } set { SetValue(OrientationPropertyId, value); } } /// <summary> /// The ID of the <see cref="ViewportSize"/> game object property. /// </summary> #if !NETFX_CORE && !XBOX && !PORTABLE [Browsable(false)] #endif public static readonly int ViewportSizePropertyId = CreateProperty( typeof(ScrollBar), "ViewportSize", GamePropertyCategories.Default, null, 0f, UIPropertyOptions.AffectsArrange); /// <summary> /// Gets or sets the size of the viewport relative to the full extent of the scrollable content. /// This is a game object property. /// </summary> /// <value> /// The size of the viewport relative to the full extent of the scrollable content. This is a /// value in the range ]0, 1]. 0 means that the extent of the scrollable content is infinite /// (which does not happen in practice). 1 means that the full scrollable content is visible in /// the scroll viewer. 0.5 means that the scroll viewer can show half of the scrollable content. /// Etc. The default value is 0.1. /// </value> /// <remarks> /// The <see cref="ViewportSize"/> defines the size of the draggable <see cref="Thumb"/>. /// </remarks> public float ViewportSize { get { return GetValue<float>(ViewportSizePropertyId); } set { SetValue(ViewportSizePropertyId, value); } } /// <summary> /// The ID of the <see cref="ThumbStyle"/> game object property. /// </summary> #if !NETFX_CORE && !XBOX && !PORTABLE [Browsable(false)] #endif public static readonly int ThumbStylePropertyId = CreateProperty( typeof(ScrollBar), "ThumbStyle", GamePropertyCategories.Style, null, "Thumb", UIPropertyOptions.None); /// <summary> /// Gets or sets the style that is applied to the <see cref="Thumb"/>. /// This is a game object property. /// </summary> /// <value> /// The style that is applied to the <see cref="Thumb"/>. Can be <see langword="null"/> or an /// empty string to hide the thumb. /// </value> public string ThumbStyle { get { return GetValue<string>(ThumbStylePropertyId); } set { SetValue(ThumbStylePropertyId, value); } } /// <summary> /// The ID of the <see cref="DecrementButtonStyle"/> game object property. /// </summary> #if !NETFX_CORE && !XBOX && !PORTABLE [Browsable(false)] #endif public static readonly int DecrementButtonStylePropertyId = CreateProperty( typeof(ScrollBar), "DecrementButtonStyle", GamePropertyCategories.Style, null, "ScrollBarButton", UIPropertyOptions.None); /// <summary> /// Gets or sets the style that is applied to the button that decreases the /// <see cref="RangeBase.Value"/>. This is a game object property. /// </summary> /// <value> /// The style that is applied to the button that decreases the <see cref="RangeBase.Value"/>. /// Can be <see langword="null"/> or an empty string to hide the button. /// </value> public string DecrementButtonStyle { get { return GetValue<string>(DecrementButtonStylePropertyId); } set { SetValue(DecrementButtonStylePropertyId, value); } } /// <summary> /// The ID of the <see cref="IncrementButtonStyle"/> game object property. /// </summary> #if !NETFX_CORE && !XBOX && !PORTABLE [Browsable(false)] #endif public static readonly int IncrementButtonStylePropertyId = CreateProperty( typeof(ScrollBar), "IncrementButtonStyle", GamePropertyCategories.Style, null, "ScrollBarButton", UIPropertyOptions.None); /// <summary> /// Gets or sets the style that is applied to the button that increments the /// <see cref="RangeBase.Value"/>. This is a game object property. /// </summary> /// <value> /// The style that is applied to the button that increments the <see cref="RangeBase.Value"/>. /// Can be <see langword="null"/> or an empty string to hide the button. /// </value> public string IncrementButtonStyle { get { return GetValue<string>(IncrementButtonStylePropertyId); } set { SetValue(IncrementButtonStylePropertyId, value); } } #endregion //-------------------------------------------------------------- #region Creation & Cleanup //-------------------------------------------------------------- /// <summary> /// Initializes static members of the <see cref="ScrollBar"/> class. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")] static ScrollBar() { OverrideDefaultValue(typeof(ScrollBar), ViewportSizePropertyId, 0.1f); } /// <summary> /// Initializes a new instance of the <see cref="ScrollBar"/> class. /// </summary> public ScrollBar() { Style = "ScrollBar"; } #endregion //-------------------------------------------------------------- #region Methods //-------------------------------------------------------------- /// <inheritdoc/> protected override void OnLoad() { base.OnLoad(); // Create decrement button. var decrementButtonStyle = DecrementButtonStyle; if (!string.IsNullOrEmpty(decrementButtonStyle)) { _decrementButton = new Button { Name = "DecrementButton", Style = decrementButtonStyle, Focusable = false, // Unlike normal buttons these arrow button can not be focused! IsRepeatButton = true, }; VisualChildren.Add(_decrementButton); var click = _decrementButton.Events.Get<EventArgs>(ButtonBase.ClickEventId); click.Event += OnDecrementButtonClick; } // Create increment button. var incrementButtonStyle = IncrementButtonStyle; if (!string.IsNullOrEmpty(incrementButtonStyle)) { _incrementButton = new Button { Name = "RightDownButton", Style = incrementButtonStyle, Focusable = false, // Unlike normal buttons these arrow button can not be focused! IsRepeatButton = true, }; VisualChildren.Add(_incrementButton); var click = _incrementButton.Events.Get<EventArgs>(ButtonBase.ClickEventId); click.Event += OnIncrementButtonClick; } // Create thumb. var thumbStyle = ThumbStyle; if (!string.IsNullOrEmpty(thumbStyle)) { _thumb = new Thumb { Name = "ScrollBarThumb", Style = thumbStyle, }; VisualChildren.Add(_thumb); } } /// <inheritdoc/> protected override void OnUnload() { // Remove thumb and buttons. VisualChildren.Remove(_thumb); _thumb = null; if (_decrementButton != null) { var click = _decrementButton.Events.Get<EventArgs>(ButtonBase.ClickEventId); click.Event -= OnDecrementButtonClick; VisualChildren.Remove(_decrementButton); _decrementButton = null; } if (_incrementButton != null) { var click = _incrementButton.Events.Get<EventArgs>(ButtonBase.ClickEventId); click.Event += OnIncrementButtonClick; VisualChildren.Remove(_incrementButton); _incrementButton = null; } base.OnUnload(); } private void OnDecrementButtonClick(object sender, EventArgs eventArgs) { Value -= Math.Sign(Maximum - Minimum) * SmallChange; } private void OnIncrementButtonClick(object sender, EventArgs eventArgs) { Value += Math.Sign(Maximum - Minimum) * SmallChange; } /// <inheritdoc/> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")] protected override void OnHandleInput(InputContext context) { base.OnHandleInput(context); if (!IsLoaded) return; var inputService = InputService; float change = 0; float value = Value; float minimum = Minimum; float maximum = Maximum; float range = maximum - minimum; Vector4F padding = Padding; if (!inputService.IsMouseOrTouchHandled) { // Check if "empty" space between thumbs and buttons is clicked. if (IsMouseDirectlyOver && inputService.IsPressed(MouseButtons.Left, false)) _isPressed = true; if (_isPressed) inputService.IsMouseOrTouchHandled = true; if (_isPressed && IsMouseDirectlyOver && inputService.IsPressed(MouseButtons.Left, true)) { // The area between the outer repeat buttons and the thumb acts as repeat button that // causes a LargeChange. if (Orientation == Orientation.Horizontal) { float thumbPosition = ActualX + (ActualWidth - padding.X - padding.Z) * (value - minimum) / range; if (context.MousePosition.X < thumbPosition) change -= Math.Sign(range) * LargeChange; else change += Math.Sign(range) * LargeChange; } else { float thumbPosition = ActualY + (ActualHeight - padding.Y - padding.W) * (value - minimum) / range; if (context.MousePosition.Y < thumbPosition) change -= Math.Sign(range) * LargeChange; else change += Math.Sign(range) * LargeChange; } } else if (inputService.IsUp(MouseButtons.Left)) { _isPressed = false; } } else { _isPressed = false; } if (_thumb != null) { // Handle thumb dragging. if (_thumb.IsDragging && !Numeric.AreEqual(minimum, maximum)) { if (Orientation == Orientation.Horizontal) { float contentWidth = ActualWidth - padding.X - padding.Z - _thumb.ActualWidth; change += _thumb.DragDelta.X / contentWidth * range; } else { float contentHeight = ActualHeight - padding.Y - padding.W - _thumb.ActualHeight; change += _thumb.DragDelta.Y / contentHeight * range; } } } if (change != 0.0f) { // Set new value. Value = value + change; } } /// <inheritdoc/> protected override void OnArrange(Vector2F position, Vector2F size) { // Update X or Y of the thumb to slide it to the correct position. if (_thumb != null) { float value = Value; float minimum = Minimum; float maximum = Maximum; float range = maximum - minimum; Vector4F padding = Padding; if (Orientation == Orientation.Horizontal) { float contentWidth = ActualWidth - padding.X - padding.Z; // ViewPortSize determines thumb width. float thumbWidth = contentWidth * ViewportSize; if (thumbWidth < _thumb.MinWidth) thumbWidth = _thumb.MinWidth; else if (thumbWidth > _thumb.MaxWidth) thumbWidth = _thumb.MaxWidth; _thumb.Width = thumbWidth; _thumb.Measure(new Vector2F(float.PositiveInfinity)); // Compute movement range of thumb center. contentWidth = ActualWidth - padding.X - padding.Z - thumbWidth; float thumbCenterPosition = contentWidth / range * (value - Minimum); if (Numeric.AreEqual(minimum, maximum)) thumbCenterPosition = 0; _thumb.X = padding.X + thumbCenterPosition; } else { float contentHeight = ActualHeight - padding.Y - padding.W; float thumbHeight = contentHeight * ViewportSize; if (thumbHeight < _thumb.MinHeight) thumbHeight = _thumb.MinHeight; else if (thumbHeight > _thumb.MaxHeight) thumbHeight = _thumb.MaxHeight; _thumb.Height = thumbHeight; _thumb.Measure(new Vector2F(float.PositiveInfinity)); contentHeight = ActualHeight - padding.Y - padding.W - thumbHeight; float thumbCenterPosition = contentHeight / range * (value - Minimum); if (Numeric.AreEqual(minimum, maximum)) thumbCenterPosition = 0; _thumb.Y = padding.Y + thumbCenterPosition; } } base.OnArrange(position, size); } #endregion } }
412
0.980094
1
0.980094
game-dev
MEDIA
0.529055
game-dev,desktop-app
0.926866
1
0.926866
dotnet/dotnet
17,990
src/roslyn/src/Compilers/Core/Portable/InternalUtilities/StringTable.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; namespace Roslyn.Utilities { /// <summary> /// This is basically a lossy cache of strings that is searchable by /// strings, string sub ranges, character array ranges or string-builder. /// </summary> internal class StringTable { // entry in the caches private struct Entry { // hash code of the entry public int HashCode; // full text of the item public string Text; } // TODO: Need to tweak the size with more scenarios. // for now this is what works well enough with // Roslyn C# compiler project // Size of local cache. private const int LocalSizeBits = 11; private const int LocalSize = (1 << LocalSizeBits); private const int LocalSizeMask = LocalSize - 1; // max size of shared cache. private const int SharedSizeBits = 16; private const int SharedSize = (1 << SharedSizeBits); private const int SharedSizeMask = SharedSize - 1; // size of bucket in shared cache. (local cache has bucket size 1). private const int SharedBucketBits = 4; private const int SharedBucketSize = (1 << SharedBucketBits); private const int SharedBucketSizeMask = SharedBucketSize - 1; // local (L1) cache // simple fast and not threadsafe cache // with limited size and "last add wins" expiration policy // // The main purpose of the local cache is to use in long lived // single threaded operations with lots of locality (like parsing). // Local cache is smaller (and thus faster) and is not affected // by cache misses on other threads. private readonly Entry[] _localTable = new Entry[LocalSize]; // shared (L2) threadsafe cache // slightly slower than local cache // we read this cache when having a miss in local cache // writes to local cache will update shared cache as well. private static readonly SegmentedArray<Entry> s_sharedTable = new SegmentedArray<Entry>(SharedSize); // essentially a random number // the usage pattern will randomly use and increment this // the counter is not static to avoid interlocked operations and cross-thread traffic private int _localRandom = Environment.TickCount; // same as above but for users that go directly with unbuffered shared cache. private static int s_sharedRandom = Environment.TickCount; internal StringTable() : this(null) { } // implement Poolable object pattern #region "Poolable" private StringTable(ObjectPool<StringTable>? pool) { _pool = pool; } private readonly ObjectPool<StringTable>? _pool; private static readonly ObjectPool<StringTable> s_staticPool = CreatePool(); private static ObjectPool<StringTable> CreatePool() { var pool = new ObjectPool<StringTable>(pool => new StringTable(pool), Environment.ProcessorCount * 2); return pool; } public static StringTable GetInstance() { return s_staticPool.Allocate(); } public void Free() { // leave cache content in the cache, just return it to the pool // Array.Clear(this.localTable, 0, this.localTable.Length); // Array.Clear(sharedTable, 0, sharedTable.Length); _pool?.Free(this); } #endregion // Poolable /// <summary> /// Legacy entrypoint for VB. /// </summary> internal string Add(char[] chars) => Add(chars.AsSpan()); /// <summary> /// Legacy entrypoint for VB. /// </summary> internal string Add(char[] chars, int start, int len) => Add(chars.AsSpan(start, len)); internal string Add(ReadOnlySpan<char> chars) { var hashCode = Hash.GetFNVHashCode(chars); // capture array to avoid extra range checks var arr = _localTable; var idx = LocalIdxFromHash(hashCode); var text = arr[idx].Text; if (text != null && arr[idx].HashCode == hashCode) { var result = arr[idx].Text; if (TextEquals(result, chars)) { return result; } } string? shared = FindSharedEntry(chars, hashCode); if (shared != null) { // PERF: the following code does element-wise assignment of a struct // because current JIT produces better code compared to // arr[idx] = new Entry(...) arr[idx].HashCode = hashCode; arr[idx].Text = shared; return shared; } return AddItem(chars, hashCode); } internal string Add(string chars, int start, int len) => Add(chars.AsSpan(start, len)); internal string Add(char chars) => Add([chars]); internal string Add(StringBuilder chars) { var hashCode = Hash.GetFNVHashCode(chars); // capture array to avoid extra range checks var arr = _localTable; var idx = LocalIdxFromHash(hashCode); var text = arr[idx].Text; if (text != null && arr[idx].HashCode == hashCode) { var result = arr[idx].Text; if (StringTable.TextEquals(result, chars)) { return result; } } string? shared = FindSharedEntry(chars, hashCode); if (shared != null) { // PERF: the following code does element-wise assignment of a struct // because current JIT produces better code compared to // arr[idx] = new Entry(...) arr[idx].HashCode = hashCode; arr[idx].Text = shared; return shared; } return AddItem(chars, hashCode); } internal string Add(string chars) => Add(chars.AsSpan()); private static string? FindSharedEntry(ReadOnlySpan<char> chars, int hashCode) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); string? e = null; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { e = arr[idx].Text; int hash = arr[idx].HashCode; if (e != null) { if (hash == hashCode && TextEquals(e, chars)) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } private static string? FindSharedEntry(string chars, int start, int len, int hashCode) => FindSharedEntry(chars.AsSpan(start, len), hashCode); private static string? FindSharedEntryASCII(int hashCode, ReadOnlySpan<byte> asciiChars) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); string? e = null; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { e = arr[idx].Text; int hash = arr[idx].HashCode; if (e != null) { if (hash == hashCode && TextEqualsASCII(e, asciiChars)) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } private static string? FindSharedEntry(char chars, int hashCode) => FindSharedEntry([chars], hashCode); private static string? FindSharedEntry(StringBuilder chars, int hashCode) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); string? e = null; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { e = arr[idx].Text; int hash = arr[idx].HashCode; if (e != null) { if (hash == hashCode && TextEquals(e, chars)) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } private static string? FindSharedEntry(string chars, int hashCode) => FindSharedEntry(chars.AsSpan(), hashCode); private string AddItem(ReadOnlySpan<char> chars, int hashCode) { var text = chars.ToString(); AddCore(text, hashCode); return text; } private string AddItem(string chars, int start, int len, int hashCode) { // Don't defer to ReadOnlySpan<char> here, as it would cause an extra allocation // in the case where start/len exactly match the full span of chars. var text = chars.Substring(start, len); AddCore(text, hashCode); return text; } private string AddItem(char chars, int hashCode) => AddItem([chars], hashCode); private string AddItem(StringBuilder chars, int hashCode) { var text = chars.ToString(); AddCore(text, hashCode); return text; } private void AddCore(string chars, int hashCode) { // add to the shared table first (in case someone looks for same item) AddSharedEntry(hashCode, chars); // add to the local table too var arr = _localTable; var idx = LocalIdxFromHash(hashCode); arr[idx].HashCode = hashCode; arr[idx].Text = chars; } private void AddSharedEntry(int hashCode, string text) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); // try finding an empty spot in the bucket // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode int curIdx = idx; for (int i = 1; i < SharedBucketSize + 1; i++) { if (arr[curIdx].Text == null) { idx = curIdx; goto foundIdx; } curIdx = (curIdx + i) & SharedSizeMask; } // or pick a random victim within the bucket range // and replace with new entry var i1 = LocalNextRandom() & SharedBucketSizeMask; idx = (idx + ((i1 * i1 + i1) / 2)) & SharedSizeMask; foundIdx: arr[idx].HashCode = hashCode; Volatile.Write(ref arr[idx].Text, text); } private static string AddSharedSlow(int hashCode, StringBuilder builder) { string text = builder.ToString(); AddSharedSlow(hashCode, text); return text; } internal static string AddSharedUtf8(ReadOnlySpan<byte> bytes) { int hashCode = Hash.GetFNVHashCode(bytes, out bool isAscii); if (isAscii) { string? shared = FindSharedEntryASCII(hashCode, bytes); if (shared != null) { return shared; } } return AddSharedSlow(hashCode, bytes, isAscii); } private static string AddSharedSlow(int hashCode, ReadOnlySpan<byte> utf8Bytes, bool isAscii) { string text; unsafe { fixed (byte* bytes = &utf8Bytes.GetPinnableReference()) { text = Encoding.UTF8.GetString(bytes, utf8Bytes.Length); } } // Don't add non-ascii strings to table. The hashCode we have here is not correct and we won't find them again. // Non-ascii in UTF-8 encoded parts of metadata (the only use of this at the moment) is assumed to be rare in // practice. If that turns out to be wrong, we could decode to pooled memory and rehash here. if (isAscii) { AddSharedSlow(hashCode, text); } return text; } private static void AddSharedSlow(int hashCode, string text) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); // try finding an empty spot in the bucket // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode int curIdx = idx; for (int i = 1; i < SharedBucketSize + 1; i++) { if (arr[curIdx].Text == null) { idx = curIdx; goto foundIdx; } curIdx = (curIdx + i) & SharedSizeMask; } // or pick a random victim within the bucket range // and replace with new entry var i1 = SharedNextRandom() & SharedBucketSizeMask; idx = (idx + ((i1 * i1 + i1) / 2)) & SharedSizeMask; foundIdx: arr[idx].HashCode = hashCode; Volatile.Write(ref arr[idx].Text, text); } private static int LocalIdxFromHash(int hash) { return hash & LocalSizeMask; } private static int SharedIdxFromHash(int hash) { // we can afford to mix some more hash bits here return (hash ^ (hash >> LocalSizeBits)) & SharedSizeMask; } private int LocalNextRandom() { return _localRandom++; } private static int SharedNextRandom() { return Interlocked.Increment(ref StringTable.s_sharedRandom); } internal static bool TextEquals(string array, string text, int start, int length) { if (array.Length != length) { return false; } // use array.Length to eliminate the range check for (var i = 0; i < array.Length; i++) { if (array[i] != text[start + i]) { return false; } } return true; } internal static bool TextEquals(string array, StringBuilder text) { if (array.Length != text.Length) { return false; } #if NETCOREAPP3_1_OR_GREATER int chunkOffset = 0; foreach (var chunk in text.GetChunks()) { if (!chunk.Span.Equals(array.AsSpan().Slice(chunkOffset, chunk.Length), StringComparison.Ordinal)) return false; chunkOffset += chunk.Length; } #else // interestingly, stringbuilder holds the list of chunks by the tail // so accessing positions at the beginning may cost more than those at the end. for (var i = array.Length - 1; i >= 0; i--) { if (array[i] != text[i]) { return false; } } #endif return true; } internal static bool TextEqualsASCII(string text, ReadOnlySpan<byte> ascii) { #if DEBUG for (var i = 0; i < ascii.Length; i++) { RoslynDebug.Assert((ascii[i] & 0x80) == 0, $"The {nameof(ascii)} input to this method must be valid ASCII."); } #endif if (ascii.Length != text.Length) { return false; } for (var i = 0; i < ascii.Length; i++) { if (ascii[i] != text[i]) { return false; } } return true; } internal static bool TextEquals(string array, ReadOnlySpan<char> text) => text.Equals(array.AsSpan(), StringComparison.Ordinal); } }
412
0.859661
1
0.859661
game-dev
MEDIA
0.173732
game-dev
0.948761
1
0.948761
GJKen/L4d2_plugins
3,807
可选-更改游戏描述(v1.0.1)(yuzumi)/left4dead2/addons/sourcemod/scripting/l4d2_get_game_description.sp
/* * 野生作者添加了一个配置文件方便萌新更改默认内容. */ #pragma semicolon 1 #pragma newdecls required #include <sourcemod> #include <sourcescramble> #define GAMEDATA "l4d2_get_game_description" MemoryPatch g_mGameDesPatch; //记录内存修补数据 bool g_bPatchEnable; //记录内存补丁状态 int g_iOS; //记录不同系统下的修改位置起始点 char g_sPath[PLATFORM_MAX_PATH], g_sGameDes[128]; //最大128长度, 中文占3字节(UTF8), 全中文最多42(服务器文件函数里写死0x80(128)长度) public Plugin myinfo = { name = "Set Game Description", author = "yuzumi | 修改: 豆瓣酱な", version = "1.0.1", description = "Change Description at any time!", url = "https://github.com/joyrhyme/L4D2-Plugins/tree/main/Set_GameDescription" }; public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max) { EngineVersion iEngineVersion = GetEngineVersion(); if(iEngineVersion != Engine_Left4Dead2 && !IsDedicatedServer()) { strcopy(error, err_max, "Plugin only supports Left 4 Dead 2 and Dedicated Server!"); return APLRes_SilentFailure; } return APLRes_Success; } public void OnPluginStart() { RegConsoleCmd("sm_set", Command_SetGameDes, "更改游戏描述 - Change Game Description"); GetFileContent();//获取文件里的内容. GetInitGameData();//加载签名文件. } public void OnConfigsExecuted() { GetFileContent();//获取文件里的内容. } //获取文件里的服名. void GetFileContent() { BuildPath(Path_SM, g_sPath, sizeof(g_sPath), "configs/l4d2_get_game_description.txt"); if(FileExists(g_sPath))//判断文件是否存在. SetGameDescription();//文件已存在,获取文件里的内容. else IsWriteGameDescription("生存之旅 3");//文件不存在,创建文件并写入默认内容. } //获取文件里的内容. void SetGameDescription() { File file = OpenFile(g_sPath, "rb"); if(file) { while(!file.EndOfFile()) file.ReadLine(g_sGameDes, sizeof(g_sGameDes)); TrimString(g_sGameDes);//整理获取到的字符串. } delete file; } //写入内容到文件里. void IsWriteGameDescription(char[] sDescription) { File file = OpenFile(g_sPath, "w"); strcopy(g_sGameDes, sizeof(g_sGameDes), sDescription); TrimString(g_sGameDes);//写入内容前整理字符串. if(file) WriteFileString(file, g_sGameDes, false);//这个方法写入内容不会自动添加换行符. delete file; } void GetInitGameData() { char sPath[PLATFORM_MAX_PATH]; BuildPath(Path_SM, sPath, sizeof sPath, "gamedata/%s.txt", GAMEDATA); if (!FileExists(sPath)) SetFailState("\n==========\nMissing required file: \"%s\".\n==========", sPath); GameData hGameData = new GameData(GAMEDATA); if (!hGameData) SetFailState("Failed to load \"%s.txt\" gamedata.", GAMEDATA); g_mGameDesPatch = MemoryPatch.CreateFromConf(hGameData, "GetGameDescription::GameDescription"); if (!g_mGameDesPatch.Validate()) SetFailState("Failed to verify patch: \"GetGameDescription::GameDescription\""); else if (g_mGameDesPatch.Enable()) { g_iOS = hGameData.GetOffset("OS") ? 4 : 1; //Linux从第5位开始,Win从第2位开始(从0开始算) StoreToAddress(g_mGameDesPatch.Address + view_as<Address>(g_iOS), view_as<int>(GetAddressOfString(g_sGameDes)), NumberType_Int32); PrintToServer("[%s] Enabled patch: \"GetGameDescription::GameDescription\"", GAMEDATA); g_bPatchEnable = true; //上面校验不通过的话应该不会Enable,所以记录这个就行? } delete hGameData; } Action Command_SetGameDes(int client, int args) { if(IsCheckClientAccess(client)) { if(args == 0) { GetFileContent(); ReplyToCommand(client, "\x04[提示]\x05已重新加载配置文件(使用指令!set空格+内容设置新描述)."); ReplyToCommand(client, "\x04[提示]\x05已设置新描述为\x04:\x05(\x03%s\x05)\x04.", g_sGameDes); } else { if (g_bPatchEnable) { char sArg[128]; GetCmdArgString(sArg, sizeof(sArg)); IsWriteGameDescription(sArg);//写入内容到文件里. ReplyToCommand(client, "\x04[提示]\x05已设置新描述为\x04:\x05(\x03%s\x05)\x04.", g_sGameDes); } else ReplyToCommand(client, "\x04[提示]\x05游戏签名文件未加载或无效."); } } else PrintToChat(client, "\x04[提示]\x05只限管理员使用该指令."); return Plugin_Handled; } bool IsCheckClientAccess(int client) { if(GetUserFlagBits(client) & ADMFLAG_ROOT) return true; return false; }
412
0.835363
1
0.835363
game-dev
MEDIA
0.817948
game-dev
0.807785
1
0.807785
DruidMech/UE4-CPP-Shooter-Series
17,551
Source Code Per Lesson/Section 10 - Outline and Glow Effects/179 Exchange Inventory Items/ShooterCharacter.h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Character.h" #include "AmmoType.h" #include "ShooterCharacter.generated.h" UENUM(BlueprintType) enum class ECombatState : uint8 { ECS_Unoccupied UMETA(DisplayName = "Unoccupied"), ECS_FireTimerInProgress UMETA(DisplayName = "FireTimerInProgress"), ECS_Reloading UMETA(DisplayName = "Reloading"), ECS_NAX UMETA(DisplayName = "DefaultMAX") }; USTRUCT(BlueprintType) struct FInterpLocation { GENERATED_BODY() // Scene component to use for its location for interping UPROPERTY(VisibleAnywhere, BlueprintReadOnly) USceneComponent* SceneComponent; // Number of items interping to/at this scene comp location UPROPERTY(VisibleAnywhere, BlueprintReadOnly) int32 ItemCount; }; DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FEquipItemDelegate, int32, CurrentSlotIndex, int32, NewSlotIndex); UCLASS() class SHOOTER_API AShooterCharacter : public ACharacter { GENERATED_BODY() public: // Sets default values for this character's properties AShooterCharacter(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; /** Called for forwards/backwards input */ void MoveForward(float Value); /** Called for side to side input */ void MoveRight(float Value); /** * Called via input to turn at a given rate. * @param Rate This is a normalized rate, i.e. 1.0 means 100% of desired turn rate */ void TurnAtRate(float Rate); /** * Called via input to look up/down at a given rate. * @param Rate This is a normalized rate, i.e. 1.0 means 100% of desired rate */ void LookUpAtRate(float Rate); /** * Rotate controller based on mouse X movement * @param Value The input value from mouse movement */ void Turn(float Value); /** * Rotate controller based on mouse Y movement * @param Value The input value from mouse movement */ void LookUp(float Value); /** Called when the Fire Button is pressed */ void FireWeapon(); bool GetBeamEndLocation(const FVector& MuzzleSocketLocation, FVector& OutBeamLocation); /** Set bAiming to true or false with button press */ void AimingButtonPressed(); void AimingButtonReleased(); void CameraInterpZoom(float DeltaTime); /** Set BaseTurnRate and BaseLookUpRate based on aiming */ void SetLookRates(); void CalculateCrosshairSpread(float DeltaTime); void StartCrosshairBulletFire(); UFUNCTION() void FinishCrosshairBulletFire(); void FireButtonPressed(); void FireButtonReleased(); void StartFireTimer(); UFUNCTION() void AutoFireReset(); /** Line trace for items under the crosshairs */ bool TraceUnderCrosshairs(FHitResult& OutHitResult, FVector& OutHitLocation); /** Trace for items if OverlappedItemCount > 0 */ void TraceForItems(); /** Spawns a default weapon and equips it */ class AWeapon* SpawnDefaultWeapon(); /** Takes a weapon and attaches it to the mesh */ void EquipWeapon(AWeapon* WeaponToEquip); /** Detach weapon and let it fall to the ground */ void DropWeapon(); void SelectButtonPressed(); void SelectButtonReleased(); /** Drops currently equipped Weapon and Equips TraceHitItem */ void SwapWeapon(AWeapon* WeaponToSwap); /** Initialize the Ammo Map with ammo values */ void InitializeAmmoMap(); /** Check to make sure our weapon has ammo */ bool WeaponHasAmmo(); /** FireWeapon functions */ void PlayFireSound(); void SendBullet(); void PlayGunfireMontage(); /** Bound to the R key and Gamepad Face Button Left */ void ReloadButtonPressed(); /** Handle reloading of the weapon */ void ReloadWeapon(); /** Checks to see if we have ammo of the EquippedWeapon's ammo type */ bool CarryingAmmo(); /** Called from Animation Blueprint with Grab Clip notify */ UFUNCTION(BlueprintCallable) void GrabClip(); /** Called from Animation Blueprint with Release Clip notify */ UFUNCTION(BlueprintCallable) void ReleaseClip(); void CrouchButtonPressed(); virtual void Jump() override; /** Interps capsule half height when crouching/standing */ void InterpCapsuleHalfHeight(float DeltaTime); void Aim(); void StopAiming(); void PickupAmmo(class AAmmo* Ammo); void InitializeInterpLocations(); void FKeyPressed(); void OneKeyPressed(); void TwoKeyPressed(); void ThreeKeyPressed(); void FourKeyPressed(); void FiveKeyPressed(); void ExchangeInventoryItems(int32 CurrentItemIndex, int32 NewItemIndex); public: // Called every frame virtual void Tick(float DeltaTime) override; // Called to bind functionality to input virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override; private: /** Camera boom positioning the camera behind the character */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true")) class USpringArmComponent* CameraBoom; /** Camera that follows the character */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true")) class UCameraComponent* FollowCamera; /** Base turn rate, in deg/sec. Other scaling may affect final turn rate */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true")) float BaseTurnRate; /** Base look up/down rate, in deg/sec. Other scaling may affect final turn rate */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true")) float BaseLookUpRate; /** Turn rate while not aiming */ UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true")) float HipTurnRate; /** Look up rate when not aiming */ UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true")) float HipLookUpRate; /** Turn rate when aiming */ UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true")) float AimingTurnRate; /** Look up rate when aiming */ UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true")) float AimingLookUpRate; /** Scale factor for mouse look sensitivity. Turn rate when not aiming. */ UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"), meta = (ClampMin = "0.0", ClampMax = "1.0", UIMin = "0.0", UIMax = "1.0")) float MouseHipTurnRate; /** Scale factor for mouse look sensitivity. Look up rate when not aiming. */ UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"), meta = (ClampMin = "0.0", ClampMax = "1.0", UIMin = "0.0", UIMax = "1.0")) float MouseHipLookUpRate; /** Scale factor for mouse look sensitivity. Turn rate when aiming. */ UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"), meta = (ClampMin = "0.0", ClampMax = "1.0", UIMin = "0.0", UIMax = "1.0")) float MouseAimingTurnRate; /** Scale factor for mouse look sensitivity. Look up rate when aiming. */ UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"), meta = (ClampMin = "0.0", ClampMax = "1.0", UIMin = "0.0", UIMax = "1.0")) float MouseAimingLookUpRate; /** Randomized gunshot sound cue */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Combat, meta = (AllowPrivateAccess = "true")) class USoundCue* FireSound; /** Flash spawned at BarrelSocket */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Combat, meta = (AllowPrivateAccess = "true")) class UParticleSystem* MuzzleFlash; /** Montage for firing the weapon */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Combat, meta = (AllowPrivateAccess = "true")) class UAnimMontage* HipFireMontage; /** Particles spawned upon bullet impact */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Combat, meta = (AllowPrivateAccess = "true")) UParticleSystem* ImpactParticles; /** Smoke trail for bullets */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Combat, meta = (AllowPrivateAccess = "true")) UParticleSystem* BeamParticles; /** True when aiming */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Combat, meta = (AllowPrivateAccess = "true")) bool bAiming; /** Default camera field of view value */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Combat, meta = (AllowPrivateAccess = "true")) float CameraDefaultFOV; /** Field of view value for when zoomed in */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Combat, meta = (AllowPrivateAccess = "true")) float CameraZoomedFOV; /** Current field of view this frame */ float CameraCurrentFOV; /** Interp speed for zooming when aiming */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Combat, meta = (AllowPrivateAccess = "true")) float ZoomInterpSpeed; /** Determines the spread of the crosshairs */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Crosshairs, meta = (AllowPrivateAccess = "true")) float CrosshairSpreadMultiplier; /** Velocity component for crosshairs spread */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Crosshairs, meta = (AllowPrivateAccess = "true")) float CrosshairVelocityFactor; /** In air component for crosshairs spread */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Crosshairs, meta = (AllowPrivateAccess = "true")) float CrosshairInAirFactor; /** Aim component for crosshairs spread */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Crosshairs, meta = (AllowPrivateAccess = "true")) float CrosshairAimFactor; /** Shooting component for crosshairs spread */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Crosshairs, meta = (AllowPrivateAccess = "true")) float CrosshairShootingFactor; float ShootTimeDuration; bool bFiringBullet; FTimerHandle CrosshairShootTimer; /** Left mouse button or right console trigger pressed */ bool bFireButtonPressed; /** True when we can fire. False when waiting for the timer */ bool bShouldFire; /** Rate of automatic gun fire */ float AutomaticFireRate; /** Sets a timer between gunshots */ FTimerHandle AutoFireTimer; /** True if we should trace every frame for items */ bool bShouldTraceForItems; /** Number of overlapped AItems */ int8 OverlappedItemCount; /** The AItem we hit last frame */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Items, meta = (AllowPrivateAccess = "true")) class AItem* TraceHitItemLastFrame; /** Currently equipped Weapon */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Combat, meta = (AllowPrivateAccess = "true")) AWeapon* EquippedWeapon; /** Set this in Blueprints for the default Weapon class */ UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = Combat, meta = (AllowPrivateAccess = "true")) TSubclassOf<AWeapon> DefaultWeaponClass; /** The item currently hit by our trace in TraceForItems (could be null) */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Combat, meta = (AllowPrivateAccess = "true")) AItem* TraceHitItem; /** Distance outward from the camera for the interp destination */ UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Items, meta = (AllowPrivateAccess = "true")) float CameraInterpDistance; /** Distance upward from the camera for the interp destination */ UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Items, meta = (AllowPrivateAccess = "true")) float CameraInterpElevation; /** Map to keep track of ammo of the different ammo types */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Items, meta = (AllowPrivateAccess = "true")) TMap<EAmmoType, int32> AmmoMap; /** Starting amount of 9mm ammo */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Items, meta = (AllowPrivateAccess = "true")) int32 Starting9mmAmmo; /** Starting amount of AR ammo */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Items, meta = (AllowPrivateAccess = "true")) int32 StartingARAmmo; /** Combat State, can only fire or reload if Unoccupied */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Combat, meta = (AllowPrivateAccess = "true")) ECombatState CombatState; /** Montage for reload animations */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Combat, meta = (AllowPrivateAccess = "true")) UAnimMontage* ReloadMontage; UFUNCTION(BlueprintCallable) void FinishReloading(); /** Transform of the clip when we first grab the clip during reloading */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Combat, meta = (AllowPrivateAccess = "true")) FTransform ClipTransform; /** Scene component to attach to the Character's hand during reloading */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Combat, meta = (AllowPrivateAccess = "true")) USceneComponent* HandSceneComponent; /** True when crouching */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Movement, meta = (AllowPrivateAccess = "true")) bool bCrouching; /** Regular movement speed */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Movement, meta = (AllowPrivateAccess = "true")) float BaseMovementSpeed; /** Crouch movement speed */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Movement, meta = (AllowPrivateAccess = "true")) float CrouchMovementSpeed; /** Current half height of the capsule */ float CurrentCapsuleHalfHeight; /** Half height of the capsule when not crouching */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Movement, meta = (AllowPrivateAccess = "true")) float StandingCapsuleHalfHeight; /** Half height of the capsule when crouching */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Movement, meta = (AllowPrivateAccess = "true")) float CrouchingCapsuleHalfHeight; /** Ground friction while not crouching */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Movement, meta = (AllowPrivateAccess = "true")) float BaseGroundFriction; /** Ground friction while crouching */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Movement, meta = (AllowPrivateAccess = "true")) float CrouchingGroundFriction; /** Used for knowing when the aiming button is pressed */ bool bAimingButtonPressed; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, meta = (AllowPrivateAccess = "true")) USceneComponent* WeaponInterpComp; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, meta = (AllowPrivateAccess = "true")) USceneComponent* InterpComp1; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, meta = (AllowPrivateAccess = "true")) USceneComponent* InterpComp2; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, meta = (AllowPrivateAccess = "true")) USceneComponent* InterpComp3; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, meta = (AllowPrivateAccess = "true")) USceneComponent* InterpComp4; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, meta = (AllowPrivateAccess = "true")) USceneComponent* InterpComp5; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, meta = (AllowPrivateAccess = "true")) USceneComponent* InterpComp6; /** Array of interp location structs */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (AllowPrivateAccess = "true")) TArray<FInterpLocation> InterpLocations; FTimerHandle PickupSoundTimer; FTimerHandle EquipSoundTimer; bool bShouldPlayPickupSound; bool bShouldPlayEquipSound; void ResetPickupSoundTimer(); void ResetEquipSoundTimer(); /** Time to wait before we can play another Pickup Sound */ UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Items, meta = (AllowPrivateAccess = "true")) float PickupSoundResetTime; /** Time to wait before we can play another Equip Sound */ UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Items, meta = (AllowPrivateAccess = "true")) float EquipSoundResetTime; /** An array of AItems for our Inventory */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Inventory, meta = (AllowPrivateAccess = "true")) TArray<AItem*> Inventory; const int32 INVENTORY_CAPACITY{ 6 }; /** Delegate for sending slot information to InventoryBar when equipping */ UPROPERTY(BlueprintAssignable, Category = Delegates, meta = (AllowPrivateAccess = "true")) FEquipItemDelegate EquipItemDelegate; public: /** Returns CameraBoom subobject */ FORCEINLINE USpringArmComponent* GetCameraBoom() const { return CameraBoom; } /** Returns FollowCamera subobject */ FORCEINLINE UCameraComponent* GetFollowCamera() const { return FollowCamera; } FORCEINLINE bool GetAiming() const { return bAiming; } UFUNCTION(BlueprintCallable) float GetCrosshairSpreadMultiplier() const; FORCEINLINE int8 GetOverlappedItemCount() const { return OverlappedItemCount; } /** Adds/subtracts to/from OverlappedItemCount and updates bShouldTraceForItems */ void IncrementOverlappedItemCount(int8 Amount); // No longer needed; AItem has GetInterpLocation //FVector GetCameraInterpLocation(); void GetPickupItem(AItem* Item); FORCEINLINE ECombatState GetCombatState() const { return CombatState; } FORCEINLINE bool GetCrouching() const { return bCrouching; } FInterpLocation GetInterpLocation(int32 Index); // Returns the index in InterpLocations array with the lowest ItemCount int32 GetInterpLocationIndex(); void IncrementInterpLocItemCount(int32 Index, int32 Amount); FORCEINLINE bool ShouldPlayPickupSound() const { return bShouldPlayPickupSound; } FORCEINLINE bool ShouldPlayEquipSound() const { return bShouldPlayEquipSound; } void StartPickupSoundTimer(); void StartEquipSoundTimer(); };
412
0.899035
1
0.899035
game-dev
MEDIA
0.918016
game-dev
0.627926
1
0.627926
lsils/mockturtle
41,156
lib/abcesop/exorList.cpp
/**CFile**************************************************************** FileName [exorList.c] SystemName [ABC: Logic synthesis and verification system.] PackageName [Exclusive sum-of-product minimization.] Synopsis [Cube lists.] Author [Alan Mishchenko] Affiliation [UC Berkeley] Date [Ver. 1.0. Started - June 20, 2005.] Revision [$Id: exorList.c,v 1.0 2005/06/20 00:00:00 alanmi Exp $] ***********************************************************************/ //////////////////////////////////////////////////////////////////////// /// /// /// Implementation of EXORCISM - 4 /// /// An Exclusive Sum-of-Product Minimizer /// /// /// /// Alan Mishchenko <alanmi@ee.pdx.edu> /// /// /// //////////////////////////////////////////////////////////////////////// /// /// /// Iterative Cube Set Minimization /// /// Iterative ExorLink Procedure /// /// Support of Cube Pair Queques /// /// /// /// Ver. 1.0. Started - July 18, 2000. Last update - July 20, 2000 /// /// Ver. 1.1. Started - July 24, 2000. Last update - July 29, 2000 /// /// Ver. 1.2. Started - July 30, 2000. Last update - July 31, 2000 /// /// Ver. 1.4. Started - Aug 10, 2000. Last update - Aug 26, 2000 /// /// Ver. 1.5. Started - Aug 30, 2000. Last update - Aug 30, 2000 /// /// Ver. 1.6. Started - Sep 11, 2000. Last update - Sep 15, 2000 /// /// Ver. 1.7. Started - Sep 20, 2000. Last update - Sep 23, 2000 /// /// /// //////////////////////////////////////////////////////////////////////// /// This software was tested with the BDD package "CUDD", v.2.3.0 /// /// by Fabio Somenzi /// /// http://vlsi.colorado.edu/~fabio/ /// //////////////////////////////////////////////////////////////////////// #include "eabc/exor.h" namespace abc::exorcism { //////////////////////////////////////////////////////////////////////// /// EXTERNAL VARIABLES /// //////////////////////////////////////////////////////////////////////// // information about options and the cover extern cinfo g_CoverInfo; // the look-up table for the number of 1's in unsigned short extern unsigned char BitCount[]; //////////////////////////////////////////////////////////////////////// /// EXTERNAL FUNCTIONS /// //////////////////////////////////////////////////////////////////////// extern int GetDistance( Cube* pC1, Cube* pC2 ); // distance computation for two cubes extern int GetDistancePlus( Cube* pC1, Cube* pC2 ); extern void ExorVar( Cube* pC, int Var, varvalue Val ); extern void AddToFreeCubes( Cube* pC ); // returns a simplified cube back into the free list //extern void PrintCube( ostream& DebugStream, Cube* pC ); // debug output for cubes extern Cube* GetFreeCube(); //////////////////////////////////////////////////////////////////////// /// ExorLink Functions extern int ExorLinkCubeIteratorStart( Cube** pGroup, Cube* pC1, Cube* pC2, cubedist Dist ); // this function starts the Exor-Link IteratorCubePair, which iterates // through the cube groups starting from the group with min literals // returns 1 on success, returns 0 if the cubes have wrong distance extern int ExorLinkCubeIteratorNext( Cube** pGroup ); // give the next group in the decreasing order of sum of literals // returns 1 on success, returns 0 if there are no more groups extern int ExorLinkCubeIteratorPick( Cube** pGroup, int g ); // gives the group #g in the order in which the groups were given // during iteration // returns 1 on success, returns 0 if something g is too large extern void ExorLinkCubeIteratorCleanUp( int fTakeLastGroup ); // removes the cubes from the store back into the list of free cubes // if fTakeLastGroup is 0, removes all cubes // if fTakeLastGroup is 1, does not store the last group //////////////////////////////////////////////////////////////////////// /// FUNCTIONS OF THIS MODULE /// //////////////////////////////////////////////////////////////////////// // iterative ExorLink int IterativelyApplyExorLink2( char fDistEnable ); int IterativelyApplyExorLink3( char fDistEnable ); int IterativelyApplyExorLink4( char fDistEnable ); // function which performs distance computation and simplifes on the fly // it is also called from the Pseudo-Kronecker module when cubes are added int CheckForCloseCubes( Cube* p, int fAddCube ); int CheckAndInsert( Cube* p ); // this function changes the cube back after it was DIST-1 transformed void UndoRecentChanges(); //////////////////////////////////////////////////////////////////////// // iterating through adjucency pair queques (with authomatic garbage collection) // start an iterator through cubes of dist CubeDist, // the resulting pointers are written into ppC1 and ppC2 int IteratorCubePairStart( cubedist Dist, Cube** ppC1, Cube** ppC2 ); // gives the next VALID cube pair (the previous one is automatically dequequed) int IteratorCubePairNext(); //////////////////////////////////////////////////////////////////////// // the cube storage // cube storage allocation/delocation int AllocateCubeSets( int nVarsIn, int nVarsOut ); void DelocateCubeSets(); // insert/extract a cube into/from the storage void CubeInsert( Cube* p ); Cube* CubeExtract( Cube* p ); //////////////////////////////////////////////////////////////////////// // Cube Set Iterator Cube* IterCubeSetStart(); // starts an iterator that traverses all the cubes in the ring Cube* IterCubeSetNext(); // returns the next cube in the ring // to use it again after it has returned NULL, call IterCubeSetStart() first //////////////////////////////////////////////////////////////////////// // cube adjacency queques // adjacency queque allocation/delocation procedures int AllocateQueques( int nPlaces ); void DelocateQueques(); // conditional adding cube pairs to queques // reset temporarily stored new range of cube pairs static void NewRangeReset(); // add temporarily stored new range of cube pairs to the queque static void NewRangeAdd(); // insert one cube pair into the new range static void NewRangeInsertCubePair( cubedist Dist, Cube* p1, Cube* p2 ); static void MarkSet(); static void MarkRewind(); void PrintQuequeStats(); int GetQuequeStats( cubedist Dist ); // iterating through the queque (with authomatic garbage collection) // start an iterator through cubes of dist CubeDist, // the resulting pointers are written into ppC1 and ppC2 int IteratorCubePairStart( cubedist Dist, Cube** ppC1, Cube** ppC2 ); // gives the next VALID cube pair (the previous one is automatically dequequed) int IteratorCubePairNext(); //////////////////////////////////////////////////////////////////////// /// EXPORTED VARIABLES /// ////////////////////////////////////////////////////////////////////////` // the number of allocated places int s_nPosAlloc; // the maximum number of occupied places int s_nPosMax[3]; //////////////////////////////////////////////////////////////////////// /// Minimization Strategy /// //////////////////////////////////////////////////////////////////////// // 1) check that ExorLink for this cube pair can be performed // (it may happen that the group is outdated due to recent reshaping) // 2) find out what is the improvement achieved by each cube group // 3) depending on the distance, do the following: // a) if ( Dist == 2 ) // try both cube groups, // if one of them leads to improvement, take the cube group right away // if none of them leads to improment // - take the last one (because it reshapes) // - take the last one only in case it does not increase literals // b) if ( Dist == 3 ) // try groups one by one // if one of them leads to improvement, take the group right away // if none of them leads to improvement // - take the group which reshapes // - take the reshaping group only in case it does not increase literals // if none of them leads to reshaping, do not take any of them // c) if ( Dist == 4 ) // try groups one by one // if one of the leads to reshaping, take it right away // if none of them leads to reshaping, do not take any of them //////////////////////////////////////////////////////////////////////// /// STATIC VARIABLES /// //////////////////////////////////////////////////////////////////////// // Cube set is a list of cubes static Cube* s_List; /////////////////////////////////////////////////////////////////////////// // undo information /////////////////////////////////////////////////////////////////////////// static struct { int fInput; // 1 if the input was changed Cube* p; // the pointer to the modified cube int PrevQa; int PrevPa; int PrevQq; int PrevPq; int PrevPz; int Var; // the number of variable that was changed int Value; // the value what was there int PrevID; // the previous ID of the removed cube } s_ChangeStore; /////////////////////////////////////////////////////////////////////////// // enable pair accumulation // from the begginning (while the starting cover is generated) // only the distance 2 accumulation is enabled static int s_fDistEnable2 = 1; static int s_fDistEnable3; static int s_fDistEnable4; // temporary storage for cubes generated by the ExorLink iterator static Cube* s_CubeGroup[5]; // the marks telling whether the given cube is inserted static int s_fInserted[5]; // enable selection only those Dist2 and Dist3 that do not increase literals int s_fDecreaseLiterals = 0; // the counters for display static int s_cEnquequed; static int s_cAttempts; static int s_cReshapes; // the number of cubes before ExorLink starts static int s_nCubesBefore; // the distance code specific for each ExorLink static cubedist s_Dist; // other variables static int s_Gain; static int s_GainTotal; static int s_GroupCounter; static int s_GroupBest; static Cube *s_pC1, *s_pC2; //////////////////////////////////////////////////////////////////////// /// Iterative ExorLink Operation /// //////////////////////////////////////////////////////////////////////// int CheckAndInsert( Cube* p ) { // return CheckForCloseCubes( p, 1 ); CubeInsert( p ); return 0; } int IterativelyApplyExorLink2( char fDistEnable ) // MEMO: instead of inserting the cubes that have already been checked // by running CheckForCloseCubes again, try inserting them without checking // and observe the difference (it will save 50% of checking time) { int z; // this var is specific to ExorLink-2 s_Dist = (cubedist)0; // enable pair accumulation s_fDistEnable2 = fDistEnable & 1; s_fDistEnable3 = fDistEnable & 2; s_fDistEnable4 = fDistEnable & 4; // initialize counters s_cEnquequed = GetQuequeStats( s_Dist ); s_cAttempts = 0; s_cReshapes = 0; // remember the number of cubes before minimization s_nCubesBefore = g_CoverInfo.nCubesInUse; for ( z = IteratorCubePairStart( s_Dist, &s_pC1, &s_pC2 ); z; z = IteratorCubePairNext() ) { s_cAttempts++; // start ExorLink of the given Distance if ( ExorLinkCubeIteratorStart( s_CubeGroup, s_pC1, s_pC2, s_Dist ) ) { // extract old cubes from storage (to prevent EXORing with their derivitives) CubeExtract( s_pC1 ); CubeExtract( s_pC2 ); // mark the current position in the cube pair queques MarkSet(); // check the first group (generated by ExorLinkCubeIteratorStart()) if ( CheckForCloseCubes( s_CubeGroup[0], 0 ) ) { // the first cube leads to improvement - it is already inserted CheckForCloseCubes( s_CubeGroup[1], 1 ); // insert the second cube goto SUCCESS; } if ( CheckForCloseCubes( s_CubeGroup[1], 0 ) ) { // the second cube leads to improvement - it is already inserted CheckForCloseCubes( s_CubeGroup[0], 1 ); // insert the first cube // CheckAndInsert( s_CubeGroup[0] ); goto SUCCESS; } // the first group does not lead to improvement // rewind to the previously marked position in the cube pair queques MarkRewind(); // generate the second group ExorLinkCubeIteratorNext( s_CubeGroup ); // check the second group if ( CheckForCloseCubes( s_CubeGroup[0], 0 ) ) { // the first cube leads to improvement - it is already inserted CheckForCloseCubes( s_CubeGroup[1], 1 ); // insert the second cube goto SUCCESS; } if ( CheckForCloseCubes( s_CubeGroup[1], 0 ) ) { // the second cube leads to improvement - it is already inserted CheckForCloseCubes( s_CubeGroup[0], 1 ); // insert the first cube // CheckAndInsert( s_CubeGroup[0] ); goto SUCCESS; } // the second group does not lead to improvement // decide whether to accept the second group, depending on literals if ( s_fDecreaseLiterals ) { if ( g_CoverInfo.fUseQCost ? s_CubeGroup[0]->q + s_CubeGroup[1]->q >= s_pC1->q + s_pC2->q : s_CubeGroup[0]->a + s_CubeGroup[1]->a >= s_pC1->a + s_pC2->a ) // the group increases literals { // do not take the last group // rewind to the previously marked position in the cube pair queques MarkRewind(); // return the old cubes back to storage CubeInsert( s_pC1 ); CubeInsert( s_pC2 ); // clean the results of generating ExorLinked cubes ExorLinkCubeIteratorCleanUp( 0 ); continue; } } // take the last group // there is no need to test these cubes again, // because they have been tested and did not yield any improvement CubeInsert( s_CubeGroup[0] ); CubeInsert( s_CubeGroup[1] ); // CheckForCloseCubes( s_CubeGroup[0], 1 ); // CheckForCloseCubes( s_CubeGroup[1], 1 ); SUCCESS: // clean the results of generating ExorLinked cubes ExorLinkCubeIteratorCleanUp( 1 ); // take the last group // free old cubes AddToFreeCubes( s_pC1 ); AddToFreeCubes( s_pC2 ); // increate the counter s_cReshapes++; } } // print the report if ( g_CoverInfo.Verbosity == 2 ) { printf( "ExLink-%d", 2 ); printf( ": Que= %5d", s_cEnquequed ); printf( " Att= %4d", s_cAttempts ); printf( " Resh= %4d", s_cReshapes ); printf( " NoResh= %4d", s_cAttempts - s_cReshapes ); printf( " Cubes= %3d", g_CoverInfo.nCubesInUse ); printf( " (%d)", s_nCubesBefore - g_CoverInfo.nCubesInUse ); printf( " Lits= %5d", CountLiterals() ); printf( " QCost = %6d", CountQCost() ); printf( "\n" ); } // return the number of cubes gained in the process return s_nCubesBefore - g_CoverInfo.nCubesInUse; } int IterativelyApplyExorLink3( char fDistEnable ) { int z, c, d; // this var is specific to ExorLink-3 s_Dist = (cubedist)1; // enable pair accumulation s_fDistEnable2 = fDistEnable & 1; s_fDistEnable3 = fDistEnable & 2; s_fDistEnable4 = fDistEnable & 4; // initialize counters s_cEnquequed = GetQuequeStats( s_Dist ); s_cAttempts = 0; s_cReshapes = 0; // remember the number of cubes before minimization s_nCubesBefore = g_CoverInfo.nCubesInUse; for ( z = IteratorCubePairStart( s_Dist, &s_pC1, &s_pC2 ); z; z = IteratorCubePairNext() ) { s_cAttempts++; // start ExorLink of the given Distance if ( ExorLinkCubeIteratorStart( s_CubeGroup, s_pC1, s_pC2, s_Dist ) ) { // extract old cubes from storage (to prevent EXORing with their derivitives) CubeExtract( s_pC1 ); CubeExtract( s_pC2 ); // mark the current position in the cube pair queques MarkSet(); // check cube groups one by one s_GroupCounter = 0; do { // check the cubes of this group one by one for ( c = 0; c < 3; c++ ) if ( !s_CubeGroup[c]->fMark ) // this cube has not yet been checked { s_Gain = CheckForCloseCubes( s_CubeGroup[c], 0 ); // do not insert the cube, by default if ( s_Gain ) { // this cube leads to improvement or reshaping - it is already inserted // decide whether to accept this group based on literal count if ( s_fDecreaseLiterals && s_Gain == 1 ) if ( g_CoverInfo.fUseQCost ? s_CubeGroup[0]->q + s_CubeGroup[1]->q + s_CubeGroup[2]->q > s_pC1->q + s_pC2->q + s_ChangeStore.PrevQq : s_CubeGroup[0]->a + s_CubeGroup[1]->a + s_CubeGroup[2]->a > s_pC1->a + s_pC2->a + s_ChangeStore.PrevQa ) // the group increases literals { // do not take this group // remember the group s_GroupBest = s_GroupCounter; // undo changes to be able to continue checking other groups UndoRecentChanges(); break; } // take this group for ( d = 0; d < 3; d++ ) // insert other cubes if ( d != c ) { CheckForCloseCubes( s_CubeGroup[d], 1 ); // if ( s_CubeGroup[d]->fMark ) // CheckAndInsert( s_CubeGroup[d] ); // CheckOnlyOneCube( s_CubeGroup[d] ); // CheckForCloseCubes( s_CubeGroup[d], 1 ); // else // CheckForCloseCubes( s_CubeGroup[d], 1 ); } // clean the results of generating ExorLinked cubes ExorLinkCubeIteratorCleanUp( 1 ); // take the last group // free old cubes AddToFreeCubes( s_pC1 ); AddToFreeCubes( s_pC2 ); // update the counter s_cReshapes++; goto END_OF_LOOP; } else // mark the cube as checked s_CubeGroup[c]->fMark = 1; } // the group is not taken - find the new group s_GroupCounter++; // rewind to the previously marked position in the cube pair queques MarkRewind(); } while ( ExorLinkCubeIteratorNext( s_CubeGroup ) ); // none of the groups leads to improvement // return the old cubes back to storage CubeInsert( s_pC1 ); CubeInsert( s_pC2 ); // clean the results of generating ExorLinked cubes ExorLinkCubeIteratorCleanUp( 0 ); } END_OF_LOOP: {} } // print the report if ( g_CoverInfo.Verbosity == 2 ) { printf( "ExLink-%d", 3 ); printf( ": Que= %5d", s_cEnquequed ); printf( " Att= %4d", s_cAttempts ); printf( " Resh= %4d", s_cReshapes ); printf( " NoResh= %4d", s_cAttempts - s_cReshapes ); printf( " Cubes= %3d", g_CoverInfo.nCubesInUse ); printf( " (%d)", s_nCubesBefore - g_CoverInfo.nCubesInUse ); printf( " Lits= %5d", CountLiterals() ); printf( " QCost = %6d", CountQCost() ); printf( "\n" ); } // return the number of cubes gained in the process return s_nCubesBefore - g_CoverInfo.nCubesInUse; } int IterativelyApplyExorLink4( char fDistEnable ) { int z, c; // this var is specific to ExorLink-4 s_Dist = (cubedist)2; // enable pair accumulation s_fDistEnable2 = fDistEnable & 1; s_fDistEnable3 = fDistEnable & 2; s_fDistEnable4 = fDistEnable & 4; // initialize counters s_cEnquequed = GetQuequeStats( s_Dist ); s_cAttempts = 0; s_cReshapes = 0; // remember the number of cubes before minimization s_nCubesBefore = g_CoverInfo.nCubesInUse; for ( z = IteratorCubePairStart( s_Dist, &s_pC1, &s_pC2 ); z; z = IteratorCubePairNext() ) { s_cAttempts++; // start ExorLink of the given Distance if ( ExorLinkCubeIteratorStart( s_CubeGroup, s_pC1, s_pC2, s_Dist ) ) { // extract old cubes from storage (to prevent EXORing with their derivitives) CubeExtract( s_pC1 ); CubeExtract( s_pC2 ); // mark the current position in the cube pair queques MarkSet(); // check cube groups one by one do { // check the cubes of this group one by one s_GainTotal = 0; for ( c = 0; c < 4; c++ ) if ( !s_CubeGroup[c]->fMark ) // this cube has not yet been checked { s_Gain = CheckForCloseCubes( s_CubeGroup[c], 0 ); // do not insert the cube, by default // if the cube leads to gain, it is already inserted s_fInserted[c] = (int)(s_Gain>0); // increment the total gain s_GainTotal += s_Gain; } else s_fInserted[c] = 0; // the cube has already been checked - it is not inserted if ( s_GainTotal == 0 ) // the group does not lead to any gain { // mark the cubes for ( c = 0; c < 4; c++ ) s_CubeGroup[c]->fMark = 1; } else if ( s_GainTotal == 1 ) // the group does not lead to substantial gain, too { // undo changes to be able to continue checking groups UndoRecentChanges(); // mark those cubes that were not inserted for ( c = 0; c < 4; c++ ) s_CubeGroup[c]->fMark = !s_fInserted[c]; } else // if ( s_GainTotal > 1 ) // the group reshapes or improves { // accept the group for ( c = 0; c < 4; c++ ) // insert other cubes if ( !s_fInserted[c] ) CheckForCloseCubes( s_CubeGroup[c], 1 ); // CheckAndInsert( s_CubeGroup[c] ); // clean the results of generating ExorLinked cubes ExorLinkCubeIteratorCleanUp( 1 ); // take the last group // free old cubes AddToFreeCubes( s_pC1 ); AddToFreeCubes( s_pC2 ); // update the counter s_cReshapes++; goto END_OF_LOOP; } // rewind to the previously marked position in the cube pair queques MarkRewind(); } while ( ExorLinkCubeIteratorNext( s_CubeGroup ) ); // none of the groups leads to improvement // return the old cubes back to storage CubeInsert( s_pC1 ); CubeInsert( s_pC2 ); // clean the results of generating ExorLinked cubes ExorLinkCubeIteratorCleanUp( 0 ); } END_OF_LOOP: {} } // print the report if ( g_CoverInfo.Verbosity == 2 ) { printf( "ExLink-%d", 4 ); printf( ": Que= %5d", s_cEnquequed ); printf( " Att= %4d", s_cAttempts ); printf( " Resh= %4d", s_cReshapes ); printf( " NoResh= %4d", s_cAttempts - s_cReshapes ); printf( " Cubes= %3d", g_CoverInfo.nCubesInUse ); printf( " (%d)", s_nCubesBefore - g_CoverInfo.nCubesInUse ); printf( " Lits= %5d", CountLiterals() ); printf( " QCost = %6d", CountQCost() ); printf( "\n" ); } // return the number of cubes gained in the process return s_nCubesBefore - g_CoverInfo.nCubesInUse; } // local static variables Cube* s_q; int s_Distance; int s_DiffVarNum; int s_DiffVarValueP_old; int s_DiffVarValueP_new; int s_DiffVarValueQ; int CheckForCloseCubes( Cube* p, int fAddCube ) // checks the cube storage for a cube that is dist-0 and dist-1 removed // from the given one (p) if such a cube is found, extracts it from the data // structure, EXORs it with the given cube, adds the resultant cube // to the data structure and performed the same check for the resultant cube; // returns the number of cubes gained in the process of reduction; // if an adjacent cube is not found, inserts the cube only if (fAddCube==1)!!! { // start the new range NewRangeReset(); for ( s_q = s_List; s_q; s_q = s_q->Next ) { s_Distance = GetDistancePlus( p, s_q ); if ( s_Distance > 4 ) { } else if ( s_Distance == 4 ) { if ( s_fDistEnable4 ) NewRangeInsertCubePair( DIST4, p, s_q ); } else if ( s_Distance == 3 ) { if ( s_fDistEnable3 ) NewRangeInsertCubePair( DIST3, p, s_q ); } else if ( s_Distance == 2 ) { if ( s_fDistEnable2 ) NewRangeInsertCubePair( DIST2, p, s_q ); } else if ( s_Distance == 1 ) { // extract the cube from the data structure ////////////////////////////////////////////////////////// // store the changes s_ChangeStore.fInput = (s_DiffVarNum != -1); s_ChangeStore.p = p; s_ChangeStore.PrevQa = s_q->a; s_ChangeStore.PrevPa = p->a; s_ChangeStore.PrevQq = s_q->q; s_ChangeStore.PrevPq = p->q; s_ChangeStore.PrevPz = p->z; s_ChangeStore.Var = s_DiffVarNum; s_ChangeStore.Value = s_DiffVarValueQ; s_ChangeStore.PrevID = s_q->ID; ////////////////////////////////////////////////////////// CubeExtract( s_q ); // perform the EXOR of the two cubes and write the result into p // it is important that the resultant cube is written into p!!! if ( s_DiffVarNum == -1 ) { int i; // exor the output part p->z = 0; for ( i = 0; i < g_CoverInfo.nWordsOut; i++ ) { p->pCubeDataOut[i] ^= s_q->pCubeDataOut[i]; p->z += BIT_COUNT(p->pCubeDataOut[i]); } } else { // the cube has already been updated by GetDistancePlus() // modify the parameters of the number of literals in the new cube // p->a += s_UpdateLiterals[ s_DiffVarValueP ][ s_DiffVarValueQ ]; if ( s_DiffVarValueP_old == VAR_NEG || s_DiffVarValueP_old == VAR_POS ) p->a--; if ( s_DiffVarValueP_new == VAR_NEG || s_DiffVarValueP_new == VAR_POS ) p->a++; p->q = ComputeQCostBits(p); } // move q to the free cube list AddToFreeCubes( s_q ); // make sure that nobody with use the pairs created so far // NewRangeReset(); // call the function again for the new cube return 1 + CheckForCloseCubes( p, 1 ); } else // if ( Distance == 0 ) { // extract the second cube from the data structure and add them both to the free list AddToFreeCubes( p ); AddToFreeCubes( CubeExtract( s_q ) ); // make sure that nobody with use the pairs created so far NewRangeReset(); return 2; } } // add the cube to the data structure if needed if ( fAddCube ) CubeInsert( p ); // add temporarily stored new range of cube pairs to the queque NewRangeAdd(); return 0; } void UndoRecentChanges() { Cube * p, * q; // get back cube q that was deleted q = GetFreeCube(); // restore the ID q->ID = s_ChangeStore.PrevID; // insert the cube into storage again CubeInsert( q ); // extract cube p p = CubeExtract( s_ChangeStore.p ); // modify it back if ( s_ChangeStore.fInput ) // the input has changed { ExorVar( p, s_ChangeStore.Var, (varvalue)s_ChangeStore.Value ); p->a = s_ChangeStore.PrevPa; p->q = s_ChangeStore.PrevPq; // p->z did not change } else // if ( s_ChangeStore.fInput ) // the output has changed { int i; for ( i = 0; i < g_CoverInfo.nWordsOut; i++ ) p->pCubeDataOut[i] ^= q->pCubeDataOut[i]; p->z = s_ChangeStore.PrevPz; // p->a did not change } } /////////////////////////////////////////////////////////////////// /// CUBE SET MANIPULATION PROCEDURES /// /////////////////////////////////////////////////////////////////// // Cube set is a list of cubes //static Cube* s_List; /////////////////////////////////////////////////////////////////// /// Memory Allocation/Delocation /// /////////////////////////////////////////////////////////////////// int AllocateCubeSets( int nVarsIn, int nVarsOut ) { s_List = NULL; // clean other data s_fDistEnable2 = 1; s_fDistEnable3 = 0; s_fDistEnable4 = 0; memset( s_CubeGroup, 0, sizeof(void *) * 5 ); memset( s_fInserted, 0, sizeof(int) * 5 ); s_fDecreaseLiterals = 0; s_cEnquequed = 0; s_cAttempts = 0; s_cReshapes = 0; s_nCubesBefore = 0; s_Gain = 0; s_GainTotal = 0; s_GroupCounter = 0; s_GroupBest = 0; s_pC1 = s_pC2 = NULL; return 4; } void DelocateCubeSets() { } /////////////////////////////////////////////////////////////////// /// Insertion Operators /// /////////////////////////////////////////////////////////////////// void CubeInsert( Cube* p ) // inserts the cube into storage (puts it at the beginning of the list) { assert( p->Prev == NULL && p->Next == NULL ); assert( p->ID ); if ( s_List == NULL ) s_List = p; else { p->Next = s_List; s_List->Prev = p; s_List = p; } g_CoverInfo.nCubesInUse++; } Cube* CubeExtract( Cube* p ) // extracts the cube from storage { // assert( p->Prev && p->Next ); // can be done only with rings assert( p->ID ); // if ( s_List == p ) // s_List = p->Next; // if ( p->Prev ) // p->Prev->Next = p->Next; if ( s_List == p ) s_List = p->Next; else p->Prev->Next = p->Next; if ( p->Next ) p->Next->Prev = p->Prev; p->Prev = NULL; p->Next = NULL; g_CoverInfo.nCubesInUse--; return p; } /////////////////////////////////////////////////////////////////// /// CUBE ITERATOR /// /////////////////////////////////////////////////////////////////// // the iterator starts from the Head and stops when it sees NULL Cube* s_pCubeLast; /////////////////////////////////////////////////////////////////// /// Cube Set Iterator /// /////////////////////////////////////////////////////////////////// Cube* IterCubeSetStart() // starts an iterator that traverses all the cubes in the ring { assert( s_pCubeLast == NULL ); // check whether the List has cubes if ( s_List == NULL ) return NULL; return ( s_pCubeLast = s_List ); } Cube* IterCubeSetNext() // returns the next cube in the cube set // to use it again after it has returned NULL, first call IterCubeSetStart() { assert( s_pCubeLast ); return ( s_pCubeLast = s_pCubeLast->Next ); } /////////////////////////////////////////////////////////////////// //// ADJACENCY QUEQUES ////// /////////////////////////////////////////////////////////////////// typedef struct { Cube** pC1; // the pointer to the first cube Cube** pC2; // the pointer to the second cube byte* ID1; // the ID of the first cube byte* ID2; // the ID of the second cube int PosOut; // extract position int PosIn; // insert position int PosCur; // temporary insert position int PosMark; // the marked position int fEmpty; // this flag is 1 if there is nothing in the queque } que; static que s_Que[3]; // Dist-2, Dist-3, Dist-4 queques // the number of allocated places //int s_nPosAlloc; // the maximum number of occupied places //int s_nPosMax[3]; ////////////////////////////////////////////////////////////////////// // Conditional Adding Cube Pairs To Queques // ////////////////////////////////////////////////////////////////////// int GetPosDiff( int PosBeg, int PosEnd ) { return (PosEnd - PosBeg + s_nPosAlloc) % s_nPosAlloc; } void MarkSet() // sets marks in the cube pair queques { s_Que[0].PosMark = s_Que[0].PosIn; s_Que[1].PosMark = s_Que[1].PosIn; s_Que[2].PosMark = s_Que[2].PosIn; } void MarkRewind() // rewinds the queques to the previously set marks { s_Que[0].PosIn = s_Que[0].PosMark; s_Que[1].PosIn = s_Que[1].PosMark; s_Que[2].PosIn = s_Que[2].PosMark; } void NewRangeReset() // resets temporarily stored new range of cube pairs { s_Que[0].PosCur = s_Que[0].PosIn; s_Que[1].PosCur = s_Que[1].PosIn; s_Que[2].PosCur = s_Que[2].PosIn; } void NewRangeAdd() // adds temporarily stored new range of cube pairs to the queque { s_Que[0].PosIn = s_Que[0].PosCur; s_Que[1].PosIn = s_Que[1].PosCur; s_Que[2].PosIn = s_Que[2].PosCur; } void NewRangeInsertCubePair( cubedist Dist, Cube* p1, Cube* p2 ) // insert one cube pair into the new range { que* p = &s_Que[Dist]; int Pos = p->PosCur; if ( p->fEmpty || Pos != p->PosOut ) { p->pC1[Pos] = p1; p->pC2[Pos] = p2; p->ID1[Pos] = p1->ID; p->ID2[Pos] = p2->ID; p->PosCur = (p->PosCur+1)%s_nPosAlloc; } else assert(0); // cout << endl << "DIST-" << (int)(Dist+2) << ": Have run out of queque space!" << endl; } void PrintQuequeStats() { /* cout << endl << "Queque statistics: "; cout << " Alloc = " << s_nPosAlloc; cout << " DIST2 = " << GetPosDiff( s_Que[0].PosOut, s_Que[0].PosIn ); cout << " DIST3 = " << GetPosDiff( s_Que[1].PosOut, s_Que[1].PosIn ); cout << " DIST4 = " << GetPosDiff( s_Que[2].PosOut, s_Que[2].PosIn ); cout << endl; cout << endl; */ } int GetQuequeStats( cubedist Dist ) { return GetPosDiff( s_Que[Dist].PosOut, s_Que[Dist].PosIn ); } ////////////////////////////////////////////////////////////////////// // Queque Iterators // ////////////////////////////////////////////////////////////////////// // iterating through the queque (with authomatic garbage collection) // only one iterator can be active at a time static struct { int fStarted; // status of the iterator (1 if working) cubedist Dist; // the currently iterated queque Cube** ppC1; // the position where the first cube pointer goes Cube** ppC2; // the position where the second cube pointer goes int PosStop; // the stop position (to prevent the iterator from // choking when new pairs are added during iteration) int CutValue; // the number of literals below which the cubes are not used } s_Iter; static que* pQ; static Cube *p1, *p2; int IteratorCubePairStart( cubedist CubeDist, Cube** ppC1, Cube** ppC2 ) // start an iterator through cubes of dist CubeDist, // the resulting pointers are written into ppC1 and ppC2 // returns 1 if the first cube pair is found { int fEntryFound; assert( s_Iter.fStarted == 0 ); assert( CubeDist >= 0 && CubeDist <= 2 ); s_Iter.fStarted = 1; s_Iter.Dist = CubeDist; s_Iter.ppC1 = ppC1; s_Iter.ppC2 = ppC2; s_Iter.PosStop = s_Que[ CubeDist ].PosIn; // determine the cut value // s_Iter.CutValue = s_nLiteralsInUse/s_nCubesInUse/2; s_Iter.CutValue = -1; fEntryFound = 0; // go through the entries while there is something in the queque for ( pQ = &s_Que[ CubeDist ]; pQ->PosOut != s_Iter.PosStop; pQ->PosOut = (pQ->PosOut+1)%s_nPosAlloc ) { p1 = pQ->pC1[ pQ->PosOut ]; p2 = pQ->pC2[ pQ->PosOut ]; // check whether the entry is valid if ( p1->ID == pQ->ID1[ pQ->PosOut ] && p2->ID == pQ->ID2[ pQ->PosOut ] ) //&& //p1->x + p1->y + p2->x + p2->y > s_Iter.CutValue ) { fEntryFound = 1; break; } } if ( fEntryFound ) { // write the result into the pick-up place *ppC1 = pQ->pC1[ pQ->PosOut ]; *ppC2 = pQ->pC2[ pQ->PosOut ]; pQ->PosOut = (pQ->PosOut+1)%s_nPosAlloc; } else s_Iter.fStarted = 0; return fEntryFound; } int IteratorCubePairNext() // gives the next VALID cube pair (the previous one is automatically dequequed) { int fEntryFound = 0; assert( s_Iter.fStarted ); // go through the entries while there is something in the queque for ( pQ = &s_Que[ s_Iter.Dist ]; pQ->PosOut != s_Iter.PosStop; pQ->PosOut = (pQ->PosOut+1)%s_nPosAlloc ) { p1 = pQ->pC1[ pQ->PosOut ]; p2 = pQ->pC2[ pQ->PosOut ]; // check whether the entry is valid if ( p1->ID == pQ->ID1[ pQ->PosOut ] && p2->ID == pQ->ID2[ pQ->PosOut ] ) //&& //p1->x + p1->y + p2->x + p2->y > s_Iter.CutValue ) { fEntryFound = 1; break; } } if ( fEntryFound ) { // write the result into the pick-up place *(s_Iter.ppC1) = pQ->pC1[ pQ->PosOut ]; *(s_Iter.ppC2) = pQ->pC2[ pQ->PosOut ]; pQ->PosOut = (pQ->PosOut+1)%s_nPosAlloc; } else // iteration has finished s_Iter.fStarted = 0; return fEntryFound; } ////////////////////////////////////////////////////////////////////// // Allocation/Delocation // ////////////////////////////////////////////////////////////////////// int AllocateQueques( int nPlaces ) // nPlaces should be approximately nCubes*nCubes/10 // allocates memory for cube pair queques { int i; s_nPosAlloc = nPlaces; for ( i = 0; i < 3; i++ ) { // clean data memset( &s_Que[i], 0, sizeof(que) ); s_Que[i].pC1 = (Cube**) ABC_ALLOC( Cube*, nPlaces ); s_Que[i].pC2 = (Cube**) ABC_ALLOC( Cube*, nPlaces ); s_Que[i].ID1 = (byte*) ABC_ALLOC( byte, nPlaces ); s_Que[i].ID2 = (byte*) ABC_ALLOC( byte, nPlaces ); if ( s_Que[i].pC1==NULL || s_Que[i].pC2==NULL || s_Que[i].ID1==NULL || s_Que[i].ID2==NULL ) return 0; s_nPosMax[i] = 0; s_Que[i].fEmpty = 1; } return nPlaces * (sizeof(Cube*) + sizeof(Cube*) + 2*sizeof(byte) ); } void DelocateQueques() { int i; for ( i = 0; i < 3; i++ ) { ABC_FREE( s_Que[i].pC1 ); ABC_FREE( s_Que[i].pC2 ); ABC_FREE( s_Que[i].ID1 ); ABC_FREE( s_Que[i].ID2 ); } } /////////////////////////////////////////////////////////////////// //////////// End of File ///////////////// /////////////////////////////////////////////////////////////////// }
412
0.986181
1
0.986181
game-dev
MEDIA
0.147142
game-dev
0.655978
1
0.655978
Rosewood-Development/PlayerParticles
19,557
src/main/java/dev/esophose/playerparticles/manager/PermissionManager.java
package dev.esophose.playerparticles.manager; import dev.esophose.playerparticles.config.Settings; import dev.esophose.playerparticles.particles.OtherPPlayer; import dev.esophose.playerparticles.particles.PPlayer; import dev.esophose.playerparticles.particles.ParticleEffect; import dev.esophose.playerparticles.styles.ParticleStyle; import dev.rosewood.rosegarden.RosePlugin; import dev.rosewood.rosegarden.manager.Manager; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; import org.bukkit.permissions.Permissible; import org.bukkit.permissions.Permission; import org.bukkit.permissions.PermissionAttachmentInfo; import org.bukkit.plugin.PluginManager; public class PermissionManager extends Manager { private static final String PERMISSION_PREFIX = "playerparticles."; private enum PPermission { EFFECT("effect"), STYLE("style"), FIXED("fixed"), FIXED_MAX("fixed.max"), FIXED_UNLIMITED("fixed.unlimited"), FIXED_CLEAR("fixed.clear"), FIXED_TELEPORT("fixed.teleport"), RELOAD("reload"), OVERRIDE("override"), RESET_OTHERS("reset.others"), GUI("gui"), PARTICLES_MAX("particles.max"), PARTICLES_UNLIMITED("particles.unlimited"), GROUPS_MAX("groups.max"), GROUPS_UNLIMITED("groups.unlimited"), WORLDGUARD_BYPASS("worldguard.bypass"); private final String permissionString; PPermission(String permissionString) { this.permissionString = permissionString; } /** * Checks if a Permissible has a PlayerParticles permission * * @param p The Permissible * @return True if the Player has permission */ public boolean check(Permissible p) { String permission = PERMISSION_PREFIX + this.permissionString; return p.hasPermission(permission); } /** * Checks if a Permissible has a PlayerParticles permission with a sub-permission * * @param p The Permissible * @param subPermission The sub-permission * @return True if the Player has permission */ public boolean check(Permissible p, String subPermission) { String permission = PERMISSION_PREFIX + this.permissionString + '.' + subPermission; return p.hasPermission(permission); } @Override public String toString() { return PERMISSION_PREFIX + this.permissionString; } } public PermissionManager(RosePlugin playerParticles) { super(playerParticles); playerParticles.getScheduler().runTaskLater(() -> { try { // Register plugin permissions to Bukkit PluginManager pluginManager = Bukkit.getPluginManager(); Set<Permission> allPermissions = new HashSet<>(); // Effects Map<String, Boolean> effectPermissions = new HashMap<>(); for (ParticleEffect effect : ParticleEffect.values()) { if (!effect.isSupported()) continue; Permission permission = new Permission("playerparticles.effect." + effect.getInternalName()); pluginManager.addPermission(permission); effectPermissions.put(permission.getName(), true); } // Effects Wildcard allPermissions.add(new Permission("playerparticles.effect.*", effectPermissions)); // Styles Map<String, Boolean> stylePermissions = new HashMap<>(); for (ParticleStyle style : playerParticles.getManager(ParticleStyleManager.class).getStylesWithDisabled()) { Permission permission = new Permission("playerparticles.style." + style.getInternalName()); pluginManager.addPermission(permission); stylePermissions.put(permission.getName(), true); } // Styles Wildcard allPermissions.add(new Permission("playerparticles.style.*", stylePermissions)); // Fixed pluginManager.addPermission(new Permission("playerparticles.fixed")); pluginManager.addPermission(new Permission("playerparticles.fixed.max")); pluginManager.addPermission(new Permission("playerparticles.fixed.unlimited")); pluginManager.addPermission(new Permission("playerparticles.fixed.clear")); pluginManager.addPermission(new Permission("playerparticles.fixed.teleport")); // Misc pluginManager.addPermission(new Permission("playerparticles.reload")); pluginManager.addPermission(new Permission("playerparticles.override")); pluginManager.addPermission(new Permission("playerparticles.reset.others")); pluginManager.addPermission(new Permission("playerparticles.gui")); pluginManager.addPermission(new Permission("playerparticles.particles.max")); pluginManager.addPermission(new Permission("playerparticles.particles.unlimited")); pluginManager.addPermission(new Permission("playerparticles.groups.max")); pluginManager.addPermission(new Permission("playerparticles.groups.unlimited")); pluginManager.addPermission(new Permission("playerparticles.worldguard.bypass")); // Register all non-child permissions Map<String, Boolean> childPermissions = new HashMap<>(); for (Permission permission : allPermissions) { pluginManager.addPermission(permission); childPermissions.put(permission.getName(), true); } // Register all permissions as a child to the global plugin permission pluginManager.addPermission(new Permission("playerparticles.*", childPermissions)); } catch (Exception e) { playerParticles.getLogger().warning("Failed to register permissions dynamically. Did you load PlayerParticles through means other than a restart or reload?"); } }, 2L); } @Override public void reload() { } @Override public void disable() { } /** * Checks if the given player has the given permission * * @param pplayer The player to check * @param permission The permission to check * @return true if the player has the permission, otherwise false */ public boolean hasPermission(PPlayer pplayer, String permission) { return pplayer.getUnderlyingExecutor().hasPermission(permission); } /** * Checks if the given player has reached the max number of particles in their active group * * @param pplayer The player to check * @return If the player has reached the max number of particles in their active group */ public boolean hasPlayerReachedMaxParticles(PPlayer pplayer) { if (PPermission.PARTICLES_UNLIMITED.check(pplayer.getUnderlyingExecutor())) return false; PPlayer executor = this.getUnderlyingExecutorAsPPlayer(pplayer); if (executor != pplayer) return false; return pplayer.getActiveParticles().size() >= this.getPermissionAmount(pplayer.getUnderlyingExecutor(), PPermission.PARTICLES_MAX, Settings.MAX_PARTICLES.get()); } /** * Checks if the given player has reached the max number of saved particle groups * * @param pplayer The player to check * @return If the player has reached the max number of saved particle groups */ public boolean hasPlayerReachedMaxGroups(PPlayer pplayer) { if (PPermission.GROUPS_UNLIMITED.check(pplayer.getUnderlyingExecutor())) return false; PPlayer executor = this.getUnderlyingExecutorAsPPlayer(pplayer); if (executor != pplayer) return false; return executor.getParticleGroups().size() - 1 >= this.getPermissionAmount(pplayer.getUnderlyingExecutor(), PPermission.GROUPS_MAX, Settings.MAX_GROUPS.get()); } /** * Checks if the given player is able to save groups * * @param pplayer The player to check * @return If the player has permission to save groups */ public boolean canPlayerSaveGroups(PPlayer pplayer) { if (PPermission.GROUPS_UNLIMITED.check(pplayer.getUnderlyingExecutor())) return true; return this.getPermissionAmount(pplayer.getUnderlyingExecutor(), PPermission.GROUPS_MAX, Settings.MAX_GROUPS.get()) != 0; } /** * Checks if the given player has reached the max number of fixed effects * * @param pplayer The player to check * @return If the player has reached the max number of fixed effects */ public boolean hasPlayerReachedMaxFixedEffects(PPlayer pplayer) { if (PPermission.FIXED_UNLIMITED.check(pplayer.getUnderlyingExecutor())) return false; PPlayer executor = this.getUnderlyingExecutorAsPPlayer(pplayer); if (executor != pplayer) return false; return pplayer.getFixedEffectIds().size() >= this.getPermissionAmount(pplayer.getUnderlyingExecutor(), PPermission.FIXED_MAX, Settings.MAX_FIXED_EFFECTS.get()); } /** * Gets the max distance a fixed effect can be created from the player * * @return The max distance a fixed effect can be created from the player */ public int getMaxFixedEffectCreationDistance() { return Settings.MAX_FIXED_EFFECT_CREATION_DISTANCE.get(); } /** * Gets the maximum number of particles a player is allowed to use * * @param pplayer The pplayer to check * @return The maximum number of particles based on the config.yml value, or unlimited */ public int getMaxParticlesAllowed(PPlayer pplayer) { if (PPermission.PARTICLES_UNLIMITED.check(pplayer.getUnderlyingExecutor())) return Integer.MAX_VALUE; PPlayer executor = this.getUnderlyingExecutorAsPPlayer(pplayer); if (executor != pplayer) return Integer.MAX_VALUE; return this.getPermissionAmount(pplayer.getUnderlyingExecutor(), PPermission.PARTICLES_MAX, Settings.MAX_PARTICLES.get()); } /** * Checks if a world is enabled for particles to spawn in * * @param world The world name to check * @return True if the world is disabled */ public boolean isWorldEnabled(String world) { return !this.getDisabledWorlds().contains(world); } /** * Gets all the worlds that are disabled * * @return All world names that are disabled */ public List<String> getDisabledWorlds() { return Settings.DISABLED_WORLDS.get(); } /** * Checks if a player can reset another offline player's particles * * @param player The player to check the permission for * @return True if the player has permission, otherwise false */ public boolean canResetOthers(PPlayer player) { return PPermission.RESET_OTHERS.check(player.getUnderlyingExecutor()); } /** * Checks if a player has permission to use an effect * * @param player The player to check the permission for * @param effect The effect to check * @return True if the player has permission to use the effect */ public boolean hasEffectPermission(PPlayer player, ParticleEffect effect) { return PPermission.EFFECT.check(player.getUnderlyingExecutor(), effect.getInternalName()); } /** * Checks if a player has permission to use a style * Always returns true for 'normal', a player needs at least one style to apply particles * * @param player The player to check the permission for * @param style The style to check * @return If the player has permission to use the style */ public boolean hasStylePermission(PPlayer player, ParticleStyle style) { return PPermission.STYLE.check(player.getUnderlyingExecutor(), style.getInternalName()); } /** * Gets a String List of all effect names a player has permission for * * @param p The player to get effect names for * @return A String List of all effect names the given player has permission for */ public List<String> getEffectNamesUserHasPermissionFor(PPlayer p) { List<String> list = new ArrayList<>(); for (ParticleEffect pe : ParticleEffect.getEnabledEffects()) if (this.hasEffectPermission(p, pe)) list.add(pe.getName()); return list; } /** * Gets a String List of all style names a player has permission for * * @param p The player to get style names for * @return A String List of all style names the given player has permission for */ public List<String> getStyleNamesUserHasPermissionFor(PPlayer p) { List<String> list = new ArrayList<>(); for (ParticleStyle ps : this.rosePlugin.getManager(ParticleStyleManager.class).getStyles()) if (this.hasStylePermission(p, ps)) list.add(ps.getName()); return list; } /** * Gets a String List of all fixable style names a player has permission for * * @param p The player to get style names for * @return A String List of all fixable style names the given player has permission for */ public List<String> getFixableStyleNamesUserHasPermissionFor(PPlayer p) { List<String> list = new ArrayList<>(); for (ParticleStyle ps : this.rosePlugin.getManager(ParticleStyleManager.class).getStyles()) if (ps.canBeFixed() && this.hasStylePermission(p, ps)) list.add(ps.getName()); return list; } /** * Gets a List of all effects a player has permission for * * @param p The player to get effects for * @return A List of all effects the given player has permission for */ public List<ParticleEffect> getEffectsUserHasPermissionFor(PPlayer p) { List<ParticleEffect> list = new ArrayList<>(); for (ParticleEffect pe : ParticleEffect.getEnabledEffects()) if (this.hasEffectPermission(p, pe)) list.add(pe); return list; } /** * Gets a List of all styles a player has permission for * * @param p The player to get styles for * @return A List of all styles the given player has permission for */ public List<ParticleStyle> getStylesUserHasPermissionFor(PPlayer p) { List<ParticleStyle> list = new ArrayList<>(); for (ParticleStyle ps : this.rosePlugin.getManager(ParticleStyleManager.class).getStyles()) if (this.hasStylePermission(p, ps)) list.add(ps); return list; } /** * Checks if a player has permission to created fixed effects * * @param player The player to check the permission for * @return True if the player has permission */ public boolean canUseFixedEffects(PPlayer player) { return PPermission.FIXED.check(player.getUnderlyingExecutor()); } /** * Checks if a player has permission to clear fixed effects * * @param player The player to check the permission for * @return True if the player has permission to use /pp fixed clear */ public boolean canClearFixedEffects(PPlayer player) { return PPermission.FIXED_CLEAR.check(player.getUnderlyingExecutor()); } /** * Checks if a player has permission to teleport to fixed effects * * @param player The player to check the permission for * @return True if the player has permission to use /pp fixed teleport */ public boolean canTeleportToFixedEffects(PPlayer player) { return PPermission.FIXED_TELEPORT.check(player.getUnderlyingExecutor()); } /** * Checks if a player has permission to open the GUI * * @param player The player to check the permission for * @return True if the player has permission to open the GUI */ public boolean canOpenGui(PPlayer player) { return !Settings.GUI_REQUIRE_PERMISSION.get() || PPermission.GUI.check(player.getUnderlyingExecutor()); } /** * Checks if a player has permission to open a specific GUI * * @param player The player to check the permission for * @param gui The gui name * @return True if the player has permission to open the GUI */ public boolean canOpenGui(PPlayer player, String gui) { return !Settings.GUI_REQUIRE_PERMISSION.get() || PPermission.GUI.check(player.getUnderlyingExecutor(), gui); } /** * Checks if a player has permission to use /pp reload * * @param sender The sender to check the permission for * @return True if the sender has permission to reload the plugin's settings */ public boolean canReloadPlugin(CommandSender sender) { return PPermission.RELOAD.check(sender); } /** * Checks if a player can use /ppo * * @param sender The CommandSender to check * @return If the sender can use /ppo */ public boolean canOverride(CommandSender sender) { if (this.isConsole(sender)) return true; return PPermission.OVERRIDE.check(sender); } /** * Checks if a player has the WorldGuard bypass permission * * @param player The Player to check * @return If the player has the WorldGuard bypass permission */ public boolean hasWorldGuardBypass(Player player) { return PPermission.WORLDGUARD_BYPASS.check(player); } private boolean isConsole(PPlayer pplayer) { return this.isConsole(pplayer.getUnderlyingExecutor()); } private boolean isConsole(CommandSender sender) { return sender instanceof ConsoleCommandSender; } private PPlayer getUnderlyingExecutorAsPPlayer(PPlayer pplayer) { if (pplayer instanceof OtherPPlayer) { OtherPPlayer other = (OtherPPlayer) pplayer; CommandSender executor = other.getUnderlyingExecutor(); if (this.isConsole(executor)) return null; Player executingPlayer = (Player) executor; return this.rosePlugin.getManager(DataManager.class).getPPlayer(executingPlayer.getUniqueId()); } return pplayer; } private int getPermissionAmount(Permissible permissible, PPermission permission, int lowerBound) { int amount = lowerBound; for (PermissionAttachmentInfo info : permissible.getEffectivePermissions()) { String target = info.getPermission().toLowerCase(); if (target.startsWith(permission.toString()) && info.getValue()) { try { amount = Math.max(amount, Integer.parseInt(target.substring(target.lastIndexOf('.') + 1))); } catch (NumberFormatException ignored) { } } } return amount; } }
412
0.886999
1
0.886999
game-dev
MEDIA
0.944426
game-dev
0.891961
1
0.891961
thegatesbrowser/thegates-old
14,031
modules/multiplayer/multiplayer_spawner.cpp
/**************************************************************************/ /* multiplayer_spawner.cpp */ /**************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /**************************************************************************/ /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /**************************************************************************/ #include "multiplayer_spawner.h" #include "core/io/marshalls.h" #include "scene/main/multiplayer_api.h" #include "scene/main/window.h" #include "scene/scene_string_names.h" #ifdef TOOLS_ENABLED /* This is editor only */ bool MultiplayerSpawner::_set(const StringName &p_name, const Variant &p_value) { if (p_name == "_spawnable_scene_count") { spawnable_scenes.resize(p_value); notify_property_list_changed(); return true; } else { String ns = p_name; if (ns.begins_with("scenes/")) { uint32_t index = ns.get_slicec('/', 1).to_int(); ERR_FAIL_UNSIGNED_INDEX_V(index, spawnable_scenes.size(), false); spawnable_scenes[index].path = p_value; return true; } } return false; } bool MultiplayerSpawner::_get(const StringName &p_name, Variant &r_ret) const { if (p_name == "_spawnable_scene_count") { r_ret = spawnable_scenes.size(); return true; } else { String ns = p_name; if (ns.begins_with("scenes/")) { uint32_t index = ns.get_slicec('/', 1).to_int(); ERR_FAIL_UNSIGNED_INDEX_V(index, spawnable_scenes.size(), false); r_ret = spawnable_scenes[index].path; return true; } } return false; } void MultiplayerSpawner::_get_property_list(List<PropertyInfo> *p_list) const { p_list->push_back(PropertyInfo(Variant::INT, "_spawnable_scene_count", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_ARRAY, "Auto Spawn List,scenes/")); List<String> exts; ResourceLoader::get_recognized_extensions_for_type("PackedScene", &exts); String ext_hint; for (const String &E : exts) { if (!ext_hint.is_empty()) { ext_hint += ","; } ext_hint += "*." + E; } for (uint32_t i = 0; i < spawnable_scenes.size(); i++) { p_list->push_back(PropertyInfo(Variant::STRING, "scenes/" + itos(i), PROPERTY_HINT_FILE, ext_hint, PROPERTY_USAGE_EDITOR)); } } #endif PackedStringArray MultiplayerSpawner::get_configuration_warnings() const { PackedStringArray warnings = Node::get_configuration_warnings(); if (spawn_path.is_empty() || !has_node(spawn_path)) { warnings.push_back(RTR("A valid NodePath must be set in the \"Spawn Path\" property in order for MultiplayerSpawner to be able to spawn Nodes.")); } return warnings; } void MultiplayerSpawner::add_spawnable_scene(const String &p_path) { SpawnableScene sc; sc.path = p_path; if (Engine::get_singleton()->is_editor_hint()) { ERR_FAIL_COND(!FileAccess::exists(p_path)); } spawnable_scenes.push_back(sc); #ifdef TOOLS_ENABLED if (Engine::get_singleton()->is_editor_hint()) { return; } #endif Node *node = get_spawn_node(); if (spawnable_scenes.size() == 1 && node && !node->is_connected("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added))) { node->connect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added)); } } int MultiplayerSpawner::get_spawnable_scene_count() const { return spawnable_scenes.size(); } String MultiplayerSpawner::get_spawnable_scene(int p_idx) const { ERR_FAIL_INDEX_V(p_idx, (int)spawnable_scenes.size(), ""); return spawnable_scenes[p_idx].path; } void MultiplayerSpawner::clear_spawnable_scenes() { spawnable_scenes.clear(); #ifdef TOOLS_ENABLED if (Engine::get_singleton()->is_editor_hint()) { return; } #endif Node *node = get_spawn_node(); if (node && node->is_connected("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added))) { node->disconnect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added)); } } Vector<String> MultiplayerSpawner::_get_spawnable_scenes() const { Vector<String> ss; ss.resize(spawnable_scenes.size()); for (int i = 0; i < ss.size(); i++) { ss.write[i] = spawnable_scenes[i].path; } return ss; } void MultiplayerSpawner::_set_spawnable_scenes(const Vector<String> &p_scenes) { clear_spawnable_scenes(); for (int i = 0; i < p_scenes.size(); i++) { add_spawnable_scene(p_scenes[i]); } } void MultiplayerSpawner::_bind_methods() { ClassDB::bind_method(D_METHOD("add_spawnable_scene", "path"), &MultiplayerSpawner::add_spawnable_scene); ClassDB::bind_method(D_METHOD("get_spawnable_scene_count"), &MultiplayerSpawner::get_spawnable_scene_count); ClassDB::bind_method(D_METHOD("get_spawnable_scene", "index"), &MultiplayerSpawner::get_spawnable_scene); ClassDB::bind_method(D_METHOD("clear_spawnable_scenes"), &MultiplayerSpawner::clear_spawnable_scenes); ClassDB::bind_method(D_METHOD("_get_spawnable_scenes"), &MultiplayerSpawner::_get_spawnable_scenes); ClassDB::bind_method(D_METHOD("_set_spawnable_scenes", "scenes"), &MultiplayerSpawner::_set_spawnable_scenes); ADD_PROPERTY(PropertyInfo(Variant::PACKED_STRING_ARRAY, "_spawnable_scenes", PROPERTY_HINT_NONE, "", (PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL)), "_set_spawnable_scenes", "_get_spawnable_scenes"); ClassDB::bind_method(D_METHOD("spawn", "data"), &MultiplayerSpawner::spawn, DEFVAL(Variant())); ClassDB::bind_method(D_METHOD("get_spawn_path"), &MultiplayerSpawner::get_spawn_path); ClassDB::bind_method(D_METHOD("set_spawn_path", "path"), &MultiplayerSpawner::set_spawn_path); ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "spawn_path", PROPERTY_HINT_NONE, ""), "set_spawn_path", "get_spawn_path"); ClassDB::bind_method(D_METHOD("get_spawn_limit"), &MultiplayerSpawner::get_spawn_limit); ClassDB::bind_method(D_METHOD("set_spawn_limit", "limit"), &MultiplayerSpawner::set_spawn_limit); ADD_PROPERTY(PropertyInfo(Variant::INT, "spawn_limit", PROPERTY_HINT_RANGE, "0,1024,1,or_greater"), "set_spawn_limit", "get_spawn_limit"); ClassDB::bind_method(D_METHOD("get_spawn_function"), &MultiplayerSpawner::get_spawn_function); ClassDB::bind_method(D_METHOD("set_spawn_function", "spawn_function"), &MultiplayerSpawner::set_spawn_function); ADD_PROPERTY(PropertyInfo(Variant::CALLABLE, "spawn_function", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE), "set_spawn_function", "get_spawn_function"); ADD_SIGNAL(MethodInfo("despawned", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node"))); ADD_SIGNAL(MethodInfo("spawned", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node"))); } void MultiplayerSpawner::_update_spawn_node() { #ifdef TOOLS_ENABLED if (Engine::get_singleton()->is_editor_hint()) { return; } #endif if (spawn_node.is_valid()) { Node *node = Object::cast_to<Node>(ObjectDB::get_instance(spawn_node)); if (node && node->is_connected("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added))) { node->disconnect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added)); } } Node *node = spawn_path.is_empty() && is_inside_tree() ? nullptr : get_node_or_null(spawn_path); if (node) { spawn_node = node->get_instance_id(); if (get_spawnable_scene_count()) { node->connect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added)); } } else { spawn_node = ObjectID(); } } void MultiplayerSpawner::_notification(int p_what) { switch (p_what) { case NOTIFICATION_POST_ENTER_TREE: { _update_spawn_node(); } break; case NOTIFICATION_EXIT_TREE: { _update_spawn_node(); for (const KeyValue<ObjectID, SpawnInfo> &E : tracked_nodes) { Node *node = Object::cast_to<Node>(ObjectDB::get_instance(E.key)); ERR_CONTINUE(!node); node->disconnect(SceneStringNames::get_singleton()->tree_exiting, callable_mp(this, &MultiplayerSpawner::_node_exit)); get_multiplayer()->object_configuration_remove(node, this); } tracked_nodes.clear(); } break; } } void MultiplayerSpawner::_node_added(Node *p_node) { if (!get_multiplayer()->has_multiplayer_peer() || !is_multiplayer_authority()) { return; } if (tracked_nodes.has(p_node->get_instance_id())) { return; } const Node *parent = get_spawn_node(); if (!parent || p_node->get_parent() != parent) { return; } int id = find_spawnable_scene_index_from_path(p_node->get_scene_file_path()); if (id == INVALID_ID) { return; } const String name = p_node->get_name(); ERR_FAIL_COND_MSG(name.validate_node_name() != name, vformat("Unable to auto-spawn node with reserved name: %s. Make sure to add your replicated scenes via 'add_child(node, true)' to produce valid names.", name)); _track(p_node, Variant(), id); } NodePath MultiplayerSpawner::get_spawn_path() const { return spawn_path; } void MultiplayerSpawner::set_spawn_path(const NodePath &p_path) { spawn_path = p_path; _update_spawn_node(); } void MultiplayerSpawner::_track(Node *p_node, const Variant &p_argument, int p_scene_id) { ObjectID oid = p_node->get_instance_id(); if (!tracked_nodes.has(oid)) { tracked_nodes[oid] = SpawnInfo(p_argument.duplicate(true), p_scene_id); p_node->connect(SceneStringNames::get_singleton()->tree_exiting, callable_mp(this, &MultiplayerSpawner::_node_exit).bind(p_node->get_instance_id()), CONNECT_ONE_SHOT); _spawn_notify(p_node->get_instance_id()); } } void MultiplayerSpawner::_spawn_notify(ObjectID p_id) { get_multiplayer()->object_configuration_add(ObjectDB::get_instance(p_id), this); } void MultiplayerSpawner::_node_exit(ObjectID p_id) { Node *node = Object::cast_to<Node>(ObjectDB::get_instance(p_id)); ERR_FAIL_NULL(node); if (tracked_nodes.has(p_id)) { tracked_nodes.erase(p_id); get_multiplayer()->object_configuration_remove(node, this); } } int MultiplayerSpawner::find_spawnable_scene_index_from_path(const String &p_scene) const { for (uint32_t i = 0; i < spawnable_scenes.size(); i++) { if (spawnable_scenes[i].path == p_scene) { return i; } } return INVALID_ID; } int MultiplayerSpawner::find_spawnable_scene_index_from_object(const ObjectID &p_id) const { const SpawnInfo *info = tracked_nodes.getptr(p_id); return info ? info->id : INVALID_ID; } const Variant MultiplayerSpawner::get_spawn_argument(const ObjectID &p_id) const { const SpawnInfo *info = tracked_nodes.getptr(p_id); return info ? info->args : Variant(); } Node *MultiplayerSpawner::instantiate_scene(int p_id) { ERR_FAIL_COND_V_MSG(spawn_limit && spawn_limit <= tracked_nodes.size(), nullptr, "Spawn limit reached!"); ERR_FAIL_UNSIGNED_INDEX_V((uint32_t)p_id, spawnable_scenes.size(), nullptr); SpawnableScene &sc = spawnable_scenes[p_id]; if (sc.cache.is_null()) { sc.cache = ResourceLoader::load(sc.path); } ERR_FAIL_COND_V_MSG(sc.cache.is_null(), nullptr, "Invalid spawnable scene: " + sc.path); return sc.cache->instantiate(); } Node *MultiplayerSpawner::instantiate_custom(const Variant &p_data) { ERR_FAIL_COND_V_MSG(spawn_limit && spawn_limit <= tracked_nodes.size(), nullptr, "Spawn limit reached!"); ERR_FAIL_COND_V_MSG(!spawn_function.is_valid(), nullptr, "Custom spawn requires a valid 'spawn_function'."); const Variant *argv[1] = { &p_data }; Variant ret; Callable::CallError ce; spawn_function.callp(argv, 1, ret, ce); ERR_FAIL_COND_V_MSG(ce.error != Callable::CallError::CALL_OK, nullptr, "Failed to call spawn function."); ERR_FAIL_COND_V_MSG(ret.get_type() != Variant::OBJECT, nullptr, "The spawn function must return a Node."); return Object::cast_to<Node>(ret.operator Object *()); } Node *MultiplayerSpawner::spawn(const Variant &p_data) { ERR_FAIL_COND_V(!is_inside_tree() || !get_multiplayer()->has_multiplayer_peer() || !is_multiplayer_authority(), nullptr); ERR_FAIL_COND_V_MSG(spawn_limit && spawn_limit <= tracked_nodes.size(), nullptr, "Spawn limit reached!"); ERR_FAIL_COND_V_MSG(!spawn_function.is_valid(), nullptr, "Custom spawn requires the 'spawn_function' property to be a valid callable."); Node *parent = get_spawn_node(); ERR_FAIL_NULL_V_MSG(parent, nullptr, "Cannot find spawn node."); Node *node = instantiate_custom(p_data); ERR_FAIL_NULL_V_MSG(node, nullptr, "The 'spawn_function' callable must return a valid node."); _track(node, p_data); parent->add_child(node, true); return node; }
412
0.91162
1
0.91162
game-dev
MEDIA
0.925642
game-dev
0.840199
1
0.840199
SAP/abap-cleaner
5,923
com.sap.adt.abapcleaner/src/com/sap/adt/abapcleaner/parser/Section.java
package com.sap.adt.abapcleaner.parser; import com.sap.adt.abapcleaner.base.Cult; import com.sap.adt.abapcleaner.programbase.*; /** * <p>A Section may either be a single {@link Command} or * any range of {@link Command}s that are (possibly remote) siblings.</p> * * <p>The Section's {@link #firstCommand} and {@link #lastCommand} are siblings; the {@link #lastCommand} is always childless. * Sections can be removed with {@link #removeFromCode()} * and inserted elsewhere with {@link Command#insertRightSibling(Section, boolean)}.</p> */ public class Section { public final Command firstCommand; public final Command lastCommand; public static Section create(Command firstCommand, Command lastCommand) throws UnexpectedSyntaxException { return new Section(firstCommand, lastCommand); } private Section(Command firstCommand, Command lastCommand) throws UnexpectedSyntaxException { if (firstCommand == null) throw new NullPointerException("firstCommand"); if (lastCommand == null) throw new NullPointerException("lastCommand"); this.firstCommand = firstCommand; this.lastCommand = lastCommand; if (lastCommand.hasChildren()) { throw new UnexpectedSyntaxException(this.lastCommand, "Command '" + this.lastCommand.firstToken.text + " ...' unexpected as last command of a Section, since it has child commands!"); } // firstCommand and lastCommand must be siblings Command command = this.firstCommand; while (command != this.lastCommand) { command = command.getNextSibling(); if (command == null) { throw new UnexpectedSyntaxException(this.lastCommand, "The first and last Command of a Section must be siblings, but " + "'" + firstCommand.firstToken.text + " ...' (line " + Cult.format(firstCommand.getSourceLineNumStart()) + ") and " + "'" + lastCommand.firstToken.text + " ...' (line " + Cult.format(lastCommand.getSourceLineNumStart()) + ") are not."); } } } public final boolean isSingleCommand() { return (firstCommand == lastCommand); } private Code getParentCode() { return firstCommand.getParentCode(); } final Command getParent() { return firstCommand.getParent(); } final void setParent(Command value) { Command command = firstCommand; command.setParent(value); while (command != lastCommand) { command = command.getNextSibling(); command.setParent(value); } } final Command getPrev() { return firstCommand.getPrev(); } final void setPrev(Command value) { firstCommand.setPrev(value); } final Command getNext() { return lastCommand.getNext(); } // lastCommand is sure to be childless final void setNext(Command value) { lastCommand.setNext(value); } final Command getPrevSibling() { return firstCommand.getPrevSibling(); } final void setPrevSibling(Command value) { firstCommand.setPrevSibling(value); } final Command getNextSibling() { return lastCommand.getNextSibling(); } final void setNextSibling(Command value) { lastCommand.setNextSibling(value); } final int getCommandCountWithChildren() { Command command = firstCommand; int result = 1; while (command != lastCommand) { command = command.getNext(); ++result; } return result; } final int getSiblingCount() { Command command = firstCommand; int result = 1; while (command != lastCommand) { command = command.getNextSibling(); ++result; } return result; } public final void removeFromCode() { if (getParentCode().firstCommand == firstCommand) getParentCode().firstCommand = getNext(); if (getParentCode().lastCommand == lastCommand) getParentCode().lastCommand = getPrev(); getParentCode().commandCount -= getCommandCountWithChildren(); if (getParent() != null) { if (getParent().getFirstChild() == firstCommand && getParent().getLastChild() == lastCommand) { getParent().setFirstChild(null); getParent().setLastChild(null); } else if (getParent().getFirstChild() == firstCommand) { getParent().setFirstChild(getNext()); } else if (getParent().getLastChild() == lastCommand) { getParent().setLastChild(getPrev()); } } if (getPrev() != null) getPrev().setNext(getNext()); if (getNext() != null) getNext().setPrev(getPrev()); if (getPrevSibling() != null) getPrevSibling().setNextSibling(getNextSibling()); if (getNextSibling() != null) getNextSibling().setPrevSibling(getPrevSibling()); } /** * adds the provided (and possibly negative) number of spaces to the indent of all lines covered by this Section; * returns true if whitespace was changed * * @param spaceCount */ public final boolean addIndent(int spaceCount) { if (spaceCount == 0) return false; boolean changed = false; Command command = firstCommand; do { Token token = command.firstToken; while (token != null) { if (token.lineBreaks > 0 && !token.isAsteriskCommentLine()) { token.spacesLeft = Math.max(token.spacesLeft + spaceCount, 0); changed = true; } token = token.getNext(); } if (command == lastCommand) break; command = command.getNext(); } while (command != null); return changed; } @Override public String toString() { StringBuilder result = new StringBuilder(); Command command = firstCommand; result.append(command.toString()); while (command != lastCommand) { command = command.getNext(); result.append(command.toString()); } return result.toString(); } void setParentCode(Code parentCode) { Command command = firstCommand; do { command.setParentCode(parentCode); if (command == lastCommand) break; command = command.getNext(); } while (command != null); } public boolean contains(Command searchCommand) { Command command = firstCommand; do { if (command == searchCommand) return true; if (command == lastCommand) break; command = command.getNext(); } while (command != null); return false; } }
412
0.841654
1
0.841654
game-dev
MEDIA
0.427469
game-dev
0.814361
1
0.814361
magefree/mage
3,827
Mage.Sets/src/mage/cards/d/DebtToTheKami.java
package mage.cards.d; import java.util.UUID; import mage.abilities.Ability; import mage.abilities.Mode; import mage.abilities.effects.OneShotEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Outcome; import mage.constants.Zone; import mage.filter.common.FilterControlledPermanent; import mage.game.Game; import mage.game.permanent.Permanent; import mage.players.Player; import mage.target.Target; import mage.target.common.TargetControlledCreaturePermanent; import mage.target.common.TargetControlledPermanent; import mage.target.common.TargetOpponent; /** * * @author weirddan455 */ public final class DebtToTheKami extends CardImpl { public DebtToTheKami(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{2}{B}"); // Choose one— // • Target opponent exiles a creature they control. this.getSpellAbility().addEffect(new DebtToTheKamiExileCreatureEffect()); this.getSpellAbility().addTarget(new TargetOpponent()); // • Target opponent exiles an enchantment they control. Mode mode = new Mode(new DebtToTheKamiExileEnchantmentEffect()); mode.addTarget(new TargetOpponent()); this.getSpellAbility().addMode(mode); } private DebtToTheKami(final DebtToTheKami card) { super(card); } @Override public DebtToTheKami copy() { return new DebtToTheKami(this); } } class DebtToTheKamiExileCreatureEffect extends OneShotEffect { DebtToTheKamiExileCreatureEffect() { super(Outcome.Exile); this.staticText = "Target opponent exiles a creature they control"; } private DebtToTheKamiExileCreatureEffect(final DebtToTheKamiExileCreatureEffect effect) { super(effect); } @Override public DebtToTheKamiExileCreatureEffect copy() { return new DebtToTheKamiExileCreatureEffect(this); } @Override public boolean apply(Game game, Ability source) { Player player = game.getPlayer(source.getFirstTarget()); if (player == null) { return false; } Target target = new TargetControlledCreaturePermanent(); target.withNotTarget(true); player.choose(outcome, target, source, game); Permanent permanent = game.getPermanent(target.getFirstTarget()); if (permanent == null) { return false; } return player.moveCards(permanent, Zone.EXILED, source, game); } } class DebtToTheKamiExileEnchantmentEffect extends OneShotEffect { private static final FilterControlledPermanent filter = new FilterControlledPermanent("enchantment you control"); static { filter.add(CardType.ENCHANTMENT.getPredicate()); } public DebtToTheKamiExileEnchantmentEffect() { super(Outcome.Exile); this.staticText = "Target opponent exiles an enchantment they control"; } private DebtToTheKamiExileEnchantmentEffect(final DebtToTheKamiExileEnchantmentEffect effect) { super(effect); } @Override public DebtToTheKamiExileEnchantmentEffect copy() { return new DebtToTheKamiExileEnchantmentEffect(this); } @Override public boolean apply(Game game, Ability source) { Player player = game.getPlayer(source.getFirstTarget()); if (player == null) { return false; } Target target = new TargetControlledPermanent(filter); target.withNotTarget(true); player.choose(outcome, target, source, game); Permanent permanent = game.getPermanent(target.getFirstTarget()); if (permanent == null) { return false; } return player.moveCards(permanent, Zone.EXILED, source, game); } }
412
0.981591
1
0.981591
game-dev
MEDIA
0.978168
game-dev
0.995895
1
0.995895
Qowyn/ark-tools
22,115
src/main/java/qowyn/ark/tools/data/Creature.java
package qowyn.ark.tools.data; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.SortedMap; import java.util.TreeMap; import com.fasterxml.jackson.core.JsonGenerator; import qowyn.ark.GameObject; import qowyn.ark.GameObjectContainer; import qowyn.ark.arrays.ArkArrayStruct; import qowyn.ark.structs.StructPropertyList; import qowyn.ark.tools.CreatureData; import qowyn.ark.tools.DataManager; import qowyn.ark.types.ArkByteValue; import qowyn.ark.types.ArkName; import qowyn.ark.types.LocationData; import qowyn.ark.types.ObjectReference; public class Creature { public static final int COLOR_SLOT_COUNT = 6; public ArkName className; public String type; public LocationData location; public long dinoId; public boolean tamed; public int targetingTeam; public int owningPlayerId; public boolean isFemale; public final byte colorSetIndices[] = new byte[COLOR_SLOT_COUNT]; public double tamedAtTime; public String tribeName; public String tamerString; public String owningPlayerName; public String tamedName; public String imprinterName; public final ArrayList<AncestorLineEntry> femaleAncestors = new ArrayList<>(); public final ArrayList<AncestorLineEntry> maleAncestors = new ArrayList<>(); public int baseCharacterLevel; public final byte[] numberOfLevelUpPointsApplied = new byte[AttributeNames.size()]; public short extraCharacterLevel; public final byte[] numberOfLevelUpPointsAppliedTamed = new byte[AttributeNames.size()]; public boolean allowLevelUps; public float experiencePoints; public float dinoImprintingQuality; public float wildRandomScale; public boolean isWakingTame; public boolean isSleeping; public float requiredTameAffinity; public float currentTameAffinity; public float tamedIneffectivenessModifier; public int tamedFollowTarget; public int tamingTeamID; public String tamedOnServerName; public String uploadedFromServerName; public int tamedAggressionLevel; public float matingProgress; public double lastEnterStasisTime; public GameObject status; public GameObject inventory; public Creature(GameObject creature, GameObjectContainer container) { className = creature.getClassName(); CreatureData creatureData = DataManager.getCreature(creature.getClassString()); type = creatureData != null ? creatureData.getName() : creature.getClassString(); location = creature.getLocation(); int dinoID1 = creature.findPropertyValue("DinoID1", Integer.class).orElse(0); int dinoID2 = creature.findPropertyValue("DinoID2", Integer.class).orElse(0); dinoId = (long) dinoID1 << Integer.SIZE | (dinoID2 & 0xFFFFFFFFL); targetingTeam = creature.findPropertyValue("TargetingTeam", Integer.class).orElse(0); tamed = targetingTeam < 0 || targetingTeam >= 50000; owningPlayerId = creature.findPropertyValue("OwningPlayerID", Integer.class).orElse(0); isFemale = creature.findPropertyValue("bIsFemale", Boolean.class).orElse(false); for (int i = 0; i < 6; i++) { colorSetIndices[i] = creature.findPropertyValue("ColorSetIndices", ArkByteValue.class, i).map(ArkByteValue::getByteValue).orElse((byte) 0); } tamedAtTime = creature.findPropertyValue("TamedAtTime", Double.class).orElse(0.0); tribeName = creature.findPropertyValue("TribeName", String.class).orElse(""); tamerString = creature.findPropertyValue("TamerString", String.class).orElse(""); owningPlayerName = creature.findPropertyValue("OwningPlayerName", String.class).orElse(""); tamedName = creature.findPropertyValue("TamedName", String.class).orElse(""); imprinterName = creature.findPropertyValue("ImprinterName", String.class).orElse(""); // Not all ancestors are saved. Only those ancestor information // are available which are displayed ingame in the UI. creature.findPropertyValue("DinoAncestors", ArkArrayStruct.class).ifPresent(ancestors -> { // traverse female ancestor line ancestors.forEach((value) -> { StructPropertyList propertyList = (StructPropertyList)value; AncestorLineEntry entry = new AncestorLineEntry(); entry.maleName = propertyList.findPropertyValue("MaleName", String.class).orElse(""); int fatherID1 = propertyList.getPropertyValue("MaleDinoID1", Integer.class); int fatherID2 = propertyList.getPropertyValue("MaleDinoID2", Integer.class); entry.maleId = (long) fatherID1 << Integer.SIZE | (fatherID2 & 0xFFFFFFFFL); entry.femaleName = propertyList.findPropertyValue("FemaleName", String.class).orElse(""); int motherID1 = propertyList.getPropertyValue("FemaleDinoID1", Integer.class); int motherID2 = propertyList.getPropertyValue("FemaleDinoID2", Integer.class); entry.femaleId = (long) motherID1 << Integer.SIZE | (motherID2 & 0xFFFFFFFFL); femaleAncestors.add(entry); }); }); creature.findPropertyValue("DinoAncestorsMale", ArkArrayStruct.class).ifPresent(ancestors -> { // traverse male ancestor line ancestors.forEach((value) -> { StructPropertyList propertyList = (StructPropertyList)value; AncestorLineEntry entry = new AncestorLineEntry(); entry.maleName = propertyList.findPropertyValue("MaleName", String.class).orElse(""); int fatherID1 = propertyList.getPropertyValue("MaleDinoID1", Integer.class); int fatherID2 = propertyList.getPropertyValue("MaleDinoID2", Integer.class); entry.maleId = (long) fatherID1 << Integer.SIZE | (fatherID2 & 0xFFFFFFFFL); entry.femaleName = propertyList.findPropertyValue("FemaleName", String.class).orElse(""); int motherID1 = propertyList.getPropertyValue("FemaleDinoID1", Integer.class); int motherID2 = propertyList.getPropertyValue("FemaleDinoID2", Integer.class); entry.femaleId = (long) motherID1 << Integer.SIZE | (motherID2 & 0xFFFFFFFFL); maleAncestors.add(entry); }); }); wildRandomScale = creature.findPropertyValue("WildRandomScale", Float.class).orElse(1.0f); isWakingTame = creature.findPropertyValue("bIsWakingTame", Boolean.class).orElse(false); isSleeping = creature.findPropertyValue("bIsSleeping", Boolean.class).orElse(false); requiredTameAffinity = creature.findPropertyValue("RequiredTameAffinity", Float.class).orElse(0.0f); currentTameAffinity = creature.findPropertyValue("CurrentTameAffinity", Float.class).orElse(0.0f); tamedIneffectivenessModifier = creature.findPropertyValue("TameIneffectivenessModifier", Float.class).orElse(0.0f); tamedFollowTarget = creature.findPropertyValue("TamedFollowTarget", ObjectReference.class).map(ObjectReference::getObjectId).orElse(-1); tamingTeamID = creature.findPropertyValue("TamingTeamID", Integer.class).orElse(0); tamedOnServerName = creature.findPropertyValue("TamedOnServerName", String.class).orElse(""); uploadedFromServerName = creature.findPropertyValue("UploadedFromServerName", String.class).orElse(""); tamedAggressionLevel = creature.findPropertyValue("TamedAggressionLevel", Integer.class).orElse(0); matingProgress = creature.findPropertyValue("MatingProgress", Float.class).orElse(0.0f); lastEnterStasisTime = creature.findPropertyValue("LastEnterStasisTime", Double.class).orElse(0.0); status = creature.findPropertyValue("MyCharacterStatusComponent", ObjectReference.class).map(container::getObject).orElse(null); inventory = creature.findPropertyValue("MyInventoryComponent", ObjectReference.class).map(container::getObject).orElse(null); if (status != null && status.getClassString().startsWith("DinoCharacterStatusComponent_")) { baseCharacterLevel = status.findPropertyValue("BaseCharacterLevel", Integer.class).orElse(1); for (int index = 0; index < AttributeNames.size(); index++) { numberOfLevelUpPointsApplied[index] = status.findPropertyValue("NumberOfLevelUpPointsApplied", ArkByteValue.class, index).map(ArkByteValue::getByteValue).orElse((byte) 0); } extraCharacterLevel = status.findPropertyValue("ExtraCharacterLevel", Short.class).orElse((short) 0); for (int index = 0; index < AttributeNames.size(); index++) { numberOfLevelUpPointsAppliedTamed[index] = status.findPropertyValue("NumberOfLevelUpPointsAppliedTamed", ArkByteValue.class, index).map(ArkByteValue::getByteValue).orElse((byte) 0); } allowLevelUps = status.findPropertyValue("bAllowLevelUps", Boolean.class).orElse(false); experiencePoints = status.findPropertyValue("ExperiencePoints", Float.class).orElse(0.0f); dinoImprintingQuality = status.findPropertyValue("DinoImprintingQuality", Float.class).orElse(0.0f); tamedIneffectivenessModifier = status.findPropertyValue("TamedIneffectivenessModifier", Float.class).orElse(tamedIneffectivenessModifier); } } public static class AncestorLineEntry { public String maleName; public long maleId; public String femaleName; public long femaleId; } public static final SortedMap<String, WriterFunction<Creature>> PROPERTIES = new TreeMap<>(); static { /** * Creature Properties */ PROPERTIES.put("type", (creature, generator, context, writeEmpty) -> { if (context instanceof DataCollector) { generator.writeStringField("type", creature.className.toString()); } else { generator.writeStringField("type", creature.type); } }); PROPERTIES.put("location", (creature, generator, context, writeEmpty) -> { if (writeEmpty || creature.location != null) { if (creature.location == null) { generator.writeNullField("location"); } else { generator.writeObjectFieldStart("location"); generator.writeNumberField("x", creature.location.getX()); generator.writeNumberField("y", creature.location.getY()); generator.writeNumberField("z", creature.location.getZ()); if (context.getLatLonCalculator() != null) { generator.writeNumberField("lat", context.getLatLonCalculator().calculateLat(creature.location.getY())); generator.writeNumberField("lon", context.getLatLonCalculator().calculateLon(creature.location.getX())); } generator.writeEndObject(); } } }); PROPERTIES.put("myInventoryComponent", (creature, generator, context, writeEmpty) -> { if (creature.inventory != null) { generator.writeNumberField("myInventoryComponent", creature.inventory.getId()); } else if (writeEmpty) { generator.writeNullField("myInventoryComponent"); } }); PROPERTIES.put("id", (creature, generator, context, writeEmpty) -> { if (writeEmpty || creature.dinoId != 0) { generator.writeNumberField("id", creature.dinoId); } }); PROPERTIES.put("tamed", (creature, generator, context, writeEmpty) -> { if (writeEmpty || creature.tamed) { generator.writeBooleanField("tamed", creature.tamed); } }); PROPERTIES.put("team", (creature, generator, context, writeEmpty) -> { if (writeEmpty || creature.targetingTeam != 0) { generator.writeNumberField("team", creature.targetingTeam); } }); PROPERTIES.put("playerId", (creature, generator, context, writeEmpty) -> { if (writeEmpty || creature.owningPlayerId != 0) { generator.writeNumberField("playerId", creature.owningPlayerId); } }); PROPERTIES.put("female", (creature, generator, context, writeEmpty) -> { if (writeEmpty || creature.isFemale) { generator.writeBooleanField("female", creature.isFemale); } }); PROPERTIES.put("colorSetIndices", (creature, generator, context, writeEmpty) -> { boolean empty = !writeEmpty; if (!empty) { generator.writeObjectFieldStart("colorSetIndices"); } for (int index = 0; index < creature.colorSetIndices.length; index++) { if (writeEmpty || creature.colorSetIndices[index] != 0) { if (empty) { empty = false; generator.writeObjectFieldStart("colorSetIndices"); } generator.writeNumberField(Integer.toString(index), Byte.toUnsignedInt(creature.colorSetIndices[index])); } } if (!empty) { generator.writeEndObject(); } }); PROPERTIES.put("femaleAncestors", (creature, generator, context, writeEmpty) -> { if (writeEmpty || !creature.femaleAncestors.isEmpty()) { generator.writeArrayFieldStart("femaleAncestors"); for (AncestorLineEntry entry: creature.femaleAncestors) { generator.writeStartObject(); generator.writeStringField("maleName", entry.maleName); generator.writeNumberField("maleId", entry.maleId); generator.writeStringField("femaleName", entry.femaleName); generator.writeNumberField("femaleId", entry.femaleId); generator.writeEndObject(); } generator.writeEndArray(); } }); PROPERTIES.put("maleAncestors", (creature, generator, context, writeEmpty) -> { if (writeEmpty || !creature.maleAncestors.isEmpty()) { generator.writeArrayFieldStart("maleAncestors"); for (AncestorLineEntry entry: creature.maleAncestors) { generator.writeStartObject(); generator.writeStringField("maleName", entry.maleName); generator.writeNumberField("maleId", entry.maleId); generator.writeStringField("femaleName", entry.femaleName); generator.writeNumberField("femaleId", entry.femaleId); generator.writeEndObject(); } generator.writeEndArray(); } }); PROPERTIES.put("tamedAtTime", (creature, generator, context, writeEmpty) -> { if (writeEmpty || creature.tamedAtTime != 0.0) { generator.writeNumberField("tamedAtTime", creature.tamedAtTime); } }); PROPERTIES.put("tamedTime", (creature, generator, context, writeEmpty) -> { if (context.getSavegame() != null && creature.tamedAtTime != 0.0) { generator.writeNumberField("tamedTime", context.getSavegame().getGameTime() - creature.tamedAtTime); } else if (writeEmpty) { generator.writeNullField("tamedTime"); } }); PROPERTIES.put("tribe", (creature, generator, context, writeEmpty) -> { if (writeEmpty || !creature.tribeName.isEmpty()) { generator.writeStringField("tribe", creature.tribeName); } }); PROPERTIES.put("tamer", (creature, generator, context, writeEmpty) -> { if (writeEmpty || !creature.tamerString.isEmpty()) { generator.writeStringField("tamer", creature.tamerString); } }); PROPERTIES.put("ownerName", (creature, generator, context, writeEmpty) -> { if (writeEmpty || !creature.owningPlayerName.isEmpty()) { generator.writeStringField("ownerName", creature.owningPlayerName); } }); PROPERTIES.put("name", (creature, generator, context, writeEmpty) -> { if (writeEmpty || !creature.tamedName.isEmpty()) { generator.writeStringField("name", creature.tamedName); } }); PROPERTIES.put("imprinter", (creature, generator, context, writeEmpty) -> { if (writeEmpty || !creature.imprinterName.isEmpty()) { generator.writeStringField("imprinter", creature.imprinterName); } }); PROPERTIES.put("baseLevel", (creature, generator, context, writeEmpty) -> { if (writeEmpty || creature.baseCharacterLevel != 0) { generator.writeNumberField("baseLevel", creature.baseCharacterLevel); } }); PROPERTIES.put("wildLevels", (creature, generator, context, writeEmpty) -> { boolean empty = !writeEmpty; if (!empty) { generator.writeObjectFieldStart("wildLevels"); } for (int index = 0; index < creature.numberOfLevelUpPointsApplied.length; index++) { if (writeEmpty || creature.numberOfLevelUpPointsApplied[index] != 0) { if (empty) { empty = false; generator.writeObjectFieldStart("wildLevels"); } generator.writeNumberField(AttributeNames.get(index), Byte.toUnsignedInt(creature.numberOfLevelUpPointsApplied[index])); } } if (!empty) { generator.writeEndObject(); } }); PROPERTIES.put("extraLevel", (creature, generator, context, writeEmpty) -> { if (writeEmpty || creature.extraCharacterLevel != 0) { generator.writeNumberField("extraLevel", creature.extraCharacterLevel); } }); PROPERTIES.put("tamedLevels", (creature, generator, context, writeEmpty) -> { boolean empty = !writeEmpty; if (!empty) { generator.writeObjectFieldStart("tamedLevels"); } for (int index = 0; index < creature.numberOfLevelUpPointsAppliedTamed.length; index++) { if (writeEmpty || creature.numberOfLevelUpPointsAppliedTamed[index] != 0) { if (empty) { empty = false; generator.writeObjectFieldStart("tamedLevels"); } generator.writeNumberField(AttributeNames.get(index), Byte.toUnsignedInt(creature.numberOfLevelUpPointsAppliedTamed[index])); } } if (!empty) { generator.writeEndObject(); } }); PROPERTIES.put("allowLevelUps", (creature, generator, context, writeEmpty) -> { if (writeEmpty || creature.allowLevelUps) { generator.writeBooleanField("allowLevelUps", creature.allowLevelUps); } }); PROPERTIES.put("experience", (creature, generator, context, writeEmpty) -> { if (writeEmpty || creature.experiencePoints != 0.0f) { generator.writeNumberField("experience", creature.experiencePoints); } }); PROPERTIES.put("imprintingQuality", (creature, generator, context, writeEmpty) -> { if (writeEmpty || creature.dinoImprintingQuality != 0.0f) { generator.writeNumberField("imprintingQuality", creature.dinoImprintingQuality); } }); PROPERTIES.put("wildRandomScale", (creature, generator, context, writeEmpty) -> { if (writeEmpty || creature.wildRandomScale != 1.0f) { generator.writeNumberField("wildRandomScale", creature.wildRandomScale); } }); PROPERTIES.put("isWakingTame", (creature, generator, context, writeEmpty) -> { if (writeEmpty || creature.isWakingTame) { generator.writeBooleanField("isWakingTame", creature.isWakingTame); } }); PROPERTIES.put("isSleeping", (creature, generator, context, writeEmpty) -> { if (writeEmpty || creature.isSleeping) { generator.writeBooleanField("isSleeping", creature.isSleeping); } }); PROPERTIES.put("requiredTameAffinity", (creature, generator, context, writeEmpty) -> { if (writeEmpty || creature.requiredTameAffinity != 0.0f) { generator.writeNumberField("requiredTameAffinity", creature.requiredTameAffinity); } }); PROPERTIES.put("currentTameAffinity", (creature, generator, context, writeEmpty) -> { if (writeEmpty || creature.currentTameAffinity != 0.0f) { generator.writeNumberField("currentTameAffinity", creature.currentTameAffinity); } }); PROPERTIES.put("tamingEffectivness", (creature, generator, context, writeEmpty) -> { if (writeEmpty || creature.tamedIneffectivenessModifier != 1.0f) { generator.writeNumberField("tamingEffectivness", 1.0f - creature.tamedIneffectivenessModifier); } }); PROPERTIES.put("tamedFollowTarget", (creature, generator, context, writeEmpty) -> { if (writeEmpty || creature.tamedFollowTarget != -1) { generator.writeNumberField("tamedFollowTarget", creature.tamedFollowTarget); } }); PROPERTIES.put("tamingTeamID", (creature, generator, context, writeEmpty) -> { if (writeEmpty || creature.tamingTeamID != 0) { generator.writeNumberField("tamingTeamID", creature.tamingTeamID); } }); PROPERTIES.put("tamedOnServerName", (creature, generator, context, writeEmpty) -> { if (writeEmpty || !creature.tamedOnServerName.isEmpty()) { generator.writeStringField("tamedOnServerName", creature.tamedOnServerName); } }); PROPERTIES.put("uploadedFromServerName", (creature, generator, context, writeEmpty) -> { if (writeEmpty || !creature.uploadedFromServerName.isEmpty()) { generator.writeStringField("uploadedFromServerName", creature.uploadedFromServerName); } }); PROPERTIES.put("tamedAggressionLevel", (creature, generator, context, writeEmpty) -> { if (writeEmpty || creature.tamedAggressionLevel != 0) { generator.writeNumberField("tamedAggressionLevel", creature.tamedAggressionLevel); } }); PROPERTIES.put("matingProgress", (creature, generator, context, writeEmpty) -> { if (writeEmpty || creature.matingProgress != 0.0f) { generator.writeNumberField("matingProgress", creature.matingProgress); } }); PROPERTIES.put("lastEnterStasisTime", (creature, generator, context, writeEmpty) -> { if (writeEmpty || creature.lastEnterStasisTime != 0.0) { generator.writeNumberField("lastEnterStasisTime", creature.lastEnterStasisTime); } }); } public static final List<WriterFunction<Creature>> PROPERTIES_LIST = new ArrayList<>(PROPERTIES.values()); public void writeAllProperties(JsonGenerator generator, DataContext context, boolean writeEmpty) throws IOException { for (WriterFunction<Creature> writer: PROPERTIES_LIST) { writer.accept(this, generator, context, writeEmpty); } } public void writeInventory(JsonGenerator generator, DataContext context, boolean writeEmpty, boolean inventorySummary) throws IOException { if (this.inventory != null) { Inventory inventory = new Inventory(this.inventory); generator.writeFieldName("inventory"); inventory.writeInventory(generator, context, writeEmpty, inventorySummary); } } }
412
0.80561
1
0.80561
game-dev
MEDIA
0.75894
game-dev
0.962107
1
0.962107
diasurgical/DevilutionX
2,858
Source/stores.h
/** * @file stores.h * * Interface of functionality for stores and towner dialogs. */ #pragma once #include <cstdint> #include <optional> #include "DiabloUI/ui_flags.hpp" #include "control.h" #include "engine/clx_sprite.hpp" #include "engine/surface.hpp" #include "game_mode.hpp" #include "utils/attributes.h" namespace devilution { constexpr int NumSmithBasicItems = 19; constexpr int NumSmithBasicItemsHf = 24; constexpr int NumSmithItems = 6; constexpr int NumSmithItemsHf = 15; constexpr int NumHealerItems = 17; constexpr int NumHealerItemsHf = 19; constexpr int NumHealerPinnedItems = 2; constexpr int NumHealerPinnedItemsMp = 3; constexpr int NumWitchItems = 17; constexpr int NumWitchItemsHf = 24; constexpr int NumWitchPinnedItems = 3; constexpr int NumStoreLines = 104; enum class TalkID : uint8_t { None, Smith, SmithBuy, SmithSell, SmithRepair, Witch, WitchBuy, WitchSell, WitchRecharge, NoMoney, NoRoom, Confirm, Boy, BoyBuy, Healer, Storyteller, HealerBuy, StorytellerIdentify, SmithPremiumBuy, Gossip, StorytellerIdentifyShow, Tavern, Drunk, Barmaid, }; /** Currently active store */ extern TalkID ActiveStore; /** Current index into PlayerItemIndexes/PlayerItems */ extern DVL_API_FOR_TEST int CurrentItemIndex; /** Map of inventory items being presented in the store */ extern int8_t PlayerItemIndexes[48]; /** Copies of the players items as presented in the store */ extern DVL_API_FOR_TEST Item PlayerItems[48]; /** Items sold by Griswold */ extern Item SmithItems[NumSmithBasicItemsHf]; /** Number of premium items for sale by Griswold */ extern int PremiumItemCount; /** Base level of current premium items sold by Griswold */ extern int PremiumItemLevel; /** Premium items sold by Griswold */ extern Item PremiumItems[NumSmithItemsHf]; /** Items sold by Pepin */ extern Item HealerItems[20]; /** Items sold by Adria */ extern Item WitchItems[NumWitchItemsHf]; /** Current level of the item sold by Wirt */ extern int BoyItemLevel; /** Current item sold by Wirt */ extern Item BoyItem; void AddStoreHoldRepair(Item *itm, int8_t i); /** Clears premium items sold by Griswold and Wirt. */ void InitStores(); /** Spawns items sold by vendors, including premium items sold by Griswold and Wirt. */ void SetupTownStores(); void FreeStoreMem(); void PrintSString(const Surface &out, int margin, int line, std::string_view text, UiFlags flags, int price = 0, int cursId = -1, bool cursIndent = false); void DrawSLine(const Surface &out, int sy); void DrawSTextHelp(); void ClearSText(int s, int e); void StartStore(TalkID s); void DrawSText(const Surface &out); void StoreESC(); void StoreUp(); void StoreDown(); void StorePrior(); void StoreNext(); void TakePlrsMoney(int cost); void StoreEnter(); void CheckStoreBtn(); void ReleaseStoreBtn(); bool IsPlayerInStore(); } // namespace devilution
412
0.908032
1
0.908032
game-dev
MEDIA
0.929878
game-dev
0.887078
1
0.887078
PlayFab/UnrealMarketplacePlugin
2,209
template/templates/PlayFabCpp/core/PlayFab_API.h.ejs
<%- copyright %> // This is automatically generated by PlayFab SDKGenerator. DO NOT modify this manually! #pragma once #include "CoreMinimal.h" #include "Core/PlayFabError.h" #include "Core/PlayFab<%- api.name %>DataModels.h" #include "Core/PlayFabSettings.h" #include "Interfaces/IHttpRequest.h" #include "Interfaces/IHttpResponse.h" namespace PlayFab { class PLAYFABCPP_API UPlayFab<%- api.name %>API { public: <% for(var i in api.calls) { var apiCall = api.calls[i]; %> DECLARE_DELEGATE_OneParam(F<%- apiCall.name %>Delegate, const <%- api.name %>Models::F<%- apiCall.result%>&); <% } %> UPlayFab<%- api.name %>API(); ~UPlayFab<%- api.name %>API(); int GetPendingCalls() const; FString GetBuildIdentifier() const; <% if (hasClientOptions) { %> bool IsClientLoggedIn() const; <% } %> // ------------ Generated API calls <% for(var i in api.calls) { var apiCall = api.calls[i]; if (hasRequest(apiCall, api)) { %><%- generateApiSummary(" ", apiCall, "summary") %> bool <%- apiCall.name %>(<%- api.name %>Models::F<%- apiCall.request %>& request, const F<%- apiCall.name %>Delegate& SuccessDelegate = F<%- apiCall.name %>Delegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); <% } else {%><%- generateApiSummary(" ", apiCall, "summary") %> bool <%- apiCall.name %>(const F<%- apiCall.name %>Delegate& SuccessDelegate = F<%- apiCall.name %>Delegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); <%- generateApiSummary(" ", apiCall, "summary") %> bool <%- apiCall.name %>(<%- api.name %>Models::F<%- apiCall.request %>& request, const F<%- apiCall.name %>Delegate& SuccessDelegate = F<%- apiCall.name %>Delegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); <% } } %> private: // ------------ Generated result handlers <% for(var i in api.calls) { var apiCall = api.calls[i]; %> void On<%- apiCall.name %>Result(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, F<%- apiCall.name %>Delegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); <% } %> }; };
412
0.704411
1
0.704411
game-dev
MEDIA
0.486851
game-dev
0.620093
1
0.620093
SourceEngine-CommunityEdition/source
2,072
game/server/cstrike/bot/states/cs_bot_defuse_bomb.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// // Author: Michael S. Booth (mike@turtlerockstudios.com), 2003 #include "cbase.h" #include "cs_bot.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" //-------------------------------------------------------------------------------------------------------------- /** * Begin defusing the bomb */ void DefuseBombState::OnEnter( CCSBot *me ) { me->Crouch(); me->SetDisposition( CCSBot::SELF_DEFENSE ); me->GetChatter()->Say( "DefusingBomb" ); } //-------------------------------------------------------------------------------------------------------------- /** * Defuse the bomb */ void DefuseBombState::OnUpdate( CCSBot *me ) { const Vector *bombPos = me->GetGameState()->GetBombPosition(); if (bombPos == NULL) { me->PrintIfWatched( "In Defuse state, but don't know where the bomb is!\n" ); me->Idle(); return; } // look at the bomb me->SetLookAt( "Defuse bomb", *bombPos, PRIORITY_HIGH ); // defuse... me->UseEnvironment(); if (gpGlobals->curtime - me->GetStateTimestamp() > 1.0f) { // if we missed starting the defuse, give up if (TheCSBots()->GetBombDefuser() == NULL) { me->PrintIfWatched( "Failed to start defuse, giving up\n" ); me->Idle(); return; } else if (TheCSBots()->GetBombDefuser() != me) { // if someone else got the defuse, give up me->PrintIfWatched( "Someone else started defusing, giving up\n" ); me->Idle(); return; } } // if bomb has been defused, give up if (!TheCSBots()->IsBombPlanted()) { me->Idle(); return; } } //-------------------------------------------------------------------------------------------------------------- void DefuseBombState::OnExit( CCSBot *me ) { me->StandUp(); me->ResetStuckMonitor(); me->SetTask( CCSBot::SEEK_AND_DESTROY ); me->SetDisposition( CCSBot::ENGAGE_AND_INVESTIGATE ); me->ClearLookAt(); }
412
0.671711
1
0.671711
game-dev
MEDIA
0.8614
game-dev
0.731753
1
0.731753
Kaedrin/nwn2cc
3,208
NWN2 WIP/Override/override_latest/Scripts/nw_s0_slaylive.NSS
//:://///////////////////////////////////////////// //:: [Slay Living] //:: [NW_S0_SlayLive.nss] //:: Copyright (c) 2000 Bioware Corp. //::////////////////////////////////////////////// //:: Caster makes a touch attack and if the target //:: fails a Fortitude save they die. //::////////////////////////////////////////////// //:: Created By: Preston Watamaniuk //:: Created On: January 22nd / 2001 //::////////////////////////////////////////////// //:: Last Updated By: Preston Watamaniuk, On: April 11, 2001 //:: VFX Pass By: Preston W, On: June 25, 2001 #include "NW_I0_SPELLS" #include "x2_inc_spellhook" #include "cmi_inc_sneakattack" #include "cmi_ginc_spells" void main() { /* Spellcast Hook Code Added 2003-06-23 by GeorgZ If you want to make changes to all spells, check x2_inc_spellhook.nss to find out more */ if (!X2PreSpellCastCode()) { // If code within the PreSpellCastHook (i.e. UMD) reports FALSE, do not run this spell return; } // End of Spell Cast Hook //Declare major variables int nMetaMagic = GetMetaMagicFeat(); object oTarget = GetSpellTargetObject(); int nCasterLevel = GetCasterLevel(OBJECT_SELF); int nDamage; effect eDam; effect eVis = EffectVisualEffect(VFX_HIT_SPELL_NECROMANCY); if (spellsIsTarget(oTarget, SPELL_TARGET_STANDARDHOSTILE, OBJECT_SELF)) { if( GetRacialType(oTarget) == RACIAL_TYPE_UNDEAD) { FloatingTextStrRefOnCreature(40105, OBJECT_SELF, FALSE); return; } //Fire cast spell at event for the specified target SignalEvent(oTarget, EventSpellCastAt(OBJECT_SELF, SPELL_SLAY_LIVING)); //Make melee touch attack if(TouchAttackMelee(oTarget)) { //Make SR check if(!MyResistSpell(OBJECT_SELF, oTarget)) { //Make Fort save if (!/*Fort Save*/ MySavingThrow(SAVING_THROW_FORT, oTarget, GetSpellSaveDC(), SAVING_THROW_TYPE_DEATH)) { //Apply the death effect and VFX impact ApplyEffectToObject(DURATION_TYPE_INSTANT, EffectDeath(), oTarget); } else { //Roll damage nDamage = d6(3)+ nCasterLevel; //Make metamagic checks if (nMetaMagic == METAMAGIC_MAXIMIZE) { nDamage = 18 + nCasterLevel; } if (nMetaMagic == METAMAGIC_EMPOWER) { nDamage = nDamage + (nDamage/2); } nDamage += GetMeleeTouchSpecDamage(OBJECT_SELF, 3 , FALSE); //include sneak attack damage if (StringToInt(Get2DAString("cmi_options","Value",CMI_OPTIONS_SneakAttackSpells))) nDamage += EvaluateSneakAttack(oTarget, OBJECT_SELF); //Apply damage effect and VFX impact eDam = EffectDamage(nDamage, DAMAGE_TYPE_NEGATIVE); ApplyEffectToObject(DURATION_TYPE_INSTANT, eDam, oTarget); } ApplyEffectToObject(DURATION_TYPE_INSTANT, eVis, oTarget); } } } }
412
0.917195
1
0.917195
game-dev
MEDIA
0.970035
game-dev
0.973718
1
0.973718
furas/python-examples
3,685
pygame/action-after-time-shake-player-when-it-is-boring/main.py
# https://www.pygame.org/docs/ # # https://github.com/furas/python-examples/ import pygame import random # --- constants --- (UPPER_CASE_NAMES) SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 FPS = 25 # for more than 220 it has no time to update screen BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) # --- classes --- (CamelCaseNames) class Player(pygame.sprite.Sprite): def __init__(self, x=SCREEN_WIDTH//2, y=SCREEN_HEIGHT//2): super().__init__() self.image_white = pygame.Surface((100,100)) self.image_white.fill(WHITE) self.image_red_face = pygame.Surface((100,100)) self.image_red_face.fill(RED) # left eye pygame.draw.rect(self.image_red_face, BLACK, (20,20,10,10)) # right eye pygame.draw.rect(self.image_red_face, BLACK, (70,20,10,10)) # mouth pygame.draw.rect(self.image_red_face, BLACK, (30,60,40,10)) # mouth left corner pygame.draw.rect(self.image_red_face, BLACK, (20,70,10,10)) # mouth right corner pygame.draw.rect(self.image_red_face, BLACK, (70,70,10,10)) self.image = self.image_white self.rect = self.image.get_rect(centerx=x, centery=y) def update(self): #move_x = random.randint(-5, 5) #move_y = random.randint(-5, 5) #self.rect.move_ip(move_x,move_y) pass def draw(self, surface): surface.blit(self.image, self.rect) def start_action(self): # save original position self.old_center = self.rect.center # change image self.image = self.image_red_face def action(self): # random move self.rect.y -= random.randint(-5, 5) def end_action(self): # restore original position self.rect.center = self.old_center # change image self.image = self.image_white # --- functions --- (lower_case_names) # --- main --- pygame.init() screen = pygame.display.set_mode( (SCREEN_WIDTH, SCREEN_HEIGHT) ) player = Player() # --- mainloop --- clock = pygame.time.Clock() # default values at start do_something = False time_since_last_action = 0 running = True while running: # --- FPS --- dt = clock.tick(30) time_since_last_action += dt # --- events --- for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYUP: if event.key == pygame.K_ESCAPE: running = False keys = pygame.key.get_pressed() moved = False if keys[pygame.K_LEFT]: player.rect.x -= 10 # player.rect.width moved = True # reset other values #do_something = False time_since_last_action = 0 elif keys[pygame.K_RIGHT]: player.rect.x += 10 # player.rect.width moved = True # reset other values #do_something = False time_since_last_action = 0 if not do_something and not moved and time_since_last_action > 1000: do_something = True player.start_action() # reset other values time_since_last_action = 0 if do_something and not moved: #----action---- player.action() if do_something and moved: do_something = False player.end_action() # reset other values time_since_last_action = 0 # --- changes/moves/updates --- #if not pygame.key.get_pressed()[pygame.K_SPACE]: # player.update() # --- draws --- screen.fill(BLACK) player.draw(screen) pygame.display.flip() # --- end --- pygame.quit()
412
0.622281
1
0.622281
game-dev
MEDIA
0.724657
game-dev
0.961678
1
0.961678
rossturner/king-under-the-mountain
16,381
core/src/main/java/technology/rocketjump/undermount/entities/components/LiquidContainerComponent.java
package technology.rocketjump.undermount.entities.components; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.badlogic.gdx.ai.msg.MessageDispatcher; import com.badlogic.gdx.math.GridPoint2; import com.google.common.collect.ImmutableMap; import org.pmw.tinylog.Logger; import technology.rocketjump.undermount.entities.model.Entity; import technology.rocketjump.undermount.entities.model.EntityType; import technology.rocketjump.undermount.entities.model.physical.furniture.FurnitureEntityAttributes; import technology.rocketjump.undermount.entities.model.physical.furniture.FurnitureLayout; import technology.rocketjump.undermount.entities.model.physical.item.ItemEntityAttributes; import technology.rocketjump.undermount.gamecontext.GameContext; import technology.rocketjump.undermount.jobs.LiquidMessageHandler; import technology.rocketjump.undermount.mapping.tile.MapTile; import technology.rocketjump.undermount.materials.model.GameMaterial; import technology.rocketjump.undermount.materials.model.GameMaterialType; import technology.rocketjump.undermount.messaging.MessageType; import technology.rocketjump.undermount.messaging.types.ItemPrimaryMaterialChangedMessage; import technology.rocketjump.undermount.misc.Destructible; import technology.rocketjump.undermount.persistence.SavedGameDependentDictionaries; import technology.rocketjump.undermount.persistence.model.InvalidSaveException; import technology.rocketjump.undermount.persistence.model.SavedGameStateHolder; import technology.rocketjump.undermount.ui.i18n.I18nText; import technology.rocketjump.undermount.ui.i18n.I18nTranslator; import technology.rocketjump.undermount.ui.i18n.I18nWord; import technology.rocketjump.undermount.zones.Zone; import technology.rocketjump.undermount.zones.ZoneClassification; import technology.rocketjump.undermount.zones.ZoneTile; import java.text.DecimalFormat; import java.util.*; import static technology.rocketjump.undermount.entities.ai.goap.actions.nourishment.LocateDrinkAction.LIQUID_AMOUNT_FOR_DRINK_CONSUMPTION; import static technology.rocketjump.undermount.entities.components.ItemAllocation.AllocationState.ACTIVE; import static technology.rocketjump.undermount.entities.components.ItemAllocation.AllocationState.CANCELLED; import static technology.rocketjump.undermount.entities.components.LiquidAllocation.LiquidAllocationType.*; import static technology.rocketjump.undermount.misc.VectorUtils.toGridPoint; public class LiquidContainerComponent implements ParentDependentEntityComponent, Destructible { private static final int MIN_CAPACITY_TO_CLASS_AS_HIGH_CAPACITY = 10; private static final float SMALL_AMOUNT = 0.1f; public static DecimalFormat oneDecimalFormat = new DecimalFormat("#.#"); private Entity parentEntity; private MessageDispatcher messageDispatcher; private GameContext gameContext; private GameMaterial targetLiquidMaterial; private float liquidQuantity = 0; private Set<LiquidAllocation> allocations = new HashSet<>(); private int maxLiquidCapacity; private Zone liquidContainerAccessZone; private boolean alwaysInactive = false; @Override public void init(Entity parentEntity, MessageDispatcher messageDispatcher, GameContext gameContext) { this.parentEntity = parentEntity; this.messageDispatcher = messageDispatcher; this.gameContext = gameContext; // Create zone in area around furniture if (parentEntity.getType().equals(EntityType.FURNITURE) && parentEntity.getBehaviourComponent() != null && liquidContainerAccessZone == null) { // Skip when BehaviourComponent is null as this implies its a furniture for placing via UI FurnitureEntityAttributes attributes = (FurnitureEntityAttributes) parentEntity.getPhysicalEntityComponent().getAttributes(); if (targetLiquidMaterial == null) { Logger.error("Creating LiquidContainer zone with no targetLiquidMaterial specified"); } else { if (!attributes.getCurrentLayout().getWorkspaces().isEmpty()) { liquidContainerAccessZone = new Zone(new ZoneClassification(ZoneClassification.ZoneType.LIQUID_SOURCE, true, targetLiquidMaterial, maxLiquidCapacity >= MIN_CAPACITY_TO_CLASS_AS_HIGH_CAPACITY)); GridPoint2 furniturePosition = toGridPoint(parentEntity.getLocationComponent().getWorldPosition()); MapTile furnitureTile = gameContext.getAreaMap().getTile(furniturePosition); for (FurnitureLayout.Workspace workspace : attributes.getCurrentLayout().getWorkspaces()) { GridPoint2 workspaceLocation = furniturePosition.cpy().add(workspace.getAccessedFrom()); MapTile workspaceTile = gameContext.getAreaMap().getTile(workspaceLocation); if (workspaceTile != null && workspaceTile.isNavigable(parentEntity)) { liquidContainerAccessZone.add(workspaceTile, furnitureTile); } } if (liquidQuantity == 0) { liquidContainerAccessZone.setActive(false); } gameContext.getAreaMap().addZone(liquidContainerAccessZone); } } } updateParentMaterial(); } @Override public void destroy(Entity parentEntity, MessageDispatcher messageDispatcher, GameContext gameContext) { if (liquidContainerAccessZone != null) { gameContext.getAreaMap().removeZone(liquidContainerAccessZone); } liquidContainerAccessZone = null; if (liquidQuantity > 0 && targetLiquidMaterial != null && messageDispatcher != null) { messageDispatcher.dispatchMessage(MessageType.LIQUID_AMOUNT_CHANGED, new LiquidAmountChangedMessage(parentEntity, targetLiquidMaterial, this.liquidQuantity, 0)); } targetLiquidMaterial = null; liquidQuantity = 0; for (LiquidAllocation allocation : new HashSet<>(allocations)) { this.cancelAllocation(allocation); } } @Override public EntityComponent clone(MessageDispatcher messageDispatcher, GameContext gameContext) { LiquidContainerComponent cloned = new LiquidContainerComponent(); cloned.messageDispatcher = messageDispatcher; cloned.parentEntity = this.parentEntity; cloned.targetLiquidMaterial = this.targetLiquidMaterial; cloned.liquidQuantity = this.liquidQuantity; cloned.maxLiquidCapacity = this.maxLiquidCapacity; if (messageDispatcher != null) { messageDispatcher.dispatchMessage(MessageType.LIQUID_AMOUNT_CHANGED, new LiquidAmountChangedMessage(parentEntity, targetLiquidMaterial, 0, this.liquidQuantity)); } return cloned; } public GameMaterial getTargetLiquidMaterial() { return targetLiquidMaterial; } public void setTargetLiquidMaterial(GameMaterial targetLiquidMaterial) { GameMaterial oldMaterial = this.targetLiquidMaterial; if (targetLiquidMaterial == null) { if (parentEntity.getPhysicalEntityComponent().getAttributes() instanceof ItemEntityAttributes) { ((ItemEntityAttributes) parentEntity.getPhysicalEntityComponent().getAttributes()).removeMaterial(GameMaterialType.LIQUID); } else if (parentEntity.getPhysicalEntityComponent().getAttributes() instanceof FurnitureEntityAttributes) { ((FurnitureEntityAttributes) parentEntity.getPhysicalEntityComponent().getAttributes()).removeMaterial(GameMaterialType.LIQUID); } } else { if (liquidContainerAccessZone != null) { liquidContainerAccessZone.getClassification().setTargetMaterial(targetLiquidMaterial); } } this.targetLiquidMaterial = targetLiquidMaterial; if (messageDispatcher != null && !Objects.equals(oldMaterial, this.targetLiquidMaterial)) { messageDispatcher.dispatchMessage(MessageType.LIQUID_AMOUNT_CHANGED, new LiquidAmountChangedMessage(parentEntity, oldMaterial, this.liquidQuantity, 0)); messageDispatcher.dispatchMessage(MessageType.LIQUID_AMOUNT_CHANGED, new LiquidAmountChangedMessage(parentEntity, this.targetLiquidMaterial, 0, this.liquidQuantity)); } } public float getLiquidQuantity() { return liquidQuantity; } public void setLiquidQuantity(float liquidQuantity) { float oldLiquidQuantity = this.liquidQuantity; this.liquidQuantity = liquidQuantity; if (liquidQuantity <= SMALL_AMOUNT) { this.liquidQuantity = 0; if (liquidContainerAccessZone != null) { liquidContainerAccessZone.setActive(false); } } else { updateParentMaterial(); if (liquidContainerAccessZone != null && !alwaysInactive) { if (liquidQuantity < usableLiquidAmount()) { liquidContainerAccessZone.setActive(false); } else { liquidContainerAccessZone.setActive(true); } } } if (parentEntity != null && messageDispatcher != null) { messageDispatcher.dispatchMessage(MessageType.ENTITY_ASSET_UPDATE_REQUIRED, parentEntity); messageDispatcher.dispatchMessage(MessageType.LIQUID_AMOUNT_CHANGED, new LiquidAmountChangedMessage(parentEntity, this.targetLiquidMaterial, oldLiquidQuantity, this.liquidQuantity)); } } public float usableLiquidAmount() { return targetLiquidMaterial != null && targetLiquidMaterial.isQuenchesThirst() ? LIQUID_AMOUNT_FOR_DRINK_CONSUMPTION : 1; } public float getNumAllocated() { float totalAllocated = 0f; for (LiquidAllocation allocation : allocations) { totalAllocated += allocation.getAllocationAmount(); } return totalAllocated; } public LiquidAllocation createAllocation(float amountRequired, Entity requestingEntity) { if (getNumUnallocated() < amountRequired) { return null; } else { ZoneTile zoneTile = LiquidMessageHandler.pickTileInZone(this.liquidContainerAccessZone, gameContext.getRandom(), gameContext.getAreaMap()); LiquidAllocation allocation = new LiquidAllocation(FROM_LIQUID_CONTAINER, zoneTile, amountRequired, targetLiquidMaterial); allocation.setTargetContainerId(parentEntity.getId()); allocation.setRequesterEntityId(requestingEntity.getId()); allocations.add(allocation); return allocation; } } public LiquidAllocation createAllocationDueToParentHauling(float amountRequired, Entity requestingEntity) { if (getNumUnallocated() < amountRequired) { return null; } else { LiquidAllocation allocation = new LiquidAllocation(PARENT_HAULING, new ZoneTile() /* null object */, amountRequired, targetLiquidMaterial); allocation.setTargetContainerId(parentEntity.getId()); allocation.setRequesterEntityId(requestingEntity.getId()); allocations.add(allocation); return allocation; } } public LiquidAllocation assignCraftingAllocation(float amountRequired) { if (getNumUnallocated() < amountRequired) { return null; } else { LiquidAllocation allocation = new LiquidAllocation(CRAFTING_ASSIGNMENT, new ZoneTile() /* null object */, amountRequired, targetLiquidMaterial); allocation.setTargetContainerId(parentEntity.getId()); allocation.setRequesterEntityId(parentEntity.getId()); allocations.add(allocation); return allocation; } } public LiquidAllocation cancelAllocation(LiquidAllocation liquidAllocation) { if (liquidAllocation != null && allocations.contains(liquidAllocation)) { if (liquidAllocation.getState().equals(ACTIVE)) { allocations.remove(liquidAllocation); liquidAllocation.setState(CANCELLED); return liquidAllocation; } else { Logger.error("Cancelling LiquidAllocation with state " + liquidAllocation.getState()); } } else { Logger.error("Attempting to cancel allocation at wrong container"); } return null; } public LiquidAllocation cancelAllocationAndDecrementQuantity(LiquidAllocation liquidAllocation) { liquidAllocation = cancelAllocation(liquidAllocation); if (liquidAllocation != null) { setLiquidQuantity(liquidQuantity - liquidAllocation.getAllocationAmount()); if (liquidQuantity < 0.1f) { messageDispatcher.dispatchMessage(MessageType.ENTITY_ASSET_UPDATE_REQUIRED, parentEntity); } } return liquidAllocation; } public void cancelAllAllocations() { for (LiquidAllocation allocation : new HashSet<>(allocations)) { this.cancelAllocation(allocation); } } private void updateParentMaterial() { if (targetLiquidMaterial != null && parentEntity != null) { if (parentEntity.getPhysicalEntityComponent().getAttributes() instanceof ItemEntityAttributes) { ItemEntityAttributes attributes = (ItemEntityAttributes) parentEntity.getPhysicalEntityComponent().getAttributes(); GameMaterial oldPrimaryMaterial = attributes.getPrimaryMaterial(); attributes.setMaterial(targetLiquidMaterial); if (!oldPrimaryMaterial.equals(attributes.getPrimaryMaterial())) { messageDispatcher.dispatchMessage(MessageType.ITEM_PRIMARY_MATERIAL_CHANGED, new ItemPrimaryMaterialChangedMessage(parentEntity, oldPrimaryMaterial)); } } else if (parentEntity.getPhysicalEntityComponent().getAttributes() instanceof FurnitureEntityAttributes) { ((FurnitureEntityAttributes) parentEntity.getPhysicalEntityComponent().getAttributes()).setMaterial(targetLiquidMaterial); } } } public void setMaxLiquidCapacity(int maxLiquidCapacity) { this.maxLiquidCapacity = maxLiquidCapacity; } public Integer getMaxLiquidCapacity() { return maxLiquidCapacity; } public boolean isAlwaysInactive() { return alwaysInactive; } public void setAlwaysInactive(boolean alwaysInactive) { this.alwaysInactive = alwaysInactive; } public List<I18nText> i18nDescription(I18nTranslator i18nTranslator) { List<I18nText> results = new ArrayList<>(); if (targetLiquidMaterial != null) { results.add(i18nTranslator.getLiquidDescription(targetLiquidMaterial, liquidQuantity)); float numAllocated = getNumAllocated(); if (numAllocated > 0) { results.add(i18nTranslator.getTranslatedWordWithReplacements("CONSTRUCTION.ITEM_ALLOCATION", ImmutableMap.of( "quantity", new I18nWord(oneDecimalFormat.format(numAllocated)), "itemDescription", new I18nWord(oneDecimalFormat.format(liquidQuantity)) ))); } } return results; } @Override public void writeTo(JSONObject asJson, SavedGameStateHolder savedGameStateHolder) { if (targetLiquidMaterial != null) { asJson.put("targetLiquidMaterial", targetLiquidMaterial.getMaterialName()); } if (liquidQuantity != 0) { asJson.put("quantity", liquidQuantity); } JSONArray allocationsArray = new JSONArray(); for (LiquidAllocation allocation : allocations) { allocation.writeTo(savedGameStateHolder); allocationsArray.add(allocation.getLiquidAllocationId()); } asJson.put("allocations", allocationsArray); if (maxLiquidCapacity != 0) { asJson.put("maxCapacity", maxLiquidCapacity); } if (liquidContainerAccessZone != null) { liquidContainerAccessZone.writeTo(savedGameStateHolder); asJson.put("accessZone", liquidContainerAccessZone.getZoneId()); } if (alwaysInactive) { asJson.put("alwaysInactive", true); } } @Override public void readFrom(JSONObject asJson, SavedGameStateHolder savedGameStateHolder, SavedGameDependentDictionaries relatedStores) throws InvalidSaveException { String targetLiquidMaterialName = asJson.getString("targetLiquidMaterial"); if (targetLiquidMaterialName != null) { this.targetLiquidMaterial = relatedStores.gameMaterialDictionary.getByName(targetLiquidMaterialName); if (this.targetLiquidMaterial == null) { throw new InvalidSaveException("Could not find material with name " + targetLiquidMaterialName); } } this.liquidQuantity = asJson.getIntValue("quantity"); JSONArray allocationsArray = asJson.getJSONArray("allocations"); if (allocationsArray != null) { for (int cursor = 0; cursor < allocationsArray.size(); cursor++) { long allocationId = allocationsArray.getLongValue(cursor); LiquidAllocation liquidAllocation = savedGameStateHolder.liquidAllocations.get(allocationId); if (liquidAllocation == null) { throw new InvalidSaveException("Could not find liquid allocation with ID " + allocationId); } else { this.allocations.add(liquidAllocation); } } } this.maxLiquidCapacity = asJson.getIntValue("maxCapacity"); Long zoneId = asJson.getLong("accessZone"); if (zoneId != null) { this.liquidContainerAccessZone = savedGameStateHolder.zones.get(zoneId); if (this.liquidContainerAccessZone == null) { throw new InvalidSaveException("Could not find zone with ID " + zoneId); } } this.alwaysInactive = asJson.getBooleanValue("alwaysInactive"); } public float getNumUnallocated() { return liquidQuantity - getNumAllocated(); } public boolean isEmpty() { return liquidQuantity <= 0; } public Zone getAccessZone() { return liquidContainerAccessZone; } }
412
0.790658
1
0.790658
game-dev
MEDIA
0.938504
game-dev
0.642964
1
0.642964
BramStoutProductions/MiEx
6,226
src/nl/bramstout/mcworldexporter/entity/ai/behaviour/AIComponentBehaviourMoveToLava.java
/* * BSD 3-Clause License * * Copyright (c) 2024, Bram Stout Productions * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package nl.bramstout.mcworldexporter.entity.ai.behaviour; import nl.bramstout.mcworldexporter.MCWorldExporter; import nl.bramstout.mcworldexporter.entity.Entity; import nl.bramstout.mcworldexporter.entity.ai.AIComponent; import nl.bramstout.mcworldexporter.entity.ai.EntityTarget.EntityTargetBlock; import nl.bramstout.mcworldexporter.entity.ai.EntityUtil; import nl.bramstout.mcworldexporter.world.Block; import nl.bramstout.mcworldexporter.world.BlockRegistry; public class AIComponentBehaviourMoveToLava extends AIComponent{ /** * Distance in blocks within the mob considers it has reached the goal. * This is the wiggle room to stop the AI from bouncing back and * forth trying to reach a specific spot. */ public float goalRadius; /** * The number of blocks each tick that the mob will check within * its search range and height for a valid block to move to. * A value of 0 will have the mob check every block within range * in one tick. */ public int searchCount; /** * Height in blocks the mob will look for land to move towards. */ public int searchHeight; /** * The distance in blocks it will look for land to move towards. */ public int searchRange; private boolean isMoving; public AIComponentBehaviourMoveToLava(String name, int priority) { super(name, PriorityGroup.BEHAVIOUR, priority, -1); isMoving = false; } @Override public boolean tick(Entity entity, float time, float deltaTime, boolean forceEnable) { float posX = entity.getAnimation().getAnimPosX().getKeyframeAtTime(time).value; float posY = entity.getAnimation().getAnimPosY().getKeyframeAtTime(time).value; float posZ = entity.getAnimation().getAnimPosZ().getKeyframeAtTime(time).value; if(isMoving) { if(entity.getAI().target == null) { isMoving = false; return false; } float targetX = entity.getAI().target.getPosX(time); float targetY = entity.getAI().target.getPosY(time); float targetZ = entity.getAI().target.getPosZ(time); float distanceSquared = (targetX - posX) * (targetX - posX) + (targetY - posY) * (targetY - posY) + (targetZ - posZ) * (targetZ - posZ); if(distanceSquared <= (goalRadius * goalRadius)) { isMoving = false; return false; } return true; } if(EntityUtil.isInLiquid(entity, posX, posY, posZ)) return false; int blockX = (int) Math.floor(posX); int blockY = (int) Math.floor(posY); int blockZ = (int) Math.floor(posZ); // Entity is in liquid, so try to find a spot for it to move to. if(searchCount <= 0) { // Check every block in range for(int sampleY = -searchHeight; sampleY <= searchHeight; ++sampleY) { for(int sampleZ = -searchRange; sampleZ <= searchRange; ++sampleZ) { for(int sampleX = -searchRange; sampleX <= searchRange; ++sampleX) { int blockId = MCWorldExporter.getApp().getWorld().getBlockId(sampleX + blockX, sampleY + blockY, sampleZ + blockZ); int blockIdAbove = MCWorldExporter.getApp().getWorld().getBlockId(sampleX + blockX, sampleY + blockY + 1, sampleZ + blockZ); if(blockIdAbove != 0) continue; Block block = BlockRegistry.getBlock(blockId); if(!block.hasLiquid()) continue; if(!block.getName().equals("minecraft:lava")) continue; // We've found a block in lava to move to. entity.getAI().target = new EntityTargetBlock(sampleX + blockX, sampleY + blockY, sampleZ + blockZ); isMoving = true; return true; } } } }else { // Randomly check blocks. for(int i = 0; i < searchCount; ++i) { int sampleX = entity.getRandom().nextInt(-searchRange, searchRange + 1) + blockX; int sampleY = entity.getRandom().nextInt(-searchHeight, searchHeight + 1) + blockY; int sampleZ = entity.getRandom().nextInt(-searchRange, searchRange + 1) + blockZ; int blockId = MCWorldExporter.getApp().getWorld().getBlockId(sampleX, sampleY, sampleZ); int blockIdAbove = MCWorldExporter.getApp().getWorld().getBlockId(sampleX, sampleY + 1, sampleZ); if(blockIdAbove != 0) continue; Block block = BlockRegistry.getBlock(blockId); if(!block.hasLiquid()) continue; if(!block.getName().equals("minecraft:lava")) continue; // We've found a block on land to move to. entity.getAI().target = new EntityTargetBlock(sampleX, sampleY, sampleZ); isMoving = true; return true; } } // We didn't find a spot to move to. return false; } @Override public void disabledTick(Entity entity, float time, float deltaTime) { isMoving = false; } }
412
0.84165
1
0.84165
game-dev
MEDIA
0.932463
game-dev
0.92563
1
0.92563
Ragebones/StormCore
65,641
src/server/scripts/Northrend/IcecrownCitadel/boss_professor_putricide.cpp
/* * Copyright (C) 2014-2017 StormCore * * 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 "ObjectMgr.h" #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "SpellAuraEffects.h" #include "Group.h" #include "Spell.h" #include "icecrown_citadel.h" #include "Vehicle.h" #include "GridNotifiers.h" enum Say { // Festergut SAY_FESTERGUT_GASEOUS_BLIGHT = 0, SAY_FESTERGUT_DEATH = 1, // Rotface SAY_ROTFACE_OOZE_FLOOD = 2, SAY_ROTFACE_DEATH = 3, // Professor Putricide SAY_AGGRO = 4, EMOTE_UNSTABLE_EXPERIMENT = 5, SAY_PHASE_TRANSITION_HEROIC = 6, SAY_TRANSFORM_1 = 7, SAY_TRANSFORM_2 = 8, // always used for phase2 change, DO NOT GROUP WITH SAY_TRANSFORM_1 EMOTE_MALLEABLE_GOO = 9, EMOTE_CHOKING_GAS_BOMB = 10, SAY_KILL = 11, SAY_BERSERK = 12, SAY_DEATH = 13 }; enum Spells { // Festergut SPELL_RELEASE_GAS_VISUAL = 69125, SPELL_GASEOUS_BLIGHT_LARGE = 69157, SPELL_GASEOUS_BLIGHT_MEDIUM = 69162, SPELL_GASEOUS_BLIGHT_SMALL = 69164, SPELL_MALLEABLE_GOO_H = 72296, SPELL_MALLEABLE_GOO_SUMMON = 72299, // Professor Putricide SPELL_SLIME_PUDDLE_TRIGGER = 70341, SPELL_MALLEABLE_GOO = 70852, SPELL_UNSTABLE_EXPERIMENT = 70351, SPELL_TEAR_GAS = 71617, // phase transition SPELL_TEAR_GAS_CREATURE = 71618, SPELL_TEAR_GAS_CANCEL = 71620, SPELL_TEAR_GAS_PERIODIC_TRIGGER = 73170, SPELL_CREATE_CONCOCTION = 71621, SPELL_GUZZLE_POTIONS = 71893, SPELL_OOZE_TANK_PROTECTION = 71770, // protects the tank SPELL_CHOKING_GAS_BOMB = 71255, SPELL_OOZE_VARIABLE = 74118, SPELL_GAS_VARIABLE = 74119, SPELL_UNBOUND_PLAGUE = 70911, SPELL_UNBOUND_PLAGUE_SEARCHER = 70917, SPELL_PLAGUE_SICKNESS = 70953, SPELL_UNBOUND_PLAGUE_PROTECTION = 70955, SPELL_MUTATED_PLAGUE = 72451, SPELL_MUTATED_PLAGUE_CLEAR = 72618, // Slime Puddle SPELL_GROW_STACKER = 70345, SPELL_GROW = 70347, SPELL_SLIME_PUDDLE_AURA = 70343, // Gas Cloud SPELL_GASEOUS_BLOAT_PROC = 70215, SPELL_GASEOUS_BLOAT = 70672, SPELL_GASEOUS_BLOAT_PROTECTION = 70812, SPELL_EXPUNGED_GAS = 70701, // Volatile Ooze SPELL_OOZE_ERUPTION = 70492, SPELL_VOLATILE_OOZE_ADHESIVE = 70447, SPELL_OOZE_ERUPTION_SEARCH_PERIODIC = 70457, SPELL_VOLATILE_OOZE_PROTECTION = 70530, // Choking Gas Bomb SPELL_CHOKING_GAS_BOMB_PERIODIC = 71259, SPELL_CHOKING_GAS_EXPLOSION_TRIGGER = 71280, // Mutated Abomination vehicle SPELL_ABOMINATION_VEHICLE_POWER_DRAIN = 70385, SPELL_MUTATED_TRANSFORMATION = 70311, SPELL_MUTATED_TRANSFORMATION_DAMAGE = 70405, SPELL_MUTATED_TRANSFORMATION_NAME = 72401, // Unholy Infusion SPELL_UNHOLY_INFUSION_CREDIT = 71518 }; #define SPELL_GASEOUS_BLOAT_HELPER RAID_MODE<uint32>(70672, 72455, 72832, 72833) enum Events { // Festergut EVENT_FESTERGUT_DIES = 1, EVENT_FESTERGUT_GOO = 2, // Rotface EVENT_ROTFACE_DIES = 3, EVENT_ROTFACE_OOZE_FLOOD = 5, // Professor Putricide EVENT_BERSERK = 6, // all phases EVENT_SLIME_PUDDLE = 7, // all phases EVENT_UNSTABLE_EXPERIMENT = 8, // P1 && P2 EVENT_TEAR_GAS = 9, // phase transition not heroic EVENT_RESUME_ATTACK = 10, EVENT_MALLEABLE_GOO = 11, EVENT_CHOKING_GAS_BOMB = 12, EVENT_UNBOUND_PLAGUE = 13, EVENT_MUTATED_PLAGUE = 14, EVENT_PHASE_TRANSITION = 15 }; enum Phases { PHASE_NONE = 0, PHASE_FESTERGUT = 1, PHASE_ROTFACE = 2, PHASE_COMBAT_1 = 4, PHASE_COMBAT_2 = 5, PHASE_COMBAT_3 = 6 }; enum Points { POINT_FESTERGUT = 366260, POINT_ROTFACE = 366270, POINT_TABLE = 366780 }; Position const festergutWatchPos = {4324.820f, 3166.03f, 389.3831f, 3.316126f}; //emote 432 (release gas) Position const rotfaceWatchPos = {4390.371f, 3164.50f, 389.3890f, 5.497787f}; //emote 432 (release ooze) Position const tablePos = {4356.190f, 3262.90f, 389.4820f, 1.483530f}; // used in Rotface encounter uint32 const oozeFloodSpells[4] = {69782, 69796, 69798, 69801}; enum PutricideData { DATA_EXPERIMENT_STAGE = 1, DATA_PHASE = 2, DATA_ABOMINATION = 3 }; #define EXPERIMENT_STATE_OOZE false #define EXPERIMENT_STATE_GAS true class AbominationDespawner { public: explicit AbominationDespawner(Unit* owner) : _owner(owner) { } bool operator()(ObjectGuid guid) { if (Unit* summon = ObjectAccessor::GetUnit(*_owner, guid)) { if (summon->GetEntry() == NPC_MUTATED_ABOMINATION_10 || summon->GetEntry() == NPC_MUTATED_ABOMINATION_25) { if (Vehicle* veh = summon->GetVehicleKit()) veh->RemoveAllPassengers(); // also despawns the vehicle // Found unit is Mutated Abomination, remove it return true; } // Found unit is not Mutated Abomintaion, leave it return false; } // No unit found, remove from SummonList return true; } private: Unit* _owner; }; struct RotfaceHeightCheck { RotfaceHeightCheck(Creature* rotface) : _rotface(rotface) { } bool operator()(Creature* stalker) const { return stalker->GetPositionZ() < _rotface->GetPositionZ() + 5.0f; } private: Creature* _rotface; }; class boss_professor_putricide : public CreatureScript { public: boss_professor_putricide() : CreatureScript("boss_professor_putricide") { } struct boss_professor_putricideAI : public BossAI { boss_professor_putricideAI(Creature* creature) : BossAI(creature, DATA_PROFESSOR_PUTRICIDE), _baseSpeed(creature->GetSpeedRate(MOVE_RUN)), _experimentState(EXPERIMENT_STATE_OOZE) { _phase = PHASE_NONE; _oozeFloodStage = 0; } void Reset() override { if (!(events.IsInPhase(PHASE_ROTFACE) || events.IsInPhase(PHASE_FESTERGUT))) instance->SetBossState(DATA_PROFESSOR_PUTRICIDE, NOT_STARTED); instance->SetData(DATA_NAUSEA_ACHIEVEMENT, uint32(true)); events.Reset(); summons.DespawnAll(); SetPhase(PHASE_COMBAT_1); _experimentState = EXPERIMENT_STATE_OOZE; me->SetReactState(REACT_DEFENSIVE); me->SetWalk(false); if (me->GetMotionMaster()->GetCurrentMovementGeneratorType() == POINT_MOTION_TYPE) me->GetMotionMaster()->MovementExpired(); if (instance->GetBossState(DATA_ROTFACE) == DONE && instance->GetBossState(DATA_FESTERGUT) == DONE) me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_NOT_SELECTABLE); } void EnterCombat(Unit* who) override { if (events.IsInPhase(PHASE_ROTFACE) || events.IsInPhase(PHASE_FESTERGUT)) return; if (!instance->CheckRequiredBosses(DATA_PROFESSOR_PUTRICIDE, who->ToPlayer())) { EnterEvadeMode(); instance->DoCastSpellOnPlayers(LIGHT_S_HAMMER_TELEPORT); return; } me->setActive(true); events.Reset(); events.ScheduleEvent(EVENT_BERSERK, 600000); events.ScheduleEvent(EVENT_SLIME_PUDDLE, 10000); events.ScheduleEvent(EVENT_UNSTABLE_EXPERIMENT, urand(30000, 35000)); if (IsHeroic()) events.ScheduleEvent(EVENT_UNBOUND_PLAGUE, 20000); SetPhase(PHASE_COMBAT_1); Talk(SAY_AGGRO); DoCast(me, SPELL_OOZE_TANK_PROTECTION, true); DoZoneInCombat(me); instance->SetBossState(DATA_PROFESSOR_PUTRICIDE, IN_PROGRESS); } void JustReachedHome() override { _JustReachedHome(); me->SetWalk(false); if (events.IsInPhase(PHASE_COMBAT_1) || events.IsInPhase(PHASE_COMBAT_2) || events.IsInPhase(PHASE_COMBAT_3)) instance->SetBossState(DATA_PROFESSOR_PUTRICIDE, FAIL); } void KilledUnit(Unit* victim) override { if (victim->GetTypeId() == TYPEID_PLAYER) Talk(SAY_KILL); } void JustDied(Unit* /*killer*/) override { _JustDied(); Talk(SAY_DEATH); if (Is25ManRaid() && me->HasAura(SPELL_SHADOWS_FATE)) DoCastAOE(SPELL_UNHOLY_INFUSION_CREDIT, true); DoCast(SPELL_MUTATED_PLAGUE_CLEAR); } void JustSummoned(Creature* summon) override { summons.Summon(summon); switch (summon->GetEntry()) { case NPC_MALLEABLE_OOZE_STALKER: DoCast(summon, SPELL_MALLEABLE_GOO_H); return; case NPC_GROWING_OOZE_PUDDLE: summon->CastSpell(summon, SPELL_GROW_STACKER, true); summon->CastSpell(summon, SPELL_SLIME_PUDDLE_AURA, true); // blizzard casts this spell 7 times initially (confirmed in sniff) for (uint8 i = 0; i < 7; ++i) summon->CastSpell(summon, SPELL_GROW, true); break; case NPC_GAS_CLOUD: // no possible aura seen in sniff adding the aurastate summon->ModifyAuraState(AURA_STATE_UNKNOWN22, true); summon->CastSpell(summon, SPELL_GASEOUS_BLOAT_PROC, true); summon->SetReactState(REACT_PASSIVE); break; case NPC_VOLATILE_OOZE: // no possible aura seen in sniff adding the aurastate summon->ModifyAuraState(AURA_STATE_UNKNOWN19, true); summon->CastSpell(summon, SPELL_OOZE_ERUPTION_SEARCH_PERIODIC, true); summon->SetReactState(REACT_PASSIVE); break; case NPC_CHOKING_GAS_BOMB: summon->CastSpell(summon, SPELL_CHOKING_GAS_BOMB_PERIODIC, true); summon->CastSpell(summon, SPELL_CHOKING_GAS_EXPLOSION_TRIGGER, true); return; case NPC_MUTATED_ABOMINATION_10: case NPC_MUTATED_ABOMINATION_25: return; default: break; } if (me->IsInCombat()) DoZoneInCombat(summon); } void DamageTaken(Unit* /*attacker*/, uint32& /*damage*/) override { switch (_phase) { case PHASE_COMBAT_1: if (HealthAbovePct(80)) return; me->SetReactState(REACT_PASSIVE); DoAction(ACTION_CHANGE_PHASE); break; case PHASE_COMBAT_2: if (HealthAbovePct(35)) return; me->SetReactState(REACT_PASSIVE); DoAction(ACTION_CHANGE_PHASE); break; default: break; } } void MovementInform(uint32 type, uint32 id) override { if (type != POINT_MOTION_TYPE) return; switch (id) { case POINT_FESTERGUT: instance->SetBossState(DATA_FESTERGUT, IN_PROGRESS); // needed here for delayed gate close me->SetSpeedRate(MOVE_RUN, _baseSpeed); DoAction(ACTION_FESTERGUT_GAS); if (Creature* festergut = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_FESTERGUT))) festergut->CastSpell(festergut, SPELL_GASEOUS_BLIGHT_LARGE, false, NULL, NULL, festergut->GetGUID()); break; case POINT_ROTFACE: instance->SetBossState(DATA_ROTFACE, IN_PROGRESS); // needed here for delayed gate close me->SetSpeedRate(MOVE_RUN, _baseSpeed); DoAction(ACTION_ROTFACE_OOZE); events.ScheduleEvent(EVENT_ROTFACE_OOZE_FLOOD, 25000, 0, PHASE_ROTFACE); break; case POINT_TABLE: // stop attack me->GetMotionMaster()->MoveIdle(); me->SetSpeedRate(MOVE_RUN, _baseSpeed); if (GameObject* table = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(DATA_PUTRICIDE_TABLE))) me->SetFacingToObject(table); // operating on new phase already switch (_phase) { case PHASE_COMBAT_2: { SpellInfo const* spell = sSpellMgr->GetSpellInfo(SPELL_CREATE_CONCOCTION); DoCast(me, SPELL_CREATE_CONCOCTION); events.ScheduleEvent(EVENT_PHASE_TRANSITION, spell->CalcCastTime() + 100); break; } case PHASE_COMBAT_3: { SpellInfo const* spell = sSpellMgr->GetSpellInfo(SPELL_GUZZLE_POTIONS); DoCast(me, SPELL_GUZZLE_POTIONS); events.ScheduleEvent(EVENT_PHASE_TRANSITION, spell->CalcCastTime() + 100); break; } default: break; } break; default: break; } } void DoAction(int32 action) override { switch (action) { case ACTION_FESTERGUT_COMBAT: SetPhase(PHASE_FESTERGUT); me->SetSpeedRate(MOVE_RUN, _baseSpeed*2.0f); me->GetMotionMaster()->MovePoint(POINT_FESTERGUT, festergutWatchPos); me->SetReactState(REACT_PASSIVE); DoZoneInCombat(me); if (IsHeroic()) events.ScheduleEvent(EVENT_FESTERGUT_GOO, urand(13000, 18000), 0, PHASE_FESTERGUT); break; case ACTION_FESTERGUT_GAS: Talk(SAY_FESTERGUT_GASEOUS_BLIGHT); DoCast(me, SPELL_RELEASE_GAS_VISUAL, true); break; case ACTION_FESTERGUT_DEATH: events.ScheduleEvent(EVENT_FESTERGUT_DIES, 4000, 0, PHASE_FESTERGUT); break; case ACTION_ROTFACE_COMBAT: { SetPhase(PHASE_ROTFACE); me->SetSpeedRate(MOVE_RUN, _baseSpeed*2.0f); me->GetMotionMaster()->MovePoint(POINT_ROTFACE, rotfaceWatchPos); me->SetReactState(REACT_PASSIVE); _oozeFloodStage = 0; DoZoneInCombat(me); // init random sequence of floods if (Creature* rotface = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_ROTFACE))) { std::list<Creature*> list; GetCreatureListWithEntryInGrid(list, rotface, NPC_PUDDLE_STALKER, 50.0f); list.remove_if(RotfaceHeightCheck(rotface)); if (list.size() > 4) { list.sort(Trinity::ObjectDistanceOrderPred(rotface)); do { list.pop_back(); } while (list.size() > 4); } uint8 i = 0; while (!list.empty()) { std::list<Creature*>::iterator itr = list.begin(); std::advance(itr, urand(0, list.size()-1)); _oozeFloodDummyGUIDs[i++] = (*itr)->GetGUID(); list.erase(itr); } } break; } case ACTION_ROTFACE_OOZE: Talk(SAY_ROTFACE_OOZE_FLOOD); if (Creature* dummy = ObjectAccessor::GetCreature(*me, _oozeFloodDummyGUIDs[_oozeFloodStage])) dummy->CastSpell(dummy, oozeFloodSpells[_oozeFloodStage], true, NULL, NULL, me->GetGUID()); // cast from self for LoS (with prof's GUID for logs) if (++_oozeFloodStage == 4) _oozeFloodStage = 0; break; case ACTION_ROTFACE_DEATH: events.ScheduleEvent(EVENT_ROTFACE_DIES, 4500, 0, PHASE_ROTFACE); break; case ACTION_CHANGE_PHASE: me->SetSpeedRate(MOVE_RUN, _baseSpeed*2.0f); events.DelayEvents(30000); me->AttackStop(); if (!IsHeroic()) { DoCast(me, SPELL_TEAR_GAS); events.ScheduleEvent(EVENT_TEAR_GAS, 2500); } else { Talk(SAY_PHASE_TRANSITION_HEROIC); DoCast(me, SPELL_UNSTABLE_EXPERIMENT, true); DoCast(me, SPELL_UNSTABLE_EXPERIMENT, true); // cast variables if (Is25ManRaid()) { std::list<Unit*> targetList; { const std::list<HostileReference*>& threatlist = me->getThreatManager().getThreatList(); for (std::list<HostileReference*>::const_iterator itr = threatlist.begin(); itr != threatlist.end(); ++itr) if ((*itr)->getTarget()->GetTypeId() == TYPEID_PLAYER) targetList.push_back((*itr)->getTarget()); } size_t half = targetList.size()/2; // half gets ooze variable while (half < targetList.size()) { std::list<Unit*>::iterator itr = targetList.begin(); advance(itr, urand(0, targetList.size() - 1)); (*itr)->CastSpell(*itr, SPELL_OOZE_VARIABLE, true); targetList.erase(itr); } // and half gets gas for (std::list<Unit*>::iterator itr = targetList.begin(); itr != targetList.end(); ++itr) (*itr)->CastSpell(*itr, SPELL_GAS_VARIABLE, true); } me->GetMotionMaster()->MovePoint(POINT_TABLE, tablePos); } switch (_phase) { case PHASE_COMBAT_1: SetPhase(PHASE_COMBAT_2); events.ScheduleEvent(EVENT_MALLEABLE_GOO, urand(21000, 26000)); events.ScheduleEvent(EVENT_CHOKING_GAS_BOMB, urand(35000, 40000)); break; case PHASE_COMBAT_2: SetPhase(PHASE_COMBAT_3); events.ScheduleEvent(EVENT_MUTATED_PLAGUE, 25000); events.CancelEvent(EVENT_UNSTABLE_EXPERIMENT); break; default: break; } break; default: break; } } uint32 GetData(uint32 type) const override { switch (type) { case DATA_EXPERIMENT_STAGE: return _experimentState; case DATA_PHASE: return _phase; case DATA_ABOMINATION: return uint32(summons.HasEntry(NPC_MUTATED_ABOMINATION_10) || summons.HasEntry(NPC_MUTATED_ABOMINATION_25)); default: break; } return 0; } void SetData(uint32 id, uint32 data) override { if (id == DATA_EXPERIMENT_STAGE) _experimentState = data != 0; } void UpdateAI(uint32 diff) override { if (!(events.IsInPhase(PHASE_ROTFACE) || events.IsInPhase(PHASE_FESTERGUT)) && !UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_FESTERGUT_DIES: Talk(SAY_FESTERGUT_DEATH); EnterEvadeMode(); break; case EVENT_FESTERGUT_GOO: me->CastCustomSpell(SPELL_MALLEABLE_GOO_SUMMON, SPELLVALUE_MAX_TARGETS, 1, NULL, true); events.ScheduleEvent(EVENT_FESTERGUT_GOO, (Is25ManRaid() ? 10000 : 30000) + urand(0, 5000), 0, PHASE_FESTERGUT); break; case EVENT_ROTFACE_DIES: Talk(SAY_ROTFACE_DEATH); EnterEvadeMode(); break; case EVENT_ROTFACE_OOZE_FLOOD: DoAction(ACTION_ROTFACE_OOZE); events.ScheduleEvent(EVENT_ROTFACE_OOZE_FLOOD, 25000, 0, PHASE_ROTFACE); break; case EVENT_BERSERK: Talk(SAY_BERSERK); DoCast(me, SPELL_BERSERK2); break; case EVENT_SLIME_PUDDLE: { std::list<Unit*> targets; SelectTargetList(targets, 2, SELECT_TARGET_RANDOM, 0.0f, true); if (!targets.empty()) for (std::list<Unit*>::iterator itr = targets.begin(); itr != targets.end(); ++itr) DoCast(*itr, SPELL_SLIME_PUDDLE_TRIGGER); events.ScheduleEvent(EVENT_SLIME_PUDDLE, 35000); break; } case EVENT_UNSTABLE_EXPERIMENT: Talk(EMOTE_UNSTABLE_EXPERIMENT); DoCast(me, SPELL_UNSTABLE_EXPERIMENT); events.ScheduleEvent(EVENT_UNSTABLE_EXPERIMENT, urand(35000, 40000)); break; case EVENT_TEAR_GAS: me->GetMotionMaster()->MovePoint(POINT_TABLE, tablePos); DoCast(me, SPELL_TEAR_GAS_PERIODIC_TRIGGER, true); break; case EVENT_RESUME_ATTACK: me->SetReactState(REACT_AGGRESSIVE); AttackStart(me->GetVictim()); // remove Tear Gas me->RemoveAurasDueToSpell(SPELL_TEAR_GAS_PERIODIC_TRIGGER); instance->DoRemoveAurasDueToSpellOnPlayers(71615); DoCastAOE(SPELL_TEAR_GAS_CANCEL); instance->DoRemoveAurasDueToSpellOnPlayers(SPELL_GAS_VARIABLE); instance->DoRemoveAurasDueToSpellOnPlayers(SPELL_OOZE_VARIABLE); break; case EVENT_MALLEABLE_GOO: if (Is25ManRaid()) { std::list<Unit*> targets; SelectTargetList(targets, 2, SELECT_TARGET_RANDOM, -7.0f, true); if (!targets.empty()) { Talk(EMOTE_MALLEABLE_GOO); for (std::list<Unit*>::iterator itr = targets.begin(); itr != targets.end(); ++itr) DoCast(*itr, SPELL_MALLEABLE_GOO); } } else { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, -7.0f, true)) { Talk(EMOTE_MALLEABLE_GOO); DoCast(target, SPELL_MALLEABLE_GOO); } } events.ScheduleEvent(EVENT_MALLEABLE_GOO, urand(25000, 30000)); break; case EVENT_CHOKING_GAS_BOMB: Talk(EMOTE_CHOKING_GAS_BOMB); DoCast(me, SPELL_CHOKING_GAS_BOMB); events.ScheduleEvent(EVENT_CHOKING_GAS_BOMB, urand(35000, 40000)); break; case EVENT_UNBOUND_PLAGUE: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, NonTankTargetSelector(me))) { DoCast(target, SPELL_UNBOUND_PLAGUE); DoCast(target, SPELL_UNBOUND_PLAGUE_SEARCHER); } events.ScheduleEvent(EVENT_UNBOUND_PLAGUE, 90000); break; case EVENT_MUTATED_PLAGUE: DoCastVictim(SPELL_MUTATED_PLAGUE); events.ScheduleEvent(EVENT_MUTATED_PLAGUE, 10000); break; case EVENT_PHASE_TRANSITION: { switch (_phase) { case PHASE_COMBAT_2: if (Creature* face = me->FindNearestCreature(NPC_TEAR_GAS_TARGET_STALKER, 50.0f)) me->SetFacingToObject(face); me->HandleEmoteCommand(EMOTE_ONESHOT_KNEEL); Talk(SAY_TRANSFORM_1); events.ScheduleEvent(EVENT_RESUME_ATTACK, 5500, 0, PHASE_COMBAT_2); break; case PHASE_COMBAT_3: if (Creature* face = me->FindNearestCreature(NPC_TEAR_GAS_TARGET_STALKER, 50.0f)) me->SetFacingToObject(face); me->HandleEmoteCommand(EMOTE_ONESHOT_KNEEL); Talk(SAY_TRANSFORM_2); summons.DespawnIf(AbominationDespawner(me)); events.ScheduleEvent(EVENT_RESUME_ATTACK, 8500, 0, PHASE_COMBAT_3); break; default: break; } } default: break; } } DoMeleeAttackIfReady(); } private: void SetPhase(Phases newPhase) { _phase = newPhase; events.SetPhase(newPhase); } ObjectGuid _oozeFloodDummyGUIDs[4]; Phases _phase; // external of EventMap because event phase gets reset on evade float const _baseSpeed; uint8 _oozeFloodStage; bool _experimentState; }; CreatureAI* GetAI(Creature* creature) const override { return GetIcecrownCitadelAI<boss_professor_putricideAI>(creature); } }; class npc_putricide_oozeAI : public ScriptedAI { public: npc_putricide_oozeAI(Creature* creature, uint32 hitTargetSpellId) : ScriptedAI(creature), _hitTargetSpellId(hitTargetSpellId), _newTargetSelectTimer(0) { } void SpellHitTarget(Unit* /*target*/, SpellInfo const* spell) override { if (!_newTargetSelectTimer && spell->Id == _hitTargetSpellId) _newTargetSelectTimer = 1000; } void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (spell->Id == SPELL_TEAR_GAS_CREATURE) _newTargetSelectTimer = 1000; } void UpdateAI(uint32 diff) override { if (!UpdateVictim() && !_newTargetSelectTimer) return; if (!_newTargetSelectTimer && !me->IsNonMeleeSpellCast(false, false, true, false, true)) _newTargetSelectTimer = 1000; DoMeleeAttackIfReady(); if (!_newTargetSelectTimer) return; if (me->HasAura(SPELL_TEAR_GAS_CREATURE)) return; if (_newTargetSelectTimer <= diff) { _newTargetSelectTimer = 0; CastMainSpell(); } else _newTargetSelectTimer -= diff; } virtual void CastMainSpell() = 0; private: uint32 _hitTargetSpellId; uint32 _newTargetSelectTimer; }; class npc_volatile_ooze : public CreatureScript { public: npc_volatile_ooze() : CreatureScript("npc_volatile_ooze") { } struct npc_volatile_oozeAI : public npc_putricide_oozeAI { npc_volatile_oozeAI(Creature* creature) : npc_putricide_oozeAI(creature, SPELL_OOZE_ERUPTION) { } void CastMainSpell() override { me->CastSpell(me, SPELL_VOLATILE_OOZE_ADHESIVE, false); } }; CreatureAI* GetAI(Creature* creature) const override { return GetIcecrownCitadelAI<npc_volatile_oozeAI>(creature); } }; class npc_gas_cloud : public CreatureScript { public: npc_gas_cloud() : CreatureScript("npc_gas_cloud") { } struct npc_gas_cloudAI : public npc_putricide_oozeAI { npc_gas_cloudAI(Creature* creature) : npc_putricide_oozeAI(creature, SPELL_EXPUNGED_GAS) { _newTargetSelectTimer = 0; } void CastMainSpell() override { me->CastCustomSpell(SPELL_GASEOUS_BLOAT, SPELLVALUE_AURA_STACK, 10, me, false); } private: uint32 _newTargetSelectTimer; }; CreatureAI* GetAI(Creature* creature) const override { return GetIcecrownCitadelAI<npc_gas_cloudAI>(creature); } }; class spell_putricide_gaseous_bloat : public SpellScriptLoader { public: spell_putricide_gaseous_bloat() : SpellScriptLoader("spell_putricide_gaseous_bloat") { } class spell_putricide_gaseous_bloat_AuraScript : public AuraScript { PrepareAuraScript(spell_putricide_gaseous_bloat_AuraScript); void HandleExtraEffect(AuraEffect const* /*aurEff*/) { Unit* target = GetTarget(); if (Unit* caster = GetCaster()) { target->RemoveAuraFromStack(GetSpellInfo()->Id, GetCasterGUID()); if (!target->HasAura(GetId())) caster->CastCustomSpell(SPELL_GASEOUS_BLOAT, SPELLVALUE_AURA_STACK, 10, caster, false); } } void Register() override { OnEffectPeriodic += AuraEffectPeriodicFn(spell_putricide_gaseous_bloat_AuraScript::HandleExtraEffect, EFFECT_0, SPELL_AURA_PERIODIC_DAMAGE); } }; AuraScript* GetAuraScript() const override { return new spell_putricide_gaseous_bloat_AuraScript(); } }; class spell_putricide_ooze_channel : public SpellScriptLoader { public: spell_putricide_ooze_channel() : SpellScriptLoader("spell_putricide_ooze_channel") { } class spell_putricide_ooze_channel_SpellScript : public SpellScript { PrepareSpellScript(spell_putricide_ooze_channel_SpellScript); public: spell_putricide_ooze_channel_SpellScript() { _target = nullptr; } private: bool Validate(SpellInfo const* spell) override { if (!spell->ExcludeTargetAuraSpell) return false; if (!sSpellMgr->GetSpellInfo(spell->ExcludeTargetAuraSpell)) return false; return true; } // set up initial variables and check if caster is creature // this will let use safely use ToCreature() casts in entire script bool Load() override { return GetCaster()->GetTypeId() == TYPEID_UNIT; } void SelectTarget(std::list<WorldObject*>& targets) { if (targets.empty()) { FinishCast(SPELL_FAILED_NO_VALID_TARGETS); GetCaster()->ToCreature()->DespawnOrUnsummon(1); // despawn next update return; } WorldObject* target = Trinity::Containers::SelectRandomContainerElement(targets); targets.clear(); targets.push_back(target); _target = target; } void SetTarget(std::list<WorldObject*>& targets) { targets.clear(); if (_target) targets.push_back(_target); } void StartAttack() { GetCaster()->ClearUnitState(UNIT_STATE_CASTING); GetCaster()->DeleteThreatList(); GetCaster()->ToCreature()->AI()->AttackStart(GetHitUnit()); GetCaster()->AddThreat(GetHitUnit(), 500000000.0f); // value seen in sniff } void Register() override { OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_putricide_ooze_channel_SpellScript::SelectTarget, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY); OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_putricide_ooze_channel_SpellScript::SetTarget, EFFECT_1, TARGET_UNIT_SRC_AREA_ENEMY); OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_putricide_ooze_channel_SpellScript::SetTarget, EFFECT_2, TARGET_UNIT_SRC_AREA_ENEMY); AfterHit += SpellHitFn(spell_putricide_ooze_channel_SpellScript::StartAttack); } WorldObject* _target; }; SpellScript* GetSpellScript() const override { return new spell_putricide_ooze_channel_SpellScript(); } }; class ExactDistanceCheck { public: ExactDistanceCheck(Unit* source, float dist) : _source(source), _dist(dist) { } bool operator()(WorldObject* unit) const { return _source->GetExactDist2d(unit) > _dist; } private: Unit* _source; float _dist; }; class spell_putricide_slime_puddle : public SpellScriptLoader { public: spell_putricide_slime_puddle() : SpellScriptLoader("spell_putricide_slime_puddle") { } class spell_putricide_slime_puddle_SpellScript : public SpellScript { PrepareSpellScript(spell_putricide_slime_puddle_SpellScript); void ScaleRange(std::list<WorldObject*>& targets) { targets.remove_if(ExactDistanceCheck(GetCaster(), 2.5f * GetCaster()->GetObjectScale())); } void Register() override { OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_putricide_slime_puddle_SpellScript::ScaleRange, EFFECT_0, TARGET_UNIT_DEST_AREA_ENEMY); OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_putricide_slime_puddle_SpellScript::ScaleRange, EFFECT_1, TARGET_UNIT_DEST_AREA_ENTRY); } }; SpellScript* GetSpellScript() const override { return new spell_putricide_slime_puddle_SpellScript(); } }; // this is here only because on retail you dont actually enter HEROIC mode for ICC class spell_putricide_slime_puddle_aura : public SpellScriptLoader { public: spell_putricide_slime_puddle_aura() : SpellScriptLoader("spell_putricide_slime_puddle_aura") { } class spell_putricide_slime_puddle_aura_SpellScript : public SpellScript { PrepareSpellScript(spell_putricide_slime_puddle_aura_SpellScript); void ReplaceAura() { if (Unit* target = GetHitUnit()) GetCaster()->AddAura((GetCaster()->GetMap()->GetSpawnMode() & 1) ? 72456 : 70346, target); } void Register() override { OnHit += SpellHitFn(spell_putricide_slime_puddle_aura_SpellScript::ReplaceAura); } }; SpellScript* GetSpellScript() const override { return new spell_putricide_slime_puddle_aura_SpellScript(); } }; class spell_putricide_unstable_experiment : public SpellScriptLoader { public: spell_putricide_unstable_experiment() : SpellScriptLoader("spell_putricide_unstable_experiment") { } class spell_putricide_unstable_experiment_SpellScript : public SpellScript { PrepareSpellScript(spell_putricide_unstable_experiment_SpellScript); void HandleScript(SpellEffIndex effIndex) { PreventHitDefaultEffect(effIndex); if (GetCaster()->GetTypeId() != TYPEID_UNIT) return; Creature* creature = GetCaster()->ToCreature(); uint32 stage = creature->AI()->GetData(DATA_EXPERIMENT_STAGE); creature->AI()->SetData(DATA_EXPERIMENT_STAGE, stage ^ true); Creature* target = NULL; std::list<Creature*> creList; GetCreatureListWithEntryInGrid(creList, GetCaster(), NPC_ABOMINATION_WING_MAD_SCIENTIST_STALKER, 200.0f); // 2 of them are spawned at green place - weird trick blizz for (std::list<Creature*>::iterator itr = creList.begin(); itr != creList.end(); ++itr) { target = *itr; std::list<Creature*> tmp; GetCreatureListWithEntryInGrid(tmp, target, NPC_ABOMINATION_WING_MAD_SCIENTIST_STALKER, 10.0f); if ((!stage && tmp.size() > 1) || (stage && tmp.size() == 1)) break; } GetCaster()->CastSpell(target, uint32(GetSpellInfo()->GetEffect(stage)->CalcValue()), true, NULL, NULL, GetCaster()->GetGUID()); } void Register() override { OnEffectHitTarget += SpellEffectFn(spell_putricide_unstable_experiment_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const override { return new spell_putricide_unstable_experiment_SpellScript(); } }; class spell_putricide_ooze_eruption_searcher : public SpellScriptLoader { public: spell_putricide_ooze_eruption_searcher() : SpellScriptLoader("spell_putricide_ooze_eruption_searcher") { } class spell_putricide_ooze_eruption_searcher_SpellScript : public SpellScript { PrepareSpellScript(spell_putricide_ooze_eruption_searcher_SpellScript); void HandleDummy(SpellEffIndex /*effIndex*/) { if (GetHitUnit()->HasAura(SPELL_VOLATILE_OOZE_ADHESIVE)) { GetHitUnit()->RemoveAurasDueToSpell(SPELL_VOLATILE_OOZE_ADHESIVE, GetCaster()->GetGUID(), 0, AURA_REMOVE_BY_ENEMY_SPELL); GetCaster()->CastSpell(GetHitUnit(), SPELL_OOZE_ERUPTION, true); } } void Register() override { OnEffectHitTarget += SpellEffectFn(spell_putricide_ooze_eruption_searcher_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const override { return new spell_putricide_ooze_eruption_searcher_SpellScript(); } }; class spell_putricide_choking_gas_bomb : public SpellScriptLoader { public: spell_putricide_choking_gas_bomb() : SpellScriptLoader("spell_putricide_choking_gas_bomb") { } class spell_putricide_choking_gas_bomb_SpellScript : public SpellScript { PrepareSpellScript(spell_putricide_choking_gas_bomb_SpellScript); void HandleScript(SpellEffIndex /*effIndex*/) { uint32 skipIndex = urand(0, 2); for (SpellEffectInfo const* effect : GetSpellInfo()->GetEffectsForDifficulty(GetCaster()->GetMap()->GetDifficultyID())) { if (!effect || effect->EffectIndex == skipIndex) continue; uint32 spellId = uint32(effect->CalcValue()); GetCaster()->CastSpell(GetCaster(), spellId, true, NULL, NULL, GetCaster()->GetGUID()); } } void Register() override { OnEffectHitTarget += SpellEffectFn(spell_putricide_choking_gas_bomb_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const override { return new spell_putricide_choking_gas_bomb_SpellScript(); } }; class spell_putricide_unbound_plague : public SpellScriptLoader { public: spell_putricide_unbound_plague() : SpellScriptLoader("spell_putricide_unbound_plague") { } class spell_putricide_unbound_plague_SpellScript : public SpellScript { PrepareSpellScript(spell_putricide_unbound_plague_SpellScript); bool Validate(SpellInfo const* /*spell*/) override { if (!sSpellMgr->GetSpellInfo(SPELL_UNBOUND_PLAGUE)) return false; if (!sSpellMgr->GetSpellInfo(SPELL_UNBOUND_PLAGUE_SEARCHER)) return false; return true; } void FilterTargets(std::list<WorldObject*>& targets) { if (AuraEffect const* eff = GetCaster()->GetAuraEffect(SPELL_UNBOUND_PLAGUE_SEARCHER, EFFECT_0)) { if (eff->GetTickNumber() < 2) { targets.clear(); return; } } targets.remove_if(Trinity::UnitAuraCheck(true, SPELL_UNBOUND_PLAGUE)); Trinity::Containers::RandomResizeList(targets, 1); } void HandleScript(SpellEffIndex /*effIndex*/) { if (!GetHitUnit()) return; InstanceScript* instance = GetCaster()->GetInstanceScript(); if (!instance) return; if (!GetHitUnit()->HasAura(SPELL_UNBOUND_PLAGUE)) { if (Creature* professor = ObjectAccessor::GetCreature(*GetCaster(), instance->GetGuidData(DATA_PROFESSOR_PUTRICIDE))) { if (Aura* oldPlague = GetCaster()->GetAura(SPELL_UNBOUND_PLAGUE, professor->GetGUID())) { if (Aura* newPlague = professor->AddAura(SPELL_UNBOUND_PLAGUE, GetHitUnit())) { newPlague->SetMaxDuration(oldPlague->GetMaxDuration()); newPlague->SetDuration(oldPlague->GetDuration()); oldPlague->Remove(); GetCaster()->RemoveAurasDueToSpell(SPELL_UNBOUND_PLAGUE_SEARCHER); GetCaster()->CastSpell(GetCaster(), SPELL_PLAGUE_SICKNESS, true); GetCaster()->CastSpell(GetCaster(), SPELL_UNBOUND_PLAGUE_PROTECTION, true); professor->CastSpell(GetHitUnit(), SPELL_UNBOUND_PLAGUE_SEARCHER, true); } } } } } void Register() override { OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_putricide_unbound_plague_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ALLY); OnEffectHitTarget += SpellEffectFn(spell_putricide_unbound_plague_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const override { return new spell_putricide_unbound_plague_SpellScript(); } }; class spell_putricide_eat_ooze : public SpellScriptLoader { public: spell_putricide_eat_ooze() : SpellScriptLoader("spell_putricide_eat_ooze") { } class spell_putricide_eat_ooze_SpellScript : public SpellScript { PrepareSpellScript(spell_putricide_eat_ooze_SpellScript); void SelectTarget(std::list<WorldObject*>& targets) { if (targets.empty()) return; targets.sort(Trinity::ObjectDistanceOrderPred(GetCaster())); WorldObject* target = targets.front(); targets.clear(); targets.push_back(target); } void HandleScript(SpellEffIndex /*effIndex*/) { Creature* target = GetHitCreature(); if (!target) return; if (Aura* grow = target->GetAura(uint32(GetEffectValue()))) { if (grow->GetStackAmount() < 3) { target->RemoveAurasDueToSpell(SPELL_GROW_STACKER); target->RemoveAura(grow); target->DespawnOrUnsummon(1); } else grow->ModStackAmount(-3); } } void Register() override { OnEffectHitTarget += SpellEffectFn(spell_putricide_eat_ooze_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_putricide_eat_ooze_SpellScript::SelectTarget, EFFECT_0, TARGET_UNIT_DEST_AREA_ENTRY); } }; SpellScript* GetSpellScript() const override { return new spell_putricide_eat_ooze_SpellScript(); } }; class spell_putricide_mutated_plague : public SpellScriptLoader { public: spell_putricide_mutated_plague() : SpellScriptLoader("spell_putricide_mutated_plague") { } class spell_putricide_mutated_plague_AuraScript : public AuraScript { PrepareAuraScript(spell_putricide_mutated_plague_AuraScript); void HandleTriggerSpell(AuraEffect const* aurEff) { PreventDefaultAction(); Unit* caster = GetCaster(); if (!caster) return; uint32 triggerSpell = GetSpellInfo()->GetEffect(aurEff->GetEffIndex())->TriggerSpell; SpellInfo const* spell = sSpellMgr->AssertSpellInfo(triggerSpell); int32 damage = spell->GetEffect(EFFECT_0)->CalcValue(caster); float multiplier = 2.0f; if (GetTarget()->GetMap()->GetSpawnMode() & 1) multiplier = 3.0f; damage *= int32(pow(multiplier, GetStackAmount())); damage = int32(damage * 1.5f); GetTarget()->CastCustomSpell(triggerSpell, SPELLVALUE_BASE_POINT0, damage, GetTarget(), true, NULL, aurEff, GetCasterGUID()); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { uint32 healSpell = uint32(GetSpellInfo()->GetEffect(EFFECT_0)->CalcValue()); SpellInfo const* healSpellInfo = sSpellMgr->GetSpellInfo(healSpell); if (!healSpellInfo) return; int32 heal = healSpellInfo->GetEffect(EFFECT_0)->CalcValue() * GetStackAmount(); GetTarget()->CastCustomSpell(healSpell, SPELLVALUE_BASE_POINT0, heal, GetTarget(), true, NULL, NULL, GetCasterGUID()); } void Register() override { OnEffectPeriodic += AuraEffectPeriodicFn(spell_putricide_mutated_plague_AuraScript::HandleTriggerSpell, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL); AfterEffectRemove += AuraEffectRemoveFn(spell_putricide_mutated_plague_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL, AURA_EFFECT_HANDLE_REAL); } }; AuraScript* GetAuraScript() const override { return new spell_putricide_mutated_plague_AuraScript(); } }; class spell_putricide_mutation_init : public SpellScriptLoader { public: spell_putricide_mutation_init() : SpellScriptLoader("spell_putricide_mutation_init") { } class spell_putricide_mutation_init_SpellScript : public SpellScript { PrepareSpellScript(spell_putricide_mutation_init_SpellScript); SpellCastResult CheckRequirementInternal(SpellCustomErrors& extendedError) { InstanceScript* instance = GetExplTargetUnit()->GetInstanceScript(); if (!instance) return SPELL_FAILED_CANT_DO_THAT_RIGHT_NOW; Creature* professor = ObjectAccessor::GetCreature(*GetExplTargetUnit(), instance->GetGuidData(DATA_PROFESSOR_PUTRICIDE)); if (!professor) return SPELL_FAILED_CANT_DO_THAT_RIGHT_NOW; if (professor->AI()->GetData(DATA_PHASE) == PHASE_COMBAT_3 || !professor->IsAlive()) { extendedError = SPELL_CUSTOM_ERROR_ALL_POTIONS_USED; return SPELL_FAILED_CUSTOM_ERROR; } if (professor->AI()->GetData(DATA_ABOMINATION)) { extendedError = SPELL_CUSTOM_ERROR_TOO_MANY_ABOMINATIONS; return SPELL_FAILED_CUSTOM_ERROR; } return SPELL_CAST_OK; } SpellCastResult CheckRequirement() { if (!GetExplTargetUnit()) return SPELL_FAILED_BAD_TARGETS; if (GetExplTargetUnit()->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_TARGET_NOT_PLAYER; SpellCustomErrors extension = SPELL_CUSTOM_ERROR_NONE; SpellCastResult result = CheckRequirementInternal(extension); if (result != SPELL_CAST_OK) { Spell::SendCastResult(GetExplTargetUnit()->ToPlayer(), GetSpellInfo(), GetSpell()->m_SpellVisual, GetSpell()->m_castId, result, extension); return result; } return SPELL_CAST_OK; } void Register() override { OnCheckCast += SpellCheckCastFn(spell_putricide_mutation_init_SpellScript::CheckRequirement); } }; class spell_putricide_mutation_init_AuraScript : public AuraScript { PrepareAuraScript(spell_putricide_mutation_init_AuraScript); void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { uint32 spellId = 70311; if (GetTarget()->GetMap()->GetSpawnMode() & 1) spellId = 71503; GetTarget()->CastSpell(GetTarget(), spellId, true); } void Register() override { AfterEffectRemove += AuraEffectRemoveFn(spell_putricide_mutation_init_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL); } }; SpellScript* GetSpellScript() const override { return new spell_putricide_mutation_init_SpellScript(); } AuraScript* GetAuraScript() const override { return new spell_putricide_mutation_init_AuraScript(); } }; class spell_putricide_mutated_transformation_dismiss : public SpellScriptLoader { public: spell_putricide_mutated_transformation_dismiss() : SpellScriptLoader("spell_putricide_mutated_transformation_dismiss") { } class spell_putricide_mutated_transformation_dismiss_AuraScript : public AuraScript { PrepareAuraScript(spell_putricide_mutated_transformation_dismiss_AuraScript); void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { if (Vehicle* veh = GetTarget()->GetVehicleKit()) veh->RemoveAllPassengers(); } void Register() override { AfterEffectRemove += AuraEffectRemoveFn(spell_putricide_mutated_transformation_dismiss_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL, AURA_EFFECT_HANDLE_REAL); } }; AuraScript* GetAuraScript() const override { return new spell_putricide_mutated_transformation_dismiss_AuraScript(); } }; class spell_putricide_mutated_transformation : public SpellScriptLoader { public: spell_putricide_mutated_transformation() : SpellScriptLoader("spell_putricide_mutated_transformation") { } class spell_putricide_mutated_transformation_SpellScript : public SpellScript { PrepareSpellScript(spell_putricide_mutated_transformation_SpellScript); void HandleSummon(SpellEffIndex effIndex) { PreventHitDefaultEffect(effIndex); Unit* caster = GetOriginalCaster(); if (!caster) return; InstanceScript* instance = caster->GetInstanceScript(); if (!instance) return; Creature* putricide = ObjectAccessor::GetCreature(*caster, instance->GetGuidData(DATA_PROFESSOR_PUTRICIDE)); if (!putricide) return; if (putricide->AI()->GetData(DATA_ABOMINATION)) { if (Player* player = caster->ToPlayer()) Spell::SendCastResult(player, GetSpellInfo(), GetSpell()->m_SpellVisual, GetSpell()->m_castId, SPELL_FAILED_CUSTOM_ERROR, SPELL_CUSTOM_ERROR_TOO_MANY_ABOMINATIONS); return; } uint32 entry = uint32(GetSpellInfo()->GetEffect(effIndex)->MiscValue); SummonPropertiesEntry const* properties = sSummonPropertiesStore.LookupEntry(uint32(GetSpellInfo()->GetEffect(effIndex)->MiscValueB)); uint32 duration = uint32(GetSpellInfo()->GetDuration()); Position pos = caster->GetPosition(); TempSummon* summon = caster->GetMap()->SummonCreature(entry, pos, properties, duration, caster, GetSpellInfo()->Id); if (!summon || !summon->IsVehicle()) return; summon->CastSpell(summon, SPELL_ABOMINATION_VEHICLE_POWER_DRAIN, true); summon->CastSpell(summon, SPELL_MUTATED_TRANSFORMATION_DAMAGE, true); caster->CastSpell(summon, SPELL_MUTATED_TRANSFORMATION_NAME, true); caster->EnterVehicle(summon, 0); // VEHICLE_SPELL_RIDE_HARDCODED is used according to sniff, this is ok summon->SetCreatorGUID(caster->GetGUID()); putricide->AI()->JustSummoned(summon); } void Register() override { OnEffectHit += SpellEffectFn(spell_putricide_mutated_transformation_SpellScript::HandleSummon, EFFECT_0, SPELL_EFFECT_SUMMON); } }; SpellScript* GetSpellScript() const override { return new spell_putricide_mutated_transformation_SpellScript(); } }; class spell_putricide_mutated_transformation_dmg : public SpellScriptLoader { public: spell_putricide_mutated_transformation_dmg() : SpellScriptLoader("spell_putricide_mutated_transformation_dmg") { } class spell_putricide_mutated_transformation_dmg_SpellScript : public SpellScript { PrepareSpellScript(spell_putricide_mutated_transformation_dmg_SpellScript); void FilterTargetsInitial(std::list<WorldObject*>& targets) { if (Unit* owner = ObjectAccessor::GetUnit(*GetCaster(), GetCaster()->GetCreatorGUID())) targets.remove(owner); } void Register() override { OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_putricide_mutated_transformation_dmg_SpellScript::FilterTargetsInitial, EFFECT_0, TARGET_UNIT_SRC_AREA_ALLY); } }; SpellScript* GetSpellScript() const override { return new spell_putricide_mutated_transformation_dmg_SpellScript(); } }; class spell_putricide_regurgitated_ooze : public SpellScriptLoader { public: spell_putricide_regurgitated_ooze() : SpellScriptLoader("spell_putricide_regurgitated_ooze") { } class spell_putricide_regurgitated_ooze_SpellScript : public SpellScript { PrepareSpellScript(spell_putricide_regurgitated_ooze_SpellScript); // the only purpose of this hook is to fail the achievement void ExtraEffect(SpellEffIndex /*effIndex*/) { if (InstanceScript* instance = GetCaster()->GetInstanceScript()) instance->SetData(DATA_NAUSEA_ACHIEVEMENT, uint32(false)); } void Register() override { OnEffectHitTarget += SpellEffectFn(spell_putricide_regurgitated_ooze_SpellScript::ExtraEffect, EFFECT_0, SPELL_EFFECT_APPLY_AURA); } }; SpellScript* GetSpellScript() const override { return new spell_putricide_regurgitated_ooze_SpellScript(); } }; // Removes aura with id stored in effect value class spell_putricide_clear_aura_effect_value : public SpellScriptLoader { public: spell_putricide_clear_aura_effect_value() : SpellScriptLoader("spell_putricide_clear_aura_effect_value") { } class spell_putricide_clear_aura_effect_value_SpellScript : public SpellScript { PrepareSpellScript(spell_putricide_clear_aura_effect_value_SpellScript); void HandleScript(SpellEffIndex effIndex) { PreventHitDefaultEffect(effIndex); GetHitUnit()->RemoveAurasDueToSpell(GetEffectValue()); } void Register() override { OnEffectHitTarget += SpellEffectFn(spell_putricide_clear_aura_effect_value_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const override { return new spell_putricide_clear_aura_effect_value_SpellScript(); } }; // Stinky and Precious spell, it's here because its used for both (Festergut and Rotface "pets") class spell_stinky_precious_decimate : public SpellScriptLoader { public: spell_stinky_precious_decimate() : SpellScriptLoader("spell_stinky_precious_decimate") { } class spell_stinky_precious_decimate_SpellScript : public SpellScript { PrepareSpellScript(spell_stinky_precious_decimate_SpellScript); void HandleScript(SpellEffIndex /*effIndex*/) { if (GetHitUnit()->GetHealthPct() > float(GetEffectValue())) { uint32 newHealth = GetHitUnit()->GetMaxHealth() * uint32(GetEffectValue()) / 100; GetHitUnit()->SetHealth(newHealth); } } void Register() override { OnEffectHitTarget += SpellEffectFn(spell_stinky_precious_decimate_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const override { return new spell_stinky_precious_decimate_SpellScript(); } }; void AddSC_boss_professor_putricide() { new boss_professor_putricide(); new npc_volatile_ooze(); new npc_gas_cloud(); new spell_putricide_gaseous_bloat(); new spell_putricide_ooze_channel(); new spell_putricide_slime_puddle(); new spell_putricide_slime_puddle_aura(); new spell_putricide_unstable_experiment(); new spell_putricide_ooze_eruption_searcher(); new spell_putricide_choking_gas_bomb(); new spell_putricide_unbound_plague(); new spell_putricide_eat_ooze(); new spell_putricide_mutated_plague(); new spell_putricide_mutation_init(); new spell_putricide_mutated_transformation_dismiss(); new spell_putricide_mutated_transformation(); new spell_putricide_mutated_transformation_dmg(); new spell_putricide_regurgitated_ooze(); new spell_putricide_clear_aura_effect_value(); new spell_stinky_precious_decimate(); }
412
0.958596
1
0.958596
game-dev
MEDIA
0.994169
game-dev
0.899502
1
0.899502
pWn3d1337/Techguns2
3,129
src/main/java/techguns/gui/containers/ChargingStationContainer.java
package techguns.gui.containers; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.IItemHandler; import techguns.gui.widgets.SlotItemHandlerOutput; import techguns.gui.widgets.SlotMachineInput; import techguns.gui.widgets.SlotMachineUpgrade; import techguns.tileentities.ChargingStationTileEnt; import techguns.tileentities.operation.ItemStackHandlerPlus; public class ChargingStationContainer extends BasicMachineContainer { public static final int SLOT_INPUT_X=19; public static final int SLOT_OUTPUT_X=68; public static final int SLOTS_ROW1_Y=17; public static final int SLOT_UPGRADE_X=MetalPressContainer.SLOT_UPGRADE_X; public static final int SLOT_UPGRADE_Y=MetalPressContainer.SLOT_OUTPUTS_Y; ChargingStationTileEnt tile; public ChargingStationContainer(InventoryPlayer player, ChargingStationTileEnt ent) { super(player, ent); this.tile=ent; IItemHandler inventory = ent.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.SOUTH); if (inventory instanceof ItemStackHandlerPlus) { ItemStackHandlerPlus handler = (ItemStackHandlerPlus) inventory; this.addSlotToContainer(new SlotMachineInput(handler, ChargingStationTileEnt.SLOT_INPUT, SLOT_INPUT_X, SLOTS_ROW1_Y)); this.addSlotToContainer(new SlotItemHandlerOutput(inventory,ChargingStationTileEnt.SLOT_OUTPUT, SLOT_OUTPUT_X, SLOTS_ROW1_Y)); this.addSlotToContainer(new SlotMachineUpgrade(handler, ChargingStationTileEnt.SLOT_UPGRADE, SLOT_UPGRADE_X, SLOT_UPGRADE_Y)); } this.addPlayerInventorySlots(player); } @Override public ItemStack transferStackInSlot(EntityPlayer ply, int id) { int HIGHEST_SLOT=ChargingStationTileEnt.SLOT_UPGRADE; //index +1 int MAXSLOTS = HIGHEST_SLOT+36+1; //36 = inventory size ItemStack stack = ItemStack.EMPTY; Slot slot = (Slot) this.inventorySlots.get(id); if(slot.getHasStack()){ ItemStack stack1 = slot.getStack(); stack=stack1.copy(); if (!stack.isEmpty()){ if (id >=0 && id<=HIGHEST_SLOT){ if (!this.mergeItemStack(stack1, HIGHEST_SLOT+1, MAXSLOTS, false)) { return ItemStack.EMPTY; } slot.onSlotChange(stack1, stack); } else if (id >HIGHEST_SLOT && id <MAXSLOTS){ int validslot = tile.getValidSlotForItemInMachine(stack1); //System.out.println("put it in slot"+validslot); if (validslot >=0){ if(!this.mergeItemStack(stack1, validslot, validslot+1, false)){ return ItemStack.EMPTY; } slot.onSlotChange(stack1, stack); } else { return ItemStack.EMPTY; } } if (stack1.getCount() == 0) { slot.putStack(ItemStack.EMPTY); } else { slot.onSlotChanged(); } if (stack1.getCount() == stack.getCount()) { return ItemStack.EMPTY; } slot.onTake(ply, stack1); } } return stack; } }
412
0.910543
1
0.910543
game-dev
MEDIA
0.995466
game-dev
0.978041
1
0.978041
brainsynder-Dev/SimplePets
4,010
nms/version-1.20.3/src/simplepets/brainsynder/nms/entity/list/EntityCatPet.java
/* * Copyright 2024 * BSDevelopment <https://bsdevelopment.org> */ package simplepets.brainsynder.nms.entity.list; import lib.brainsynder.nbt.StorageTagCompound; import lib.brainsynder.utils.DyeColorWrapper; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.animal.CatVariant; import simplepets.brainsynder.api.entity.passive.IEntityCatPet; import simplepets.brainsynder.api.pet.PetType; import simplepets.brainsynder.api.user.PetUser; import simplepets.brainsynder.api.wrappers.CatType; import simplepets.brainsynder.nms.entity.EntityTameablePet; import simplepets.brainsynder.nms.utils.PetDataAccess; /** * NMS: {@link net.minecraft.world.entity.animal.Cat} */ public class EntityCatPet extends EntityTameablePet implements IEntityCatPet { private static final EntityDataAccessor<CatVariant> TYPE = SynchedEntityData.defineId(EntityCatPet.class, EntityDataSerializers.CAT_VARIANT); private static final EntityDataAccessor<Boolean> SLEEPING_WITH_OWNER = SynchedEntityData.defineId(EntityCatPet.class, EntityDataSerializers.BOOLEAN); private static final EntityDataAccessor<Boolean> HEAD_UP = SynchedEntityData.defineId(EntityCatPet.class, EntityDataSerializers.BOOLEAN); private static final EntityDataAccessor<Integer> COLLAR_COLOR = SynchedEntityData.defineId(EntityCatPet.class, EntityDataSerializers.INT); public EntityCatPet(PetType type, PetUser user) { super(EntityType.CAT, type, user); } @Override public void populateDataAccess(PetDataAccess dataAccess) { super.populateDataAccess(dataAccess); dataAccess.define(TYPE, BuiltInRegistries.CAT_VARIANT.getOrThrow(CatVariant.TABBY)); dataAccess.define(SLEEPING_WITH_OWNER, false); dataAccess.define(HEAD_UP, false); dataAccess.define(COLLAR_COLOR, DyeColorWrapper.WHITE.getWoolData()); } @Override public StorageTagCompound asCompound() { StorageTagCompound compound = super.asCompound(); compound.setEnum("type", getCatType()); compound.setEnum("collar", getCollarColor()); compound.setBoolean("sleeping", isPetSleeping()); compound.setBoolean("head_up", isHeadUp()); return compound; } @Override public void applyCompound(StorageTagCompound object) { if (object.hasKey("type")) setCatType(object.getEnum("type", CatType.class, CatType.TABBY)); if (object.hasKey("collar")) setCollarColor(object.getEnum("collar", DyeColorWrapper.class, DyeColorWrapper.WHITE)); if (object.hasKey("sleeping")) setPetSleeping(object.getBoolean("sleeping", false)); if (object.hasKey("head_up")) setHeadUp(object.getBoolean("head_up", false)); super.applyCompound(object); } @Override public CatType getCatType() { return CatType.getByID(BuiltInRegistries.CAT_VARIANT.getId(entityData.get(TYPE))); } @Override public void setCatType(CatType type) { entityData.set(TYPE, BuiltInRegistries.CAT_VARIANT.byId(type.ordinal())); } @Override public DyeColorWrapper getCollarColor() { return DyeColorWrapper.getByWoolData((byte) ((int) entityData.get(COLLAR_COLOR))); } @Override public void setCollarColor(DyeColorWrapper color) { entityData.set(COLLAR_COLOR, color.ordinal()); } @Override public boolean isHeadUp() { return entityData.get(HEAD_UP); } @Override public void setHeadUp(boolean value) { entityData.set(HEAD_UP, value); } @Override public boolean isPetSleeping() { return entityData.get(SLEEPING_WITH_OWNER); } @Override public void setPetSleeping(boolean sleeping) { entityData.set(SLEEPING_WITH_OWNER, sleeping); } }
412
0.858324
1
0.858324
game-dev
MEDIA
0.951778
game-dev
0.825544
1
0.825544
dotnet/dotnet
4,365
src/runtime/src/coreclr/md/ceefilegen/ceegentokenmapper.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. //***************************************************************************** // CeeGenTokenMapper.cpp // // // This helper class tracks mapped tokens from their old value to the new value // which can happen when the data is optimized on save. // //***************************************************************************** #include "stdafx.h" #include "ceegentokenmapper.h" //***************************************************************************** // At this point, only a select set of token values are stored for remap. // If others should become required, this needs to get updated. //***************************************************************************** int CeeGenTokenMapper::IndexForType(mdToken tk) { #ifdef CEEGEN_TRACKED_TOKEN #undef CEEGEN_TRACKED_TOKEN #endif #define CEEGEN_TRACKED_TOKEN(type) case INDEX_OF_TYPE(mdt ## type): return (tkix ## type); int iType = INDEX_OF_TYPE(TypeFromToken(tk)); switch(iType) { CEEGEN_TRACKED_TOKENS() } return (-1); } //***************************************************************************** // Called by the meta data engine when a token is remapped to a new location. // This value is recorded in the m_rgMap array based on type and rid of the // from token value. //***************************************************************************** HRESULT STDMETHODCALLTYPE CeeGenTokenMapper::Map( mdToken tkFrom, mdToken tkTo) { HRESULT hr = S_OK; mdToken *pToken = NULL; ULONG ridFrom = 0; TOKENMAP *pMap = NULL; if ( IndexForType(tkFrom) == -1 ) { // It is a type that we are not tracking, such as mdtProperty or mdtEvent, // just return S_OK. goto ErrExit; } _ASSERTE(IndexForType(tkFrom) < GetMaxMapSize()); _ASSERTE(IndexForType(tkTo) != -1 && IndexForType(tkTo) < GetMaxMapSize()); ridFrom = RidFromToken(tkFrom); pMap = &m_rgMap[IndexForType(tkFrom)]; // If there isn't enough entries, fill out array up to the count // and mark the token to nil so we know there is no valid data yet. if ((ULONG) pMap->Count() <= ridFrom) { for (int i=ridFrom - pMap->Count() + 1; i; i--) { pToken = pMap->Append(); if (!pToken) break; *pToken = mdTokenNil; } _ASSERTE(!pToken || pMap->Get(ridFrom) == pToken); } else pToken = pMap->Get(ridFrom); IfNullGo(pToken); *pToken = tkTo; ErrExit: return hr; } //***************************************************************************** // Check the given token to see if it has moved to a new location. If so, // return true and give back the new token. //***************************************************************************** int CeeGenTokenMapper::HasTokenMoved( mdToken tkFrom, mdToken &tkTo) { mdToken tk; int i = IndexForType(tkFrom); if(i == -1) return false; _ASSERTE(i < GetMaxMapSize()); TOKENMAP *pMap = &m_rgMap[i]; // Assume nothing moves. tkTo = tkFrom; // If the array is smaller than the index, can't have moved. if ((ULONG) pMap->Count() <= RidFromToken(tkFrom)) return (false); // If the entry is set to 0, then nothing there. tk = *pMap->Get(RidFromToken(tkFrom)); if (tk == mdTokenNil) return (false); // Had to move to a new location, return that new location. tkTo = tk; return (true); } //***************************************************************************** // Hand out a copy of the meta data information. //***************************************************************************** HRESULT CeeGenTokenMapper::GetMetaData( IMetaDataImport **ppIImport) { if (m_pIImport) return (m_pIImport->QueryInterface(IID_IMetaDataImport, (PVOID *) ppIImport)); *ppIImport = 0; return E_FAIL; } HRESULT STDMETHODCALLTYPE CeeGenTokenMapper::QueryInterface(REFIID iid, PVOID *ppIUnk) { if (iid == IID_IUnknown || iid == IID_IMapToken) *ppIUnk = static_cast<IMapToken*>(this); else { *ppIUnk = 0; return (E_NOINTERFACE); } AddRef(); return (S_OK); }
412
0.941307
1
0.941307
game-dev
MEDIA
0.167998
game-dev
0.867613
1
0.867613
Deadrik/TFCraft
4,186
src/Common/com/bioxx/tfc/Blocks/Terrain/BlockClay.java
package com.bioxx.tfc.Blocks.Terrain; import java.util.ArrayList; import java.util.List; import java.util.Random; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import com.bioxx.tfc.Reference; import com.bioxx.tfc.Blocks.BlockTerra; import com.bioxx.tfc.Core.TFCTabs; import com.bioxx.tfc.api.TFCItems; import com.bioxx.tfc.api.Constant.Global; public class BlockClay extends BlockTerra { protected IIcon[] dirtTexture; protected int textureOffset; public BlockClay(int texOff) { super(Material.clay); this.setCreativeTab(TFCTabs.TFC_BUILDING); textureOffset = texOff; } @Override public void getSubBlocks(Item item, CreativeTabs tab, List list) { // Change to false if this block should not be added to the creative tab Boolean addToCreative = true; if(addToCreative) { int count; if(textureOffset == 0) count = 16; else count = Global.STONE_ALL.length - 16; for(int i = 0; i < count; i++) list.add(new ItemStack(item, 1, i)); } } @Override public void registerBlockIcons(IIconRegister registerer) { int count = (textureOffset == 0 ? 16 : Global.STONE_ALL.length - 16); dirtTexture = new IIcon[count]; for(int i = 0; i < count; i++) dirtTexture[i] = registerer.registerIcon(Reference.MOD_ID + ":" + "clay/Clay " + Global.STONE_ALL[i + textureOffset]); } /** * Retrieves the block texture to use based on the display side. Args: iBlockAccess, x, y, z, side */ @Override public IIcon getIcon(IBlockAccess bAccess, int x, int y, int z, int side) { int meta = bAccess.getBlockMetadata(x, y, z); if(meta >= dirtTexture.length) return dirtTexture[dirtTexture.length - 1]; return dirtTexture[meta]; } /** * From the specified side and block metadata retrieves the blocks texture. Args: side, metadata */ @Override public IIcon getIcon(int side, int meta) { if(meta >= dirtTexture.length) return dirtTexture[dirtTexture.length - 1]; return dirtTexture[meta]; } /** * Returns the items to drop on destruction. */ @Override public Item getItemDropped(int metadata, Random rand, int fortune) { return TFCItems.clayBall; } /** * Returns the quantity of items to drop on block destruction. */ @Override public int quantityDropped(Random rand) { return rand.nextInt(3) + 1; } @Override public int damageDropped(int dmg) { return dmg; } /** * The reason for overriding getDrops is because we only want to drop the clay item with meta 0, * but also need damageDropped to return the correct meta for localization purposes. */ @Override public ArrayList<ItemStack> getDrops(World world, int x, int y, int z, int metadata, int fortune) { ArrayList<ItemStack> ret = new ArrayList<ItemStack>(); int count = this.quantityDropped(world.rand); Item item = getItemDropped(metadata, world.rand, fortune); for(int i = 0; i < count; i++) ret.add(new ItemStack(item, 1, 0)); return ret; } /*public void getCollidingBoundingBoxes(World world, int i, int j, int k, AxisAlignedBB par5AxisAlignedBB, ArrayList par6ArrayList) { if((!world.isBlockOpaqueCube(i+1, j, k) || !world.isBlockOpaqueCube(i-1, j, k) || !world.isBlockOpaqueCube(i, j, k+1) || !world.isBlockOpaqueCube(i, j, k-1)) && !world.isBlockOpaqueCube(i, j+1, k)) { par6ArrayList.add(AxisAlignedBB.getBoundingBoxFromPool(i, j, k,i +1,j + 0.5f,k + 1)); double minX = 0.25; double minZ = 0.25; double maxX = 0.75; double maxZ = 0.75; if(!world.isBlockOpaqueCube(i+1, j, k)) maxX = 0.5; if(!world.isBlockOpaqueCube(i-1, j, k)) minX = 0.5; if(!world.isBlockOpaqueCube(i, j, k+1)) maxZ = 0.5; if(!world.isBlockOpaqueCube(i, j, k-1)) minZ = 0.5; par6ArrayList.add(AxisAlignedBB.getBoundingBoxFromPool(i + minX, j + 0.5, k + minZ, i + maxX, j + 1, k + maxZ)); } else par6ArrayList.add(AxisAlignedBB.getBoundingBoxFromPool(i, j, k,i + 1,j + 1,k +1)); }*/ }
412
0.854955
1
0.854955
game-dev
MEDIA
0.98282
game-dev
0.881333
1
0.881333
Alexejhero/Fragmented
13,367
Packages/FMOD/FMOD/addons/ResonanceAudio/Scripts/FmodResonanceAudio.cs
// Copyright 2017 Google Inc. All rights reserved. // // 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. using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using FMODUnity; namespace FMODUnityResonance { /// This is the main Resonance Audio class that communicates with the FMOD Unity integration. Native /// functions of the system can only be called through this class to preserve the internal system /// functionality. public static class FmodResonanceAudio { /// Maximum allowed gain value in decibels. public const float MaxGainDb = 24.0f; /// Minimum allowed gain value in decibels. public const float MinGainDb = -24.0f; /// Maximum allowed reverb brightness modifier value. public const float MaxReverbBrightness = 1.0f; /// Minimum allowed reverb brightness modifier value. public const float MinReverbBrightness = -1.0f; /// Maximum allowed reverb time modifier value. public const float MaxReverbTime = 3.0f; /// Maximum allowed reflectivity multiplier of a room surface material. public const float MaxReflectivity = 2.0f; // Right-handed to left-handed matrix converter (and vice versa). private static readonly Matrix4x4 flipZ = Matrix4x4.Scale(new Vector3(1, 1, -1)); // Get a handle to the Resonance Audio Listener FMOD Plugin. private static readonly string listenerPluginName = "Resonance Audio Listener"; // Size of |RoomProperties| struct in bytes. private static readonly int roomPropertiesSize = FMOD.MarshalHelper.SizeOf(typeof(RoomProperties)); // Plugin data parameter index for the room properties. private static readonly int roomPropertiesIndex = 1; // Boundaries instance to be used in room detection logic. private static Bounds bounds = new Bounds(Vector3.zero, Vector3.zero); // Container to store the currently active rooms in the scene. private static List<FmodResonanceAudioRoom> enabledRooms = new List<FmodResonanceAudioRoom>(); // Current listener position. private static FMOD.VECTOR listenerPositionFmod = new FMOD.VECTOR(); // FMOD Resonance Audio Listener Plugin. private static FMOD.DSP listenerPlugin; /// Updates the room effects of the environment with given |room| properties. /// @note This should only be called from the main Unity thread. public static void UpdateAudioRoom(FmodResonanceAudioRoom room, bool roomEnabled) { // Update the enabled rooms list. if (roomEnabled) { if (!enabledRooms.Contains(room)) { enabledRooms.Add(room); } } else { enabledRooms.Remove(room); } // Update the current room effects to be applied. if (enabledRooms.Count > 0) { FmodResonanceAudioRoom currentRoom = enabledRooms[enabledRooms.Count - 1]; RoomProperties roomProperties = GetRoomProperties(currentRoom); // Pass the room properties into a pointer. IntPtr roomPropertiesPtr = Marshal.AllocHGlobal(roomPropertiesSize); Marshal.StructureToPtr(roomProperties, roomPropertiesPtr, false); ListenerPlugin.setParameterData(roomPropertiesIndex, GetBytes(roomPropertiesPtr, roomPropertiesSize)); Marshal.FreeHGlobal(roomPropertiesPtr); } else { // Set the room properties to a null room, which will effectively disable the room effects. ListenerPlugin.setParameterData(roomPropertiesIndex, GetBytes(IntPtr.Zero, 0)); } } /// Returns whether the listener is currently inside the given |room| boundaries. public static bool IsListenerInsideRoom(FmodResonanceAudioRoom room) { // Compute the room position relative to the listener. FMOD.VECTOR unused; RuntimeManager.CoreSystem.get3DListenerAttributes(0, out listenerPositionFmod, out unused, out unused, out unused); Vector3 listenerPosition = new Vector3(listenerPositionFmod.x, listenerPositionFmod.y, listenerPositionFmod.z); Vector3 relativePosition = listenerPosition - room.transform.position; Quaternion rotationInverse = Quaternion.Inverse(room.transform.rotation); // Set the size of the room as the boundary and return whether the listener is inside. bounds.size = Vector3.Scale(room.transform.lossyScale, room.Size); return bounds.Contains(rotationInverse * relativePosition); } [StructLayout(LayoutKind.Sequential)] private struct RoomProperties { // Center position of the room in world space. public float PositionX; public float PositionY; public float PositionZ; // Rotation (quaternion) of the room in world space. public float RotationX; public float RotationY; public float RotationZ; public float RotationW; // Size of the shoebox room in world space. public float DimensionsX; public float DimensionsY; public float DimensionsZ; // Material name of each surface of the shoebox room. public FmodResonanceAudioRoom.SurfaceMaterial MaterialLeft; public FmodResonanceAudioRoom.SurfaceMaterial MaterialRight; public FmodResonanceAudioRoom.SurfaceMaterial MaterialBottom; public FmodResonanceAudioRoom.SurfaceMaterial MaterialTop; public FmodResonanceAudioRoom.SurfaceMaterial MaterialFront; public FmodResonanceAudioRoom.SurfaceMaterial MaterialBack; // User defined uniform scaling factor for reflectivity. This parameter has no effect when set // to 1.0f. public float ReflectionScalar; // User defined reverb tail gain multiplier. This parameter has no effect when set to 0.0f. public float ReverbGain; // Adjusts the reverberation time across all frequency bands. RT60 values are multiplied by this // factor. Has no effect when set to 1.0f. public float ReverbTime; // Controls the slope of a line from the lowest to the highest RT60 values (increases high // frequency RT60s when positive, decreases when negative). Has no effect when set to 0.0f. public float ReverbBrightness; }; // Returns the FMOD Resonance Audio Listener Plugin. private static FMOD.DSP ListenerPlugin { get { if (!listenerPlugin.hasHandle()) { listenerPlugin = Initialize(); } return listenerPlugin; } } // Converts given |db| value to its amplitude equivalent where 'dB = 20 * log10(amplitude)'. private static float ConvertAmplitudeFromDb(float db) { return Mathf.Pow(10.0f, 0.05f * db); } // Converts given |position| and |rotation| from Unity space to audio space. private static void ConvertAudioTransformFromUnity(ref Vector3 position, ref Quaternion rotation) { // Compose the transformation matrix. Matrix4x4 transformMatrix = Matrix4x4.TRS(position, rotation, Vector3.one); // Convert the transformation matrix from left-handed to right-handed. transformMatrix = flipZ * transformMatrix * flipZ; // Update |position| and |rotation| respectively. position = transformMatrix.GetColumn(3); rotation = Quaternion.LookRotation(transformMatrix.GetColumn(2), transformMatrix.GetColumn(1)); } // Returns a byte array of |length| created from |ptr|. private static byte[] GetBytes(IntPtr ptr, int length) { if (ptr != IntPtr.Zero) { byte[] byteArray = new byte[length]; Marshal.Copy(ptr, byteArray, 0, length); return byteArray; } // Return an empty array if the pointer is null. return new byte[1]; } // Returns room properties of the given |room|. private static RoomProperties GetRoomProperties(FmodResonanceAudioRoom room) { RoomProperties roomProperties; Vector3 position = room.transform.position; Quaternion rotation = room.transform.rotation; Vector3 scale = Vector3.Scale(room.transform.lossyScale, room.Size); ConvertAudioTransformFromUnity(ref position, ref rotation); roomProperties.PositionX = position.x; roomProperties.PositionY = position.y; roomProperties.PositionZ = position.z; roomProperties.RotationX = rotation.x; roomProperties.RotationY = rotation.y; roomProperties.RotationZ = rotation.z; roomProperties.RotationW = rotation.w; roomProperties.DimensionsX = scale.x; roomProperties.DimensionsY = scale.y; roomProperties.DimensionsZ = scale.z; roomProperties.MaterialLeft = room.LeftWall; roomProperties.MaterialRight = room.RightWall; roomProperties.MaterialBottom = room.Floor; roomProperties.MaterialTop = room.Ceiling; roomProperties.MaterialFront = room.FrontWall; roomProperties.MaterialBack = room.BackWall; roomProperties.ReverbGain = ConvertAmplitudeFromDb(room.ReverbGainDb); roomProperties.ReverbTime = room.ReverbTime; roomProperties.ReverbBrightness = room.ReverbBrightness; roomProperties.ReflectionScalar = room.Reflectivity; return roomProperties; } // Initializes and returns the FMOD Resonance Audio Listener Plugin. private static FMOD.DSP Initialize() { // Search through all busses on in banks. int numBanks = 0; FMOD.DSP dsp = new FMOD.DSP(); FMOD.Studio.Bank[] banks = null; RuntimeManager.StudioSystem.getBankCount(out numBanks); RuntimeManager.StudioSystem.getBankList(out banks); for (int currentBank = 0; currentBank < numBanks; ++currentBank) { int numBusses = 0; FMOD.Studio.Bus[] busses = null; banks[currentBank].getBusCount(out numBusses); banks[currentBank].getBusList(out busses); for (int currentBus = 0; currentBus < numBusses; ++currentBus) { // Make sure the channel group of the current bus is assigned properly. string busPath = null; busses[currentBus].getPath(out busPath); RuntimeManager.StudioSystem.getBus(busPath, out busses[currentBus]); busses[currentBus].lockChannelGroup(); RuntimeManager.StudioSystem.flushCommands(); FMOD.ChannelGroup channelGroup; busses[currentBus].getChannelGroup(out channelGroup); if (channelGroup.hasHandle()) { int numDsps = 0; channelGroup.getNumDSPs(out numDsps); for (int currentDsp = 0; currentDsp < numDsps; ++currentDsp) { channelGroup.getDSP(currentDsp, out dsp); string dspNameSb; int unusedInt = 0; uint unusedUint = 0; dsp.getInfo(out dspNameSb, out unusedUint, out unusedInt, out unusedInt, out unusedInt); if (dspNameSb.ToString().Equals(listenerPluginName) && dsp.hasHandle()) { return dsp; } } } busses[currentBus].unlockChannelGroup(); } } RuntimeUtils.DebugLogError(listenerPluginName + " not found in the FMOD project."); return dsp; } } }
412
0.94117
1
0.94117
game-dev
MEDIA
0.367187
game-dev
0.951613
1
0.951613
jawadbappy/forgery_localization_HLED
1,844
Radon/fftw-3.3.6-pl2/api/plan-many-dft-c2r.c
/* * Copyright (c) 2003, 2007-14 Matteo Frigo * Copyright (c) 2003, 2007-14 Massachusetts Institute of Technology * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include "api.h" #include "rdft.h" X(plan) X(plan_many_dft_c2r)(int rank, const int *n, int howmany, C *in, const int *inembed, int istride, int idist, R *out, const int *onembed, int ostride, int odist, unsigned flags) { R *ri, *ii; int *nfi, *nfo; int inplace; X(plan) p; if (!X(many_kosherp)(rank, n, howmany)) return 0; EXTRACT_REIM(FFT_SIGN, in, &ri, &ii); inplace = out == ri; if (!inplace) flags |= FFTW_DESTROY_INPUT; p = X(mkapiplan)( 0, flags, X(mkproblem_rdft2_d_3pointers)( X(mktensor_rowmajor)( rank, n, X(rdft2_pad)(rank, n, inembed, inplace, 1, &nfi), X(rdft2_pad)(rank, n, onembed, inplace, 0, &nfo), 2 * istride, ostride), X(mktensor_1d)(howmany, 2 * idist, odist), TAINT_UNALIGNED(out, flags), TAINT_UNALIGNED(ri, flags), TAINT_UNALIGNED(ii, flags), HC2R)); X(ifree0)(nfi); X(ifree0)(nfo); return p; }
412
0.580292
1
0.580292
game-dev
MEDIA
0.695881
game-dev
0.769906
1
0.769906